diff --git a/.clang-tidy b/.clang-tidy index a7a3b20..03866ef 100644 --- a/.clang-tidy +++ b/.clang-tidy
@@ -1,6 +1,9 @@ --- # TODO(crbug.com/1282228): reenable google-readability-casting once it no # longer has as many false-positives. + # TODO(crbug.com/1406869): reenable modernize-use-default-member-init once + # C++20 is everywhere; it recommends using default member init for bit fields, + # which is C++20-only. Checks: '-*, bugprone-argument-comment, bugprone-assert-side-effect, @@ -24,7 +27,6 @@ modernize-replace-random-shuffle, modernize-shrink-to-fit, modernize-use-bool-literals, - modernize-use-default-member-init, modernize-use-emplace, modernize-use-equals-default, modernize-use-equals-delete,
diff --git a/DEPS b/DEPS index a95e153..6681b95 100644 --- a/DEPS +++ b/DEPS
@@ -249,7 +249,7 @@ # luci-go CIPD package version. # Make sure the revision is uploaded by infra-packagers builder. # https://ci.chromium.org/p/infra-internal/g/infra-packagers/console - 'luci_go': 'git_revision:c53344de69401cd5d608484b37cd6545f328406c', + 'luci_go': 'git_revision:6ac770095bc0e289138f6f29aa91ff2f4886b81c', # This can be overridden, e.g. with custom_vars, to build clang from HEAD # instead of downloading the prebuilt pinned revision. @@ -300,15 +300,15 @@ # 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': '048bc558980d2e2f6f29d7ecc2d5adf9215f5a6b', + 'skia_revision': 'cf0dd295c1bb396063efc8fed2accbca938ea38e', # 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': '4b3e7386ed71796fd768a5e99ee5fbbe25a0fc97', + 'v8_revision': '7c8dc6d97acbc320d7c994abb0f067f02982badc', # 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': '70a8d65e6f8585b376e391045446df2c9fbd0cec', + 'angle_revision': 'b526112dafd79c1eebc72c392d1b180282206370', # Three lines of non-changing comments so that # the commit queue can handle CLs rolling SwiftShader # and whatever else without interference from each other. @@ -316,7 +316,7 @@ # Three lines of non-changing comments so that # the commit queue can handle CLs rolling PDFium # and whatever else without interference from each other. - 'pdfium_revision': '4c16842f61a150b40c4dd104775dec19225ae7fe', + 'pdfium_revision': 'e60fa0d7d7733b23c444daa048dd509972d68cfe', # Three lines of non-changing comments so that # the commit queue can handle CLs rolling BoringSSL # and whatever else without interference from each other. @@ -327,7 +327,7 @@ # Three lines of non-changing comments so that # the commit queue can handle CLs rolling Fuchsia sdk # and whatever else without interference from each other. - 'fuchsia_version': 'version:12.20230511.4.1', + 'fuchsia_version': 'version:12.20230512.2.1', # Three lines of non-changing comments so that # the commit queue can handle CLs rolling google-toolbox-for-mac # and whatever else without interference from each other. @@ -427,7 +427,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': 'b0726080f4cabfb34500e8f5739dc229cc6ef849', + 'dawn_revision': '9ae8ed2f62491423d28302927f35d5add9caf2ab', # Three lines of non-changing comments so that # the commit queue can handle CLs rolling feed # and whatever else without interference from each other. @@ -792,7 +792,7 @@ 'src/clank': { 'url': Var('chrome_git') + '/clank/internal/apps.git' + '@' + - 'a78acad1e38ffbe645f0b3fe942a57d5065e585d', + 'cdebce11d28b49f1806558dfe4ff16942f056434', 'condition': 'checkout_android and checkout_src_internal', }, @@ -1030,7 +1030,7 @@ 'packages': [ { 'package': 'chromium/third_party/android_build_tools/bundletool', - 'version': 'xnKkaX2u7XVfsUzExic0KW3jYMINpI16Ll9QYESBoI8C', + 'version': 'Xt6znihJ60Ym06wn163_2B0HOt2tNsV5fVy-BpYJZcMC', }, ], 'condition': 'checkout_android', @@ -1216,13 +1216,13 @@ }, 'src/third_party/depot_tools': - Var('chromium_git') + '/chromium/tools/depot_tools.git' + '@' + 'f949f4c1675420f581441ffa243f6788c875cbbf', + Var('chromium_git') + '/chromium/tools/depot_tools.git' + '@' + 'a1e578320b09a600894b6b11bc4e7d5f31627c6c', 'src/third_party/devtools-frontend/src': Var('chromium_git') + '/devtools/devtools-frontend' + '@' + Var('devtools_frontend_revision'), 'src/third_party/devtools-frontend-internal': { - 'url': Var('chrome_git') + '/devtools/devtools-internal.git' + '@' + '8a5d92f504dd0be47e8d4aaf25dc3cb697075908', + 'url': Var('chrome_git') + '/devtools/devtools-internal.git' + '@' + '41701d83415488258b46d595e54114137f9c5038', 'condition': 'checkout_src_internal', }, @@ -1689,7 +1689,7 @@ Var('pdfium_git') + '/pdfium.git' + '@' + Var('pdfium_revision'), 'src/third_party/perfetto': - Var('android_git') + '/platform/external/perfetto.git' + '@' + 'edd765afa06f3b0c0d117e9e1e7ab12b441ed765', + Var('android_git') + '/platform/external/perfetto.git' + '@' + 'a6abd9944464ff392ea57c6e3e82784e603987ec', 'src/third_party/perl': { 'url': Var('chromium_git') + '/chromium/deps/perl.git' + '@' + '6f3e5028eb65d0b4c5fdd792106ac4c84eee1eb3', @@ -1871,7 +1871,7 @@ Var('chromium_git') + '/external/khronosgroup/webgl.git' + '@' + 'd1b65aa5a88f6efd900604dfcda840154e9f16e2', 'src/third_party/webgpu-cts/src': - Var('chromium_git') + '/external/github.com/gpuweb/cts.git' + '@' + '4fd26fe4abb31b74e8b5cc9ea6ff0e36970eb7bf', + Var('chromium_git') + '/external/github.com/gpuweb/cts.git' + '@' + '13476ef7408a828a641dce55c363a085eff8e228', 'src/third_party/webrtc': Var('webrtc_git') + '/src.git' + '@' + 'a79bc6ee47446865a229e69d835ddcd0b9d39c8e', @@ -1964,7 +1964,7 @@ Var('chromium_git') + '/v8/v8.git' + '@' + Var('v8_revision'), 'src-internal': { - 'url': Var('chrome_git') + '/chrome/src-internal.git@baf76316f79a5e8efb0a2dbfe4d56fa6ede6455d', + 'url': Var('chrome_git') + '/chrome/src-internal.git@2b923545e8362ee0c006529ebc4c8763165fd7dc', 'condition': 'checkout_src_internal', }, @@ -2005,7 +2005,7 @@ 'packages': [ { 'package': 'chromeos_internal/apps/media_app/app', - 'version': 'bPs5vp1jOH4akpgvlB8bb7dXkH6hr8V2_lfmxpKfI9QC', + 'version': 'ZqoJl676iJHbSO1RK4MmZKjHy0b8ttQIE7p-4VDh3EcC', }, ], 'condition': 'checkout_chromeos and checkout_src_internal', @@ -4032,7 +4032,7 @@ # grepping. 'src/chrome/installer/mac/internal': { 'url': Var('chrome_git') + '/chrome/installer/mac/internal.git' + '@' + - '0ba5f35b46b9f1aece303b3ce5d614bee9dc42f8', + 'bfca440a36e60367df7082099e6a0b8908685a16', 'condition': 'checkout_src_internal', }, @@ -4163,7 +4163,7 @@ 'src/ios_internal': { 'url': '{chrome_git}/chrome/ios_internal.git' + '@' + - '1ec92ade73656e4bc4561102182e470c211879f1', + '6e7940481da07fbbb0147d58ddfff81ce33ff680', 'condition': 'checkout_ios and checkout_src_internal', },
diff --git a/ash/BUILD.gn b/ash/BUILD.gn index 70d1241..6828828f 100644 --- a/ash/BUILD.gn +++ b/ash/BUILD.gn
@@ -358,6 +358,8 @@ "capture_mode/capture_window_observer.h", "capture_mode/folder_selection_dialog_controller.cc", "capture_mode/folder_selection_dialog_controller.h", + "capture_mode/game_capture_bar_view.cc", + "capture_mode/game_capture_bar_view.h", "capture_mode/key_combo_view.cc", "capture_mode/key_combo_view.h", "capture_mode/key_item_view.cc",
diff --git a/ash/ash_strings.grd b/ash/ash_strings.grd index fbc100b..81d456a8 100644 --- a/ash/ash_strings.grd +++ b/ash/ash_strings.grd
@@ -5763,6 +5763,9 @@ <message name="IDS_ASH_SCREEN_CAPTURE_SAVE_TO_LINUX_FILES" desc="The label of the menu item button for selecting the root of the Linux Files path to store the captured images and videos."> Linux files </message> + <message name="IDS_ASH_GAME_CAPTURE_START_RECORDING_BUTTON" desc="The label of the start recording button inside the game capture bar."> + Start recording + </message> <!-- Snap Group --> <message name="IDS_ASH_SNAP_GROUP_CLICK_TO_LOCK_WINDOWS" desc="Click to lock the windows.">
diff --git a/ash/ash_strings_grd/IDS_ASH_GAME_CAPTURE_START_RECORDING_BUTTON.png.sha1 b/ash/ash_strings_grd/IDS_ASH_GAME_CAPTURE_START_RECORDING_BUTTON.png.sha1 new file mode 100644 index 0000000..4de6021 --- /dev/null +++ b/ash/ash_strings_grd/IDS_ASH_GAME_CAPTURE_START_RECORDING_BUTTON.png.sha1
@@ -0,0 +1 @@ +06533ee3def0b1205425c681c0de96d690536e64 \ No newline at end of file
diff --git a/ash/capture_mode/capture_mode_bar_view.cc b/ash/capture_mode/capture_mode_bar_view.cc index 8ba189f..facad852 100644 --- a/ash/capture_mode/capture_mode_bar_view.cc +++ b/ash/capture_mode/capture_mode_bar_view.cc
@@ -39,6 +39,8 @@ } // namespace +CaptureModeBarView::~CaptureModeBarView() = default; + CaptureModeTypeView* CaptureModeBarView::capture_type_view() const { return nullptr; } @@ -47,6 +49,10 @@ return nullptr; } +PillButton* CaptureModeBarView::GetStartRecordingButton() const { + return nullptr; +} + void CaptureModeBarView::OnCaptureSourceChanged(CaptureModeSource new_source) { return; } @@ -85,8 +91,6 @@ shadow_->SetRoundedCornerRadius(kBorderRadius); } -CaptureModeBarView::~CaptureModeBarView() = default; - void CaptureModeBarView::AppendCommonElements() { settings_button_ = AddChildView(std::make_unique<IconButton>( base::BindRepeating(&CaptureModeBarView::OnSettingsButtonPressed,
diff --git a/ash/capture_mode/capture_mode_bar_view.h b/ash/capture_mode/capture_mode_bar_view.h index a22d2d3..22f2bb4d 100644 --- a/ash/capture_mode/capture_mode_bar_view.h +++ b/ash/capture_mode/capture_mode_bar_view.h
@@ -15,6 +15,7 @@ class CaptureModeSourceView; class CaptureModeTypeView; +class PillButton; class IconButton; class SystemShadow; @@ -25,13 +26,18 @@ public: METADATA_HEADER(CaptureModeBarView); + ~CaptureModeBarView() override; + IconButton* settings_button() const { return settings_button_; } IconButton* close_button() const { return close_button_; } // TODO(minch): Renames these two functions to GetCaptureTypeView and // GetCaptureSourceView and updates all the clients. + // These functions may return `nullptr` depending on the actual type of the + // bar. virtual CaptureModeTypeView* capture_type_view() const; virtual CaptureModeSourceView* capture_source_view() const; + virtual PillButton* GetStartRecordingButton() const; // Called when either the capture mode source or type changes. virtual void OnCaptureSourceChanged(CaptureModeSource new_source); @@ -42,7 +48,6 @@ protected: CaptureModeBarView(); - ~CaptureModeBarView() override; // Adds the common elements of different capture bars to the bar view. void AppendCommonElements();
diff --git a/ash/capture_mode/capture_mode_behavior.cc b/ash/capture_mode/capture_mode_behavior.cc index c19ffa4..58a7515 100644 --- a/ash/capture_mode/capture_mode_behavior.cc +++ b/ash/capture_mode/capture_mode_behavior.cc
@@ -12,6 +12,8 @@ #include "ash/capture_mode/capture_mode_controller.h" #include "ash/capture_mode/capture_mode_metrics.h" #include "ash/capture_mode/capture_mode_types.h" +#include "ash/capture_mode/game_capture_bar_view.h" +#include "ash/capture_mode/normal_capture_bar_view.h" #include "ash/constants/ash_features.h" #include "ash/projector/projector_controller_impl.h" #include "ash/shelf/shelf.h" @@ -30,6 +32,9 @@ // adjusted based on the current active behavior. constexpr gfx::Size kFullBarSize{376, 64}; +// Size of the game capture bar. +constexpr gfx::Size kGameCaptureBarSize{260, 64}; + // Distance from the bottom of the capture bar to the bottom of the display, top // of the hotseat or top of the shelf depending on the shelf alignment or // hotseat visibility. @@ -184,6 +189,14 @@ bool ShouldGifBeSupported() const override { return false; } bool ShouldShowUserNudge() const override { return false; } bool ShouldAutoSelectFirstCamera() const override { return true; } + std::unique_ptr<CaptureModeBarView> CreateCaptureModeBarView() override { + return std::make_unique<GameCaptureBarView>(); + } + + protected: + int GetCaptureBarWidth() const override { + return kGameCaptureBarSize.width(); + } }; } // namespace @@ -303,6 +316,11 @@ return ""; } +std::unique_ptr<CaptureModeBarView> +CaptureModeBehavior::CreateCaptureModeBarView() { + return std::make_unique<NormalCaptureBarView>(this); +} + gfx::Rect CaptureModeBehavior::GetCaptureBarBounds(aura::Window* root) const { DCHECK(root);
diff --git a/ash/capture_mode/capture_mode_behavior.h b/ash/capture_mode/capture_mode_behavior.h index 85b47287..d62b00a 100644 --- a/ash/capture_mode/capture_mode_behavior.h +++ b/ash/capture_mode/capture_mode_behavior.h
@@ -23,6 +23,8 @@ namespace ash { +class CaptureModeBarView; + // Contains the cached capture mode configurations that will be used for // configurations restoration when initiating the corresponding capture mode // session. @@ -89,6 +91,10 @@ // indicate the histogram is for a projector-initiated capture mode session. virtual const char* GetClientMetricComponent() const; + // Creates the capture mode bar view, which might look different depending on + // the actual type of the behavior. + virtual std::unique_ptr<CaptureModeBarView> CreateCaptureModeBarView(); + // Gets the bounds in screen coordinates of the capture bar in the given // `root` window. The returned bounds of the bar will vary depending on the // actual type of the behavior.
diff --git a/ash/capture_mode/capture_mode_game_dashboard_unittests.cc b/ash/capture_mode/capture_mode_game_dashboard_unittests.cc index ed7da7d..7e7447e 100644 --- a/ash/capture_mode/capture_mode_game_dashboard_unittests.cc +++ b/ash/capture_mode/capture_mode_game_dashboard_unittests.cc
@@ -81,4 +81,21 @@ EXPECT_TRUE(active_behavior->ShouldAutoSelectFirstCamera()); } +TEST_F(GameDashboardCaptureModeTest, CaptureBar) { + StartGameCaptureModeSession(); + views::Widget* bar_widget = GetCaptureModeBarWidget(); + ASSERT_TRUE(bar_widget); + + // Checks that the game capture bar only includes the start recording button, + // settings button and close button. + EXPECT_TRUE(GetStartRecordingButton()); + EXPECT_FALSE(GetImageToggleButton()); + EXPECT_FALSE(GetVideoToggleButton()); + EXPECT_FALSE(GetFullscreenToggleButton()); + EXPECT_FALSE(GetRegionToggleButton()); + EXPECT_FALSE(GetWindowToggleButton()); + EXPECT_TRUE(GetSettingsButton()); + EXPECT_TRUE(GetCloseButton()); +} + } // namespace ash
diff --git a/ash/capture_mode/capture_mode_session.cc b/ash/capture_mode/capture_mode_session.cc index 502abdea..71e9aad 100644 --- a/ash/capture_mode/capture_mode_session.cc +++ b/ash/capture_mode/capture_mode_session.cc
@@ -4,6 +4,7 @@ #include "ash/capture_mode/capture_mode_session.h" +#include <memory> #include <tuple> #include <utility> @@ -499,7 +500,7 @@ parent, active_behavior_->GetCaptureBarBounds(current_root_), "CaptureModeBarWidget")); capture_mode_bar_view_ = capture_mode_bar_widget_->SetContentsView( - std::make_unique<NormalCaptureBarView>(active_behavior_)); + active_behavior_->CreateCaptureModeBarView()); capture_mode_bar_widget_->GetNativeWindow()->SetTitle( l10n_util::GetStringUTF16(IDS_ASH_SCREEN_CAPTURE_A11Y_TITLE)); capture_mode_bar_widget_->Show(); @@ -532,11 +533,10 @@ // `OnCaptureTypeChanged` may trigger `ShowCaptureToast` which depends on the // capture bar. // Also please note we should call `OnCaptureTypeChanged` in - // `CaptureModeTypeView` instead of `CaptureModeSession`, since this is during + // `CaptureModeBarView` instead of `CaptureModeSession`, since this is during // the initialization of the capture session, the type change is not triggered // by the user. - capture_mode_bar_view_->capture_type_view()->OnCaptureTypeChanged( - controller_->type()); + capture_mode_bar_view_->OnCaptureTypeChanged(controller_->type()); MaybeCreateUserNudge(); if (active_behavior_->ShouldAutoSelectFirstCamera()) {
diff --git a/ash/capture_mode/capture_mode_session_focus_cycler.cc b/ash/capture_mode/capture_mode_session_focus_cycler.cc index 5dd7435..e357451 100644 --- a/ash/capture_mode/capture_mode_session_focus_cycler.cc +++ b/ash/capture_mode/capture_mode_session_focus_cycler.cc
@@ -584,8 +584,10 @@ // currently has focus and we are already in region mode, as we still want to // create a default region in this case. CaptureModeBarView* bar_view = session_->capture_mode_bar_view_; - if (view->GetView() == - bar_view->capture_source_view()->region_toggle_button() && + if (const CaptureModeSourceView* capture_source_view = + bar_view->capture_source_view(); + capture_source_view && + view->GetView() == capture_source_view->region_toggle_button() && CaptureModeController::Get()->source() == CaptureModeSource::kRegion) { return false; } @@ -804,6 +806,9 @@ CaptureModeBarView* bar_view = session_->capture_mode_bar_view_; CaptureModeTypeView* type_view = bar_view->capture_type_view(); CaptureModeSourceView* source_view = bar_view->capture_source_view(); + if (!type_view || !source_view) { + break; + } for (auto* button : {type_view->image_toggle_button(), type_view->video_toggle_button(), source_view->fullscreen_toggle_button(),
diff --git a/ash/capture_mode/capture_mode_test_util.cc b/ash/capture_mode/capture_mode_test_util.cc index 0b2bfb096..8be22a3 100644 --- a/ash/capture_mode/capture_mode_test_util.cc +++ b/ash/capture_mode/capture_mode_test_util.cc
@@ -9,8 +9,10 @@ #include "ash/accessibility/autoclick/autoclick_controller.h" #include "ash/capture_mode/capture_mode_bar_view.h" #include "ash/capture_mode/capture_mode_controller.h" +#include "ash/capture_mode/capture_mode_session.h" #include "ash/capture_mode/capture_mode_session_test_api.h" #include "ash/capture_mode/capture_mode_source_view.h" +#include "ash/capture_mode/capture_mode_type_view.h" #include "ash/capture_mode/test_capture_mode_delegate.h" #include "ash/public/cpp/capture_mode/capture_mode_test_api.h" #include "ash/public/cpp/projector/projector_controller.h" @@ -19,6 +21,7 @@ #include "ash/public/cpp/projector/speech_recognition_availability.h" #include "ash/shell.h" #include "ash/style/icon_button.h" +#include "ash/style/pill_button.h" #include "ash/system/accessibility/autoclick_menu_bubble_controller.h" #include "ash/wm/tablet_mode/tablet_mode_controller_test_api.h" #include "base/files/file_path.h" @@ -173,32 +176,18 @@ ClickOnView(view, event_generator); } +views::Widget* GetCaptureModeBarWidget() { + auto* session = CaptureModeController::Get()->capture_mode_session(); + DCHECK(session); + return session->capture_mode_bar_widget(); +} + CaptureModeBarView* GetCaptureModeBarView() { auto* session = CaptureModeController::Get()->capture_mode_session(); DCHECK(session); return CaptureModeSessionTestApi(session).GetCaptureModeBarView(); } -IconButton* GetSettingsButton() { - auto* controller = CaptureModeController::Get(); - DCHECK(controller->IsActive()); - return GetCaptureModeBarView()->settings_button(); -} - -IconButton* GetFullscreenToggleButton() { - auto* controller = CaptureModeController::Get(); - DCHECK(controller->IsActive()); - return GetCaptureModeBarView() - ->capture_source_view() - ->fullscreen_toggle_button(); -} - -IconButton* GetRegionToggleButton() { - auto* controller = CaptureModeController::Get(); - DCHECK(controller->IsActive()); - return GetCaptureModeBarView()->capture_source_view()->region_toggle_button(); -} - UserNudgeController* GetUserNudgeController() { auto* session = CaptureModeController::Get()->capture_mode_session(); DCHECK(session); @@ -292,6 +281,62 @@ return image; } +IconButton* GetImageToggleButton() { + auto* controller = CaptureModeController::Get(); + DCHECK(controller->IsActive()); + auto* capture_type_view = GetCaptureModeBarView()->capture_type_view(); + return capture_type_view ? capture_type_view->image_toggle_button() : nullptr; +} + +IconButton* GetVideoToggleButton() { + auto* controller = CaptureModeController::Get(); + DCHECK(controller->IsActive()); + auto* capture_type_view = GetCaptureModeBarView()->capture_type_view(); + return capture_type_view ? capture_type_view->video_toggle_button() : nullptr; +} + +IconButton* GetFullscreenToggleButton() { + auto* controller = CaptureModeController::Get(); + DCHECK(controller->IsActive()); + auto* capture_source_view = GetCaptureModeBarView()->capture_source_view(); + return capture_source_view ? capture_source_view->fullscreen_toggle_button() + : nullptr; +} + +IconButton* GetRegionToggleButton() { + auto* controller = CaptureModeController::Get(); + DCHECK(controller->IsActive()); + auto* capture_source_view = GetCaptureModeBarView()->capture_source_view(); + return capture_source_view ? capture_source_view->region_toggle_button() + : nullptr; +} + +IconButton* GetWindowToggleButton() { + auto* controller = CaptureModeController::Get(); + DCHECK(controller->IsActive()); + auto* capture_source_view = GetCaptureModeBarView()->capture_source_view(); + return capture_source_view ? capture_source_view->window_toggle_button() + : nullptr; +} + +PillButton* GetStartRecordingButton() { + auto* controller = CaptureModeController::Get(); + DCHECK(controller->IsActive()); + return GetCaptureModeBarView()->GetStartRecordingButton(); +} + +IconButton* GetSettingsButton() { + auto* controller = CaptureModeController::Get(); + DCHECK(controller->IsActive()); + return GetCaptureModeBarView()->settings_button(); +} + +IconButton* GetCloseButton() { + auto* controller = CaptureModeController::Get(); + DCHECK(controller->IsActive()); + return GetCaptureModeBarView()->close_button(); +} + // ----------------------------------------------------------------------------- // ProjectorCaptureModeIntegrationHelper:
diff --git a/ash/capture_mode/capture_mode_test_util.h b/ash/capture_mode/capture_mode_test_util.h index 22b2efd3..84311b4a 100644 --- a/ash/capture_mode/capture_mode_test_util.h +++ b/ash/capture_mode/capture_mode_test_util.h
@@ -40,6 +40,7 @@ namespace ash { +class PillButton; class IconButton; class CaptureModeController; class CaptureModeBarView; @@ -99,14 +100,10 @@ bool in_table_mode, ui::test::EventGenerator* event_generator); +views::Widget* GetCaptureModeBarWidget(); + CaptureModeBarView* GetCaptureModeBarView(); -IconButton* GetSettingsButton(); - -IconButton* GetFullscreenToggleButton(); - -IconButton* GetRegionToggleButton(); - UserNudgeController* GetUserNudgeController(); bool IsLayerStackedRightBelow(ui::Layer* layer, ui::Layer* sibling); @@ -136,6 +133,16 @@ // bitmap was successfully read from disk or an empty gfx::Image otherwise. gfx::Image ReadAndDecodeImageFile(const base::FilePath& image_path); +// Gets the buttons inside the capture bar view. +IconButton* GetImageToggleButton(); +IconButton* GetVideoToggleButton(); +IconButton* GetFullscreenToggleButton(); +IconButton* GetRegionToggleButton(); +IconButton* GetWindowToggleButton(); +PillButton* GetStartRecordingButton(); +IconButton* GetSettingsButton(); +IconButton* GetCloseButton(); + // Defines a helper class to allow setting up and testing the Projector feature // in multiple test fixtures. Note that this helper initializes the Projector- // related features in its constructor, so test fixtures that use this should
diff --git a/ash/capture_mode/capture_mode_unittests.cc b/ash/capture_mode/capture_mode_unittests.cc index 5552afe..9287c5c 100644 --- a/ash/capture_mode/capture_mode_unittests.cc +++ b/ash/capture_mode/capture_mode_unittests.cc
@@ -235,12 +235,6 @@ demo_tools_enabled_ = features::AreCaptureModeDemoToolsEnabled(); } - views::Widget* GetCaptureModeBarWidget() const { - auto* session = CaptureModeController::Get()->capture_mode_session(); - DCHECK(session); - return session->capture_mode_bar_widget(); - } - views::Widget* GetCaptureModeLabelWidget() const { auto* session = CaptureModeController::Get()->capture_mode_session(); DCHECK(session); @@ -271,32 +265,6 @@ return CaptureModeSessionTestApi(session).IsAllUisVisible(); } - IconButton* GetImageToggleButton() const { - auto* controller = CaptureModeController::Get(); - DCHECK(controller->IsActive()); - return GetCaptureModeBarView()->capture_type_view()->image_toggle_button(); - } - - IconButton* GetVideoToggleButton() const { - auto* controller = CaptureModeController::Get(); - DCHECK(controller->IsActive()); - return GetCaptureModeBarView()->capture_type_view()->video_toggle_button(); - } - - IconButton* GetWindowToggleButton() const { - auto* controller = CaptureModeController::Get(); - DCHECK(controller->IsActive()); - return GetCaptureModeBarView() - ->capture_source_view() - ->window_toggle_button(); - } - - IconButton* GetCloseButton() const { - auto* controller = CaptureModeController::Get(); - DCHECK(controller->IsActive()); - return GetCaptureModeBarView()->close_button(); - } - aura::Window* GetDimensionsLabelWindow() const { auto* controller = CaptureModeController::Get(); DCHECK(controller->IsActive()); @@ -4724,6 +4692,7 @@ EXPECT_TRUE(GetFullscreenToggleButton()); EXPECT_TRUE(GetRegionToggleButton()); EXPECT_TRUE(GetWindowToggleButton()); + EXPECT_FALSE(GetStartRecordingButton()); EXPECT_TRUE(GetSettingsButton()); EXPECT_TRUE(GetCloseButton()); @@ -5811,6 +5780,7 @@ EXPECT_TRUE(GetFullscreenToggleButton()); EXPECT_TRUE(GetRegionToggleButton()); EXPECT_TRUE(GetWindowToggleButton()); + EXPECT_FALSE(GetStartRecordingButton()); EXPECT_TRUE(GetSettingsButton()); EXPECT_TRUE(GetCloseButton());
diff --git a/ash/capture_mode/game_capture_bar_view.cc b/ash/capture_mode/game_capture_bar_view.cc new file mode 100644 index 0000000..800ba2c4 --- /dev/null +++ b/ash/capture_mode/game_capture_bar_view.cc
@@ -0,0 +1,38 @@ +// Copyright 2023 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/capture_mode/game_capture_bar_view.h" + +#include "ash/strings/grit/ash_strings.h" +#include "ash/style/pill_button.h" +#include "ui/base/l10n/l10n_util.h" +#include "ui/base/metadata/metadata_impl_macros.h" + +namespace ash { + +GameCaptureBarView::GameCaptureBarView() + : start_recording_button_(AddChildView(std::make_unique<PillButton>( + base::BindRepeating(&GameCaptureBarView::StartRecording, + base::Unretained(this)), + l10n_util::GetStringUTF16( + IDS_ASH_GAME_CAPTURE_START_RECORDING_BUTTON), + PillButton::kPrimaryWithoutIcon))) { + AppendCommonElements(); +} + +GameCaptureBarView::~GameCaptureBarView() = default; + +PillButton* GameCaptureBarView::GetStartRecordingButton() const { + return start_recording_button_; +} + +void GameCaptureBarView::StartRecording() { + // TODO(b/282193685): Start recording once the selected window is set and not + // changeable after game capture session starts. +} + +BEGIN_METADATA(GameCaptureBarView, CaptureModeBarView) +END_METADATA + +} // namespace ash
diff --git a/ash/capture_mode/game_capture_bar_view.h b/ash/capture_mode/game_capture_bar_view.h new file mode 100644 index 0000000..d3f844d9 --- /dev/null +++ b/ash/capture_mode/game_capture_bar_view.h
@@ -0,0 +1,41 @@ +// Copyright 2023 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_CAPTURE_MODE_GAME_CAPTURE_BAR_VIEW_H_ +#define ASH_CAPTURE_MODE_GAME_CAPTURE_BAR_VIEW_H_ + +#include "ash/ash_export.h" +#include "ash/capture_mode/capture_mode_bar_view.h" +#include "base/memory/raw_ptr.h" +#include "ui/base/metadata/metadata_header_macros.h" + +namespace ash { + +class PillButton; + +// A view that acts as the content view of the capture mode bar widget of a +// game capture session. The bar only includes a start recording button, the +// settings and close buttons. +class ASH_EXPORT GameCaptureBarView : public CaptureModeBarView { + public: + METADATA_HEADER(GameCaptureBarView); + + GameCaptureBarView(); + GameCaptureBarView(const GameCaptureBarView&) = delete; + GameCaptureBarView& operator=(const GameCaptureBarView&) = delete; + ~GameCaptureBarView() override; + + // CaptureModeBarView: + PillButton* GetStartRecordingButton() const override; + + private: + // Called when clicking on the start recording button inside the bar. + void StartRecording(); + + raw_ptr<PillButton, ExperimentalAsh> start_recording_button_; +}; + +} // namespace ash + +#endif // ASH_CAPTURE_MODE_GAME_CAPTURE_BAR_VIEW_H_
diff --git a/ash/capture_mode/normal_capture_bar_view.h b/ash/capture_mode/normal_capture_bar_view.h index 37d5a67..3ced7e4 100644 --- a/ash/capture_mode/normal_capture_bar_view.h +++ b/ash/capture_mode/normal_capture_bar_view.h
@@ -17,10 +17,11 @@ class CaptureModeSourceView; class CaptureModeTypeView; -// A view that acts as the content view of the capture mode bar widget. It has -// a set of buttons to toggle between image and video capture, and another set -// of buttons to toggle between fullscreen, region, and window capture sources. -// It also contains a settings button. The structure looks like this: +// A view that acts as the content view of the capture mode bar widget for a +// normal capture session. It has a set of buttons to toggle between image and +// video capture, and another set of buttons to toggle between fullscreen, +// region, and window capture sources. It also contains a settings button. The +// structure looks like this: // // +---------------------------------------------------------------+ // | +----------------+ | | |
diff --git a/ash/system/channel_indicator/channel_indicator_quick_settings_view.cc b/ash/system/channel_indicator/channel_indicator_quick_settings_view.cc index 25ae7c9b..0dab2d8 100644 --- a/ash/system/channel_indicator/channel_indicator_quick_settings_view.cc +++ b/ash/system/channel_indicator/channel_indicator_quick_settings_view.cc
@@ -346,7 +346,8 @@ void PaintButtonContents(gfx::Canvas* canvas) override { cc::PaintFlags flags; if (features::IsQsRevampEnabled()) { - flags.setColor(GetColorProvider()->GetColor(kColorAshSeparatorColor)); + flags.setColor( + GetColorProvider()->GetColor(cros_tokens::kCrosSysSeparator)); flags.setStyle(cc::PaintFlags::kStroke_Style); } else { flags.setColor(channel_indicator_utils::GetBgColor(channel_));
diff --git a/ash/system/channel_indicator/channel_indicator_quick_settings_view_pixeltest.cc b/ash/system/channel_indicator/channel_indicator_quick_settings_view_pixeltest.cc index 7cd138d..6d6a6cc 100644 --- a/ash/system/channel_indicator/channel_indicator_quick_settings_view_pixeltest.cc +++ b/ash/system/channel_indicator/channel_indicator_quick_settings_view_pixeltest.cc
@@ -113,7 +113,7 @@ // `ChannelIndicatorQuickSettingsView`. EXPECT_TRUE(GetPixelDiffer()->CompareUiComponentsOnPrimaryScreen( "feedback_button_visible", - /*revision_number=*/1, view())); + /*revision_number=*/2, view())); } } // namespace ash
diff --git a/ash/webui/common/resources/navigation_view_panel.html b/ash/webui/common/resources/navigation_view_panel.html index a4b1b3d..87d8bbf 100644 --- a/ash/webui/common/resources/navigation_view_panel.html +++ b/ash/webui/common/resources/navigation_view_panel.html
@@ -1,9 +1,16 @@ <style include="cr-shared-style"> + ::slotted([slot=bottom-nav-content-drawer]) { + position: absolute; + } + + ::slotted([slot=bottom-nav-content-panel]) { + position: fixed; + } + ::slotted([slot=bottom-nav-content-drawer]), ::slotted([slot=bottom-nav-content-panel]) { bottom: 24px; inset-inline-start: 16px; - position: fixed; } ::slotted([slot=banner]) {
diff --git a/ash/webui/personalization_app/personalization_app_ui.cc b/ash/webui/personalization_app/personalization_app_ui.cc index 7bd9c4a..a0dd5718 100644 --- a/ash/webui/personalization_app/personalization_app_ui.cc +++ b/ash/webui/personalization_app/personalization_app_ui.cc
@@ -469,6 +469,9 @@ source->AddBoolean("isTimeOfDayScreenSaverEnabled", features::IsTimeOfDayScreenSaverEnabled()); + + source->AddBoolean("isTimeOfDayWallpaperEnabled", + features::IsTimeOfDayWallpaperEnabled()); } void PersonalizationAppUI::AddIntegers(content::WebUIDataSource* source) {
diff --git a/ash/webui/personalization_app/resources/js/load_time_booleans.ts b/ash/webui/personalization_app/resources/js/load_time_booleans.ts index 9818d99..38c8973 100644 --- a/ash/webui/personalization_app/resources/js/load_time_booleans.ts +++ b/ash/webui/personalization_app/resources/js/load_time_booleans.ts
@@ -50,3 +50,7 @@ export function isTimeOfDayScreenSaverEnabled() { return loadTimeData.getBoolean('isTimeOfDayScreenSaverEnabled'); } + +export function isTimeOfDayWallpaperEnabled() { + return loadTimeData.getBoolean('isTimeOfDayWallpaperEnabled'); +}
diff --git a/ash/webui/personalization_app/resources/js/wallpaper/utils.ts b/ash/webui/personalization_app/resources/js/wallpaper/utils.ts index 1af2f5b..3ff1411 100644 --- a/ash/webui/personalization_app/resources/js/wallpaper/utils.ts +++ b/ash/webui/personalization_app/resources/js/wallpaper/utils.ts
@@ -104,7 +104,7 @@ */ export function getLoadingPlaceholders<T>(factory: () => T): T[] { const x = getNumberOfGridItemsPerRow(); - const y = Math.floor(window.innerHeight / /*tileHeightPx=*/ 136); + const y = Math.max(Math.floor(window.innerHeight / /*tileHeightPx=*/ 136), 2); return Array.from({length: x * y}, factory); }
diff --git a/ash/webui/personalization_app/resources/js/wallpaper/wallpaper_collections_element.ts b/ash/webui/personalization_app/resources/js/wallpaper/wallpaper_collections_element.ts index fea135c..4e294c8 100644 --- a/ash/webui/personalization_app/resources/js/wallpaper/wallpaper_collections_element.ts +++ b/ash/webui/personalization_app/resources/js/wallpaper/wallpaper_collections_element.ts
@@ -21,7 +21,7 @@ import {afterNextRender} from 'chrome://resources/polymer/v3_0/polymer/polymer_bundled.min.js'; import {GooglePhotosEnablementState, WallpaperCollection, WallpaperImage} from '../../personalization_app.mojom-webui.js'; -import {isGooglePhotosIntegrationEnabled} from '../load_time_booleans.js'; +import {isGooglePhotosIntegrationEnabled, isTimeOfDayWallpaperEnabled} from '../load_time_booleans.js'; import {Paths, PersonalizationRouter} from '../personalization_router_element.js'; import {WithPersonalizationStore} from '../personalization_store.js'; import {getCountText, isImageDataUrl, isNonEmptyArray, isSelectionEvent} from '../utils.js'; @@ -45,6 +45,7 @@ interface LoadingTile { type: TileType.LOADING; + id: string; } interface GooglePhotosTile { @@ -76,6 +77,15 @@ type Tile = LoadingTile|GooglePhotosTile|LocalTile|OnlineTile; +// "regular" backdrop collections are displayed differently than the special +// "timeOfDay" wallpaper collection. Split them to make them easier to handle. +// The special "timeOfDay" collection may not exist depending on the device and +// features enabled. +interface SplitCollections { + regular: WallpaperCollection[]; + timeOfDay: WallpaperCollection|null; +} + /** * Before switching entirely to WallpaperGridItem, have to deal with a mix of * keyboard and mouse events and a custom WallpaperGridItemSelected event. @@ -147,7 +157,7 @@ localImageData: Record<FilePath['path']|DefaultImageSymbol, Url>): LocalTile|LoadingTile { if (localImagesLoading) { - return {type: TileType.LOADING}; + return {type: TileType.LOADING, id: kLocalCollectionId}; } if (!localImages || localImages.length === 0) { @@ -182,6 +192,29 @@ }; } +function getOnlineTile( + collection: WallpaperCollection, imageCount: number|null): OnlineTile { + return { + count: getCountText(imageCount || 0), + // If `imageCount` is null or 0, this collection failed to load and the user + // cannot select it. + disabled: !imageCount, + id: collection.id, + info: collection.descriptionContent, + name: collection.name, + preview: collection.previews, + type: TileType.IMAGE_ONLINE, + }; +} + +function getTemporaryBackdropCollectionId(index: number) { + return `backdrop_collection_${index}`; +} + +function isTimeOfDay({id}: WallpaperCollection|Tile): boolean { + return id === loadTimeData.getString('timeOfDayWallpaperCollectionId'); +} + export class WallpaperCollections extends WithPersonalizationStore { static get is() { return 'wallpaper-collections'; @@ -200,7 +233,16 @@ observer: 'onHiddenChanged_', }, - collections_: Array, + collections_: { + type: Array, + observer: 'onCollectionsChanged_', + }, + + /** + * Wallpaper collections split out into "regular" collections, and the + * special time of day collection. + */ + splitCollections_: Object, images_: Object, @@ -243,8 +285,38 @@ value() { // Fill the view with loading tiles. Will be adjusted to the correct // number of tiles when collections are received. - return getLoadingPlaceholders( - (): LoadingTile => ({type: TileType.LOADING})); + const placeholders = getLoadingPlaceholders<LoadingTile>( + () => ({type: TileType.LOADING, id: ''})); + + let currentIndex = 0; + // Time of day tile. + if (isTimeOfDayWallpaperEnabled()) { + placeholders[currentIndex].id = + loadTimeData.getString('timeOfDayWallpaperCollectionId'); + currentIndex++; + } + + // Local images tile. + placeholders[currentIndex].id = kLocalCollectionId; + currentIndex++; + + // Google Photos tile. + if (isGooglePhotosIntegrationEnabled()) { + placeholders[currentIndex].id = kGooglePhotosCollectionId; + currentIndex++; + } + + // The rest of the backdrop tiles. Actual number will be adjusted once + // collections are received. The actual id is not important as long as + // they are unique. + const firstBackdropIndex = currentIndex; + while (currentIndex < placeholders.length) { + placeholders[currentIndex].id = getTemporaryBackdropCollectionId( + currentIndex - firstBackdropIndex); + currentIndex++; + } + + return placeholders; }, }, @@ -254,6 +326,7 @@ override hidden: boolean; private collections_: WallpaperCollection[]|null; + private splitCollections_: SplitCollections|null; private images_: Record<string, WallpaperImage[]|null>; private imagesLoading_: Record<string, boolean>; private imageCounts_: Record<string, number|null>; @@ -267,7 +340,7 @@ static get observers() { return [ 'onLocalImagesChanged_(localImages_, localImagesLoading_, localImageData_)', - 'onCollectionLoaded_(collections_, imageCounts_)', + 'onCollectionLoaded_(splitCollections_, imageCounts_)', ]; } @@ -303,6 +376,22 @@ } /** + * Tiles are laid out + * `[time_of_day?, local, google_photos?, ...regular backdrop tiles...]`. + * Get the index of the first regular backdrop tile. + * @returns the index of the first regular backdrop tile. + */ + private getFirstRegularBackdropTileIndex(): number { + const firstBackdropIndex = this.tiles_.findIndex( + tile => tile.id !== kLocalCollectionId && + tile.id !== kGooglePhotosCollectionId && !isTimeOfDay(tile)); + assert( + firstBackdropIndex > 0, + 'first backdrop index must always be greater than 0'); + return firstBackdropIndex; + } + + /** * Notify that this element visibility has changed. */ private async onHiddenChanged_(hidden: boolean) { @@ -313,6 +402,55 @@ } /** + * Called when the list of wallpaper collections changes. Collections are not + * actually displayed until they have completed loading, which is handled by + * `onCollectionLoaded_`. + */ + private onCollectionsChanged_(collections: WallpaperCollection[]|null) { + if (!isNonEmptyArray(collections)) { + this.splitCollections_ = null; + return; + } + + const timeOfDay = collections.find(isTimeOfDay) ?? null; + if (!timeOfDay && isTimeOfDayWallpaperEnabled()) { + console.error('missing time of day wallpaper from collections'); + this.tiles_ = this.tiles_.filter(tile => !isTimeOfDay(tile)); + } + + this.splitCollections_ = { + regular: collections.filter(collection => !isTimeOfDay(collection)), + timeOfDay, + }; + + // This is the index of the first tile after the "special" tiles like time + // of day, local images, and google photos. + const firstBackdropIndex = this.getFirstRegularBackdropTileIndex(); + const desiredNumTiles = + this.splitCollections_.regular.length + firstBackdropIndex; + + // Adjust the number of loading tiles to match the collections that just + // came in. There may be more (or fewer) loading tiles than necessary to + // display all collections. Match the number of tiles to the correct length. + if (this.tiles_.length < desiredNumTiles) { + this.push( + 'tiles_', + ...Array.from( + {length: desiredNumTiles - this.tiles_.length}, + (_, i): LoadingTile => { + return { + type: TileType.LOADING, + id: getTemporaryBackdropCollectionId( + i - firstBackdropIndex + this.tiles_.length), + }; + })); + } + if (this.tiles_.length > desiredNumTiles) { + this.splice('tiles_', desiredNumTiles); + } + } + + /** * Calculate count of image units in each collection when a new collection is * fetched. D/L variants of the same image represent a count of 1. */ @@ -356,66 +494,64 @@ * A value of null indicates that the given collection id has failed to load. */ private onCollectionLoaded_( - collections: WallpaperCollection[]|null, + splitCollections: SplitCollections|null, imageCounts: Record<string, number|null>) { - if (!isNonEmptyArray(collections) || !imageCounts) { + if (!splitCollections || !isNonEmptyArray(splitCollections.regular) || + !imageCounts) { return; } - // The first tile in the collections grid is reserved for local images. The - // second tile is reserved for Google Photos, provided that the integration - // is enabled. The tile index of other collections must be `offset` so as - // not to occupy reserved space. - const offset = isGooglePhotosIntegrationEnabled() ? 2 : 1; + const firstBackdropIndex = this.getFirstRegularBackdropTileIndex(); - if (this.tiles_.length < collections.length + offset) { - this.push( - 'tiles_', - ...Array.from( - {length: collections.length + offset - this.tiles_.length}, - (): LoadingTile => ({type: TileType.LOADING}))); - } - if (this.tiles_.length > collections.length + offset) { - this.splice('tiles_', collections.length + offset); - } - - collections.forEach((collection, i) => { - const index = i + offset; - const tile = this.tiles_[index]; + splitCollections.regular.forEach((collection, i) => { assert( isNonEmptyArray(collection.previews), `preview images required for collection ${collection.id}`); + const index = i + firstBackdropIndex; + const tile = this.tiles_[index]; + if (imageCounts[collection.id] === undefined) { + // Collection is still loading, skip. return; } - const count = getCountText(imageCounts[collection.id] || 0); - if (tile.type !== TileType.IMAGE_ONLINE || count !== tile.count) { - // Return all the previews to display the split view. - const preview = collection.previews; - - const newTile: OnlineTile = { - count, - // If `imageCounts[collection.id]` is null, this collection failed to - // load and the user cannot select it. - disabled: imageCounts[collection.id] === null, - id: collection.id, - info: collection.descriptionContent, - name: collection.name, - preview, - type: TileType.IMAGE_ONLINE, - }; + const newTile = getOnlineTile(collection, imageCounts[collection.id]); + if (tile.type !== newTile.type || tile.id !== newTile.id || + tile.count !== newTile.count) { this.set(`tiles_.${index}`, newTile); } }); + + if (splitCollections.timeOfDay && + imageCounts[splitCollections.timeOfDay.id] !== undefined) { + const tileIndex = this.tiles_.findIndex(isTimeOfDay); + if (tileIndex < 0) { + console.warn('received time of day collection when not supported'); + return; + } + const tile = this.tiles_[tileIndex]; + const newTile = getOnlineTile( + splitCollections.timeOfDay, + imageCounts[splitCollections.timeOfDay.id]); + if (tile.type !== newTile.type || tile.count !== newTile.count) { + this.set(`tiles_.${tileIndex}`, newTile); + } + } } /** Invoked on changes to |googlePhotosEnabled_|. */ - private onGooglePhotosEnabledChanged_( - googlePhotosEnabled: WallpaperCollections['googlePhotosEnabled_']) { + private onGooglePhotosEnabledChanged_(googlePhotosEnabled: + GooglePhotosEnablementState| + undefined) { if (googlePhotosEnabled !== undefined) { + assert( + isGooglePhotosIntegrationEnabled(), + 'google photos integration must be enabled'); const tile = getGooglePhotosTile(googlePhotosEnabled); - this.set('tiles_.1', tile); + const index = + this.tiles_.findIndex(tile => tile.id === kGooglePhotosCollectionId); + assert(index >= 0, 'could not find google photos tile'); + this.set(`tiles_.${index}`, tile); } } @@ -428,7 +564,9 @@ localImagesLoading: boolean, localImageData: Record<FilePath['path']|DefaultImageSymbol, Url>) { const tile = getLocalTile(localImages, localImagesLoading, localImageData); - this.set('tiles_.0', tile); + const index = this.tiles_.findIndex(tile => tile.id === kLocalCollectionId); + assert(index >= 0, 'could not find local tile'); + this.set(`tiles_.${index}`, tile); } /** Navigate to the correct route based on user selection. */ @@ -491,8 +629,7 @@ } private isTimeOfDayCollection_(item: Tile|null): boolean { - return this.isOnlineTile_(item) && - item.id === loadTimeData.getString('timeOfDayWallpaperCollectionId'); + return this.isOnlineTile_(item) && isTimeOfDay(item); } private getAriaIndex_(index: number): number {
diff --git a/ash/wm/overview/overview_item_view.cc b/ash/wm/overview/overview_item_view.cc index 40d17c4..cef9685 100644 --- a/ash/wm/overview/overview_item_view.cc +++ b/ash/wm/overview/overview_item_view.cc
@@ -347,16 +347,6 @@ void OverviewItemView::OnThemeChanged() { WindowMiniView::OnThemeChanged(); UpdateFocusState(IsViewHighlighted()); - - // If it's still showing the saved desk library, make sure overview item - // window is not visible. - // Please note, `overview_item_` might be null if it's about to be restored to - // its original state outside of overview. Please refer to b/270171802 for - // details. - if (overview_item_ && - overview_item_->overview_grid()->IsShowingSavedDeskLibrary()) { - overview_item_->GetWindow()->layer()->SetOpacity(0.f); - } } BEGIN_METADATA(OverviewItemView, WindowMiniView)
diff --git a/ash/wm/overview/overview_session_unittest.cc b/ash/wm/overview/overview_session_unittest.cc index d5cb30d..3bb39df2 100644 --- a/ash/wm/overview/overview_session_unittest.cc +++ b/ash/wm/overview/overview_session_unittest.cc
@@ -842,8 +842,9 @@ // Tests the animation histograms when entering and exiting overview with a // maximized and fullscreen window. -// TODO(b/252523767): Reenable this test. -TEST_P(OverviewSessionTest, DISABLED_MaximizedFullscreenHistograms) { +#if defined(NDEBUG) && !defined(ADDRESS_SANITIZER) && \ + !defined(LEAK_SANITIZER) && !defined(THREAD_SANITIZER) +TEST_P(OverviewSessionTest, MaximizedFullscreenHistograms) { std::unique_ptr<aura::Window> maximized_window(CreateTestWindow()); std::unique_ptr<aura::Window> fullscreen_window(CreateTestWindow()); @@ -881,6 +882,7 @@ CheckOverviewEnterExitHistogram("FullscreenWindowExit1", {0, 2, 0, 0, 0}, {0, 2, 0, 0, 0}); } +#endif TEST_P(OverviewSessionTest, TabletModeHistograms) { ui::ScopedAnimationDurationScaleMode anmatin_scale(
diff --git a/ash/wm/overview/overview_test_base.cc b/ash/wm/overview/overview_test_base.cc index 6092a1fa..98981c3 100644 --- a/ash/wm/overview/overview_test_base.cc +++ b/ash/wm/overview/overview_test_base.cc
@@ -222,13 +222,14 @@ const std::vector<int>& exit_counts) { CheckForDuplicateTraceName(trace); - // Overview histograms recorded via ui::ThroughputTracker is reported - // on the next frame presented after animation stops. Wait for the next - // frame with a 100ms timeout for the report, regardless of whether there - // is a next frame. - std::ignore = ui::WaitForNextFrameToBePresented( - Shell::GetPrimaryRootWindow()->layer()->GetCompositor(), - base::Milliseconds(500)); + // Force a frame then wait, ensuring there is one more frame presented after + // animation finishes to allow animation throughput data to be passed from + // cc to ui. + ui::Compositor* compositor = + Shell::GetPrimaryRootWindow()->layer()->GetCompositor(); + compositor->ScheduleFullRedraw(); + std::ignore = + ui::WaitForNextFrameToBePresented(compositor, base::Milliseconds(500)); { SCOPED_TRACE(trace + ".Enter");
diff --git a/ash/wm/splitview/split_view_controller_unittest.cc b/ash/wm/splitview/split_view_controller_unittest.cc index abc7674..ff731d7 100644 --- a/ash/wm/splitview/split_view_controller_unittest.cc +++ b/ash/wm/splitview/split_view_controller_unittest.cc
@@ -311,13 +311,14 @@ std::vector<int>&& exit_counts) { CheckForDuplicateTraceName(trace); - // Overview histograms recorded via ui::ThroughputTracker is reported - // on the next frame presented after animation stops. Wait for the next - // frame with a 100ms timeout for the report, regardless of whether there - // is a next frame. - std::ignore = ui::WaitForNextFrameToBePresented( - Shell::GetPrimaryRootWindow()->layer()->GetCompositor(), - base::Milliseconds(100)); + // Force a frame then wait, ensuring there is one more frame presented after + // animation finishes to allow animation throughput data to be passed from + // cc to ui. + ui::Compositor* compositor = + Shell::GetPrimaryRootWindow()->layer()->GetCompositor(); + compositor->ScheduleFullRedraw(); + std::ignore = + ui::WaitForNextFrameToBePresented(compositor, base::Milliseconds(500)); { SCOPED_TRACE(trace + std::string(".Enter")); @@ -776,10 +777,11 @@ EXPECT_TRUE(wm::IsActiveWindow(window1.get())); } +#if defined(NDEBUG) && !defined(ADDRESS_SANITIZER) && \ + !defined(LEAK_SANITIZER) && !defined(THREAD_SANITIZER) // Tests that the overview mode enter exit smoothness histograms are recorded // properly when one window is snapped. -// TODO(b/252523767): Reenable this test. -TEST_F(SplitViewControllerTest, DISABLED_EnterExitOverviewModeHistograms) { +TEST_F(SplitViewControllerTest, EnterExitOverviewModeHistograms) { const gfx::Rect bounds(0, 0, 400, 400); std::unique_ptr<aura::Window> window1(CreateWindow(bounds)); std::unique_ptr<aura::Window> window2(CreateWindow(bounds)); @@ -795,7 +797,7 @@ split_view_controller()->state()); ui::ScopedAnimationDurationScaleMode animation_scale( - ui::ScopedAnimationDurationScaleMode::NON_ZERO_DURATION); + ui::ScopedAnimationDurationScaleMode::NORMAL_DURATION); ToggleOverview(); WaitForOverviewEnterAnimation(); @@ -805,6 +807,7 @@ WaitForOverviewExitAnimation(); CheckOverviewEnterExitHistogram("ExitInSplitView", {0, 1}, {0, 1}); } +#endif // Tests that the split divider was created when the split view mode is active // and destroyed when the split view mode is ended. The split divider should be @@ -1745,8 +1748,9 @@ // Tests the overview animation smoothness histograms when using long pressing // the overview button. -// TODO(b/252523767): Reenable this test. -TEST_F(SplitViewControllerTest, DISABLED_LongPressInOverviewModeHistograms) { +#if defined(NDEBUG) && !defined(ADDRESS_SANITIZER) && \ + !defined(LEAK_SANITIZER) && !defined(THREAD_SANITIZER) +TEST_F(SplitViewControllerTest, LongPressInOverviewModeHistograms) { ui::ScopedAnimationDurationScaleMode animation_scale( ui::ScopedAnimationDurationScaleMode::NON_ZERO_DURATION); @@ -1776,6 +1780,7 @@ EXPECT_EQ(window.get(), split_view_controller()->primary_window()); CheckOverviewEnterExitHistogram("NoTransition", {1, 0}, {0, 0}); } +#endif TEST_F(SplitViewControllerTest, LongPressWithUnsnappableWindow) { // Add an unsnappable window and a regular window.
diff --git a/base/BUILD.gn b/base/BUILD.gn index 4b16bc5a7..1cf5be6 100644 --- a/base/BUILD.gn +++ b/base/BUILD.gn
@@ -205,40 +205,6 @@ flags = [ "ENABLE_MESSAGE_PUMP_EPOLL=$enable_message_pump_epoll" ] } -if (is_apple) { - # TODO(https://crbug.com/1280317): Merge back into the `base` target once all - # .mm files are ARCed. - source_set("base_arc") { - sources = [ - "mac/dispatch_source_mach.h", - "mac/dispatch_source_mach.mm", - ] - configs += [ "//build/config/compiler:enable_arc" ] - deps = [ - ":base_static", - "//third_party/abseil-cpp:absl", - ] - - if (is_mac) { - sources += [ - "files/file_path_watcher_fsevents.h", - "files/file_path_watcher_fsevents.mm", - "mac/mach_port_rendezvous.h", - "mac/mach_port_rendezvous.mm", - "synchronization/waitable_event_watcher_mac.mm", - ] - libs = [ "bsm" ] - frameworks = [ - "AppKit.framework", - "CoreServices.framework", - ] - } - if (is_ios) { - frameworks = [ "UIKit.framework" ] - } - } -} - # Base and everything it depends on should be a static library rather than # a source set. Base is more of a "library" in the classic sense in that many # small parts of it are used in many different contexts. This combined with a @@ -2001,6 +1967,8 @@ "enterprise_util.cc", "enterprise_util.h", "enterprise_util_mac.mm", + "files/file_path_watcher_fsevents.cc", + "files/file_path_watcher_fsevents.h", "files/file_path_watcher_kqueue.cc", "files/file_path_watcher_kqueue.h", "files/file_path_watcher_mac.cc", @@ -2013,6 +1981,8 @@ "mac/launchd.h", "mac/mac_util.h", "mac/mac_util.mm", + "mac/mach_port_rendezvous.cc", + "mac/mach_port_rendezvous.h", "mac/os_crash_dumps.cc", "mac/os_crash_dumps.h", "mac/scoped_aedesc.h", @@ -2020,6 +1990,7 @@ "mac/scoped_authorizationref.mm", "mac/scoped_cffiledescriptorref.h", "mac/scoped_cftyperef.h", + "mac/scoped_dispatch_object.h", "mac/scoped_ionotificationportref.h", "mac/scoped_ioobject.h", "mac/scoped_ioplugininterface.h", @@ -2053,6 +2024,7 @@ "profiler/stack_sampler_mac.cc", "profiler/suspendable_thread_delegate_mac.cc", "profiler/suspendable_thread_delegate_mac.h", + "synchronization/waitable_event_watcher_mac.cc", "system/sys_info_mac.mm", "time/time_exploded_posix.cc", ] @@ -2073,19 +2045,20 @@ # Mac or iOS. if (is_apple) { - allow_circular_includes_from = [ ":base_arc" ] sources += [ + "apple/backup_util.h", + "apple/backup_util.mm", "apple/bridging.h", + "apple/bundle_locations.h", + "apple/bundle_locations.mm", "file_version_info_mac.h", "file_version_info_mac.mm", "files/file_util_mac.mm", - "mac/backup_util.h", - "mac/backup_util.mm", - "mac/bundle_locations.h", - "mac/bundle_locations.mm", "mac/call_with_eh_frame.cc", "mac/call_with_eh_frame.h", "mac/call_with_eh_frame_asm.S", + "mac/dispatch_source_mach.cc", + "mac/dispatch_source_mach.h", "mac/foundation_util.h", "mac/foundation_util.mm", "mac/mac_logging.h", @@ -2115,7 +2088,6 @@ "time/time_mac.mm", ] frameworks += [ "Security.framework" ] - public_deps += [ ":base_arc" ] } # Linux. @@ -3492,10 +3464,7 @@ if (is_apple) { public_deps = [ ":base_unittests_bundle_data" ] - deps += [ - ":base_arc", - ":base_unittests_arc", - ] + deps += [ ":base_unittests_arc" ] } if (!is_ios) { @@ -3593,8 +3562,8 @@ sources += [ "allocator/partition_allocator/shim/allocator_interception_mac_unittest.mm", "allocator/partition_allocator/shim/malloc_zone_functions_mac_unittest.cc", + "apple/backup_util_unittest.mm", "enterprise_util_mac_unittest.mm", - "mac/backup_util_unittest.mm", "mac/bind_objc_block_unittest.mm", "mac/call_with_eh_frame_unittest.mm", "mac/dispatch_source_mach_unittest.cc", @@ -3756,7 +3725,7 @@ sources += [ # Pull in specific Mac files for iOS. - "mac/backup_util_unittest.mm", + "apple/backup_util_unittest.mm", "mac/bind_objc_block_unittest.mm", "mac/foundation_util_unittest.mm", "mac/scoped_nsobject_unittest.mm",
diff --git a/base/mac/backup_util.h b/base/apple/backup_util.h similarity index 83% rename from base/mac/backup_util.h rename to base/apple/backup_util.h index 9bb2560..6a4e638 100644 --- a/base/mac/backup_util.h +++ b/base/apple/backup_util.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 BASE_MAC_BACKUP_UTIL_H_ -#define BASE_MAC_BACKUP_UTIL_H_ +#ifndef BASE_APPLE_BACKUP_UTIL_H_ +#define BASE_APPLE_BACKUP_UTIL_H_ #include "base/base_export.h" @@ -11,7 +11,7 @@ class FilePath; } -namespace base::mac { +namespace base::apple { // Returns true if the file or directory at `file_path` is excluded from // OS-managed backups. @@ -26,6 +26,6 @@ // occurs. BASE_EXPORT bool ClearBackupExclusion(const FilePath& file_path); -} // namespace base::mac +} // namespace base::apple -#endif // BASE_MAC_BACKUP_UTIL_H_ +#endif // BASE_APPLE_BACKUP_UTIL_H_
diff --git a/base/mac/backup_util.mm b/base/apple/backup_util.mm similarity index 90% rename from base/mac/backup_util.mm rename to base/apple/backup_util.mm index 2c4139c..aeb34b7 100644 --- a/base/mac/backup_util.mm +++ b/base/apple/backup_util.mm
@@ -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 "base/mac/backup_util.h" +#include "base/apple/backup_util.h" #import <Foundation/Foundation.h> @@ -12,13 +12,13 @@ #include "base/strings/sys_string_conversions.h" #include "base/threading/scoped_blocking_call.h" -namespace base::mac { +namespace base::apple { bool GetBackupExclusion(const FilePath& file_path) { base::ScopedBlockingCall scoped_blocking_call(FROM_HERE, base::BlockingType::MAY_BLOCK); - NSURL* file_url = FilePathToNSURL(file_path); + NSURL* file_url = mac::FilePathToNSURL(file_path); DCHECK([file_url checkPromisedItemIsReachableAndReturnError:nil]); NSError* error = nil; @@ -40,7 +40,7 @@ base::ScopedBlockingCall scoped_blocking_call(FROM_HERE, base::BlockingType::MAY_BLOCK); - NSURL* file_url = FilePathToNSURL(file_path); + NSURL* file_url = mac::FilePathToNSURL(file_path); DCHECK([file_url checkPromisedItemIsReachableAndReturnError:nil]); NSError* error = nil; @@ -61,4 +61,4 @@ return SetBackupState(file_path, false); } -} // namespace base::mac +} // namespace base::apple
diff --git a/base/mac/backup_util_unittest.mm b/base/apple/backup_util_unittest.mm similarity index 94% rename from base/mac/backup_util_unittest.mm rename to base/apple/backup_util_unittest.mm index ec95a08..219a997 100644 --- a/base/mac/backup_util_unittest.mm +++ b/base/apple/backup_util_unittest.mm
@@ -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 "base/mac/backup_util.h" +#include "base/apple/backup_util.h" #include <stddef.h> #include <stdint.h> @@ -17,7 +17,7 @@ #include "testing/gtest/include/gtest/gtest.h" #include "testing/platform_test.h" -namespace base::mac { +namespace base::apple { namespace { @@ -45,7 +45,7 @@ ASSERT_TRUE(temp_dir_.CreateUniqueTempDir()); FilePath excluded_file_path = temp_dir_.GetPath().Append("excluded"); base::ScopedCFTypeRef<CFURLRef> excluded_url = - base::mac::FilePathToCFURL(excluded_file_path); + mac::FilePathToCFURL(excluded_file_path); constexpr char placeholder_data[] = "All your base are belong to us!"; ASSERT_EQ(checked_cast<int>(std::size(placeholder_data)), @@ -67,4 +67,4 @@ } // namespace -} // namespace base::mac +} // namespace base::apple
diff --git a/base/mac/bundle_locations.h b/base/apple/bundle_locations.h similarity index 92% rename from base/mac/bundle_locations.h rename to base/apple/bundle_locations.h index eb498665..c75707d3 100644 --- a/base/mac/bundle_locations.h +++ b/base/apple/bundle_locations.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 BASE_MAC_BUNDLE_LOCATIONS_H_ -#define BASE_MAC_BUNDLE_LOCATIONS_H_ +#ifndef BASE_APPLE_BUNDLE_LOCATIONS_H_ +#define BASE_APPLE_BUNDLE_LOCATIONS_H_ #include "base/base_export.h" #include "base/files/file_path.h" @@ -16,7 +16,7 @@ class FilePath; } -namespace base::mac { +namespace base::apple { // This file provides several functions to explicitly request the various // component bundles of Chrome. Please use these methods rather than calling @@ -63,6 +63,6 @@ BASE_EXPORT void SetOverrideFrameworkBundle(NSBundle* bundle); #endif // __OBJC__ -} // namespace base::mac +} // namespace base::apple -#endif // BASE_MAC_BUNDLE_LOCATIONS_H_ +#endif // BASE_APPLE_BUNDLE_LOCATIONS_H_
diff --git a/base/mac/bundle_locations.mm b/base/apple/bundle_locations.mm similarity index 81% rename from base/mac/bundle_locations.mm rename to base/apple/bundle_locations.mm index 111be3b..89ad6c1 100644 --- a/base/mac/bundle_locations.mm +++ b/base/apple/bundle_locations.mm
@@ -2,13 +2,13 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "base/mac/bundle_locations.h" +#include "base/apple/bundle_locations.h" #include "base/check.h" #include "base/mac/foundation_util.h" #include "base/strings/sys_string_conversions.h" -namespace base::mac { +namespace base::apple { // NSBundle isn't threadsafe, all functions in this file must be called on the // main thread. @@ -24,12 +24,13 @@ } FilePath MainBundlePath() { - return NSStringToFilePath(MainBundle().bundlePath); + return mac::NSStringToFilePath(MainBundle().bundlePath); } NSBundle* OuterBundle() { - if (g_override_outer_bundle) + if (g_override_outer_bundle) { return g_override_outer_bundle; + } return NSBundle.mainBundle; } @@ -38,17 +39,18 @@ } FilePath OuterBundlePath() { - return NSStringToFilePath(OuterBundle().bundlePath); + return mac::NSStringToFilePath(OuterBundle().bundlePath); } NSBundle* FrameworkBundle() { - if (g_override_framework_bundle) + if (g_override_framework_bundle) { return g_override_framework_bundle; + } return NSBundle.mainBundle; } FilePath FrameworkBundlePath() { - return NSStringToFilePath(FrameworkBundle().bundlePath); + return mac::NSStringToFilePath(FrameworkBundle().bundlePath); } static void AssignOverrideBundle(NSBundle* new_bundle, @@ -63,7 +65,7 @@ NSBundle** override_bundle) { NSBundle* new_bundle = nil; if (!file_path.empty()) { - new_bundle = [NSBundle bundleWithURL:base::mac::FilePathToNSURL(file_path)]; + new_bundle = [NSBundle bundleWithURL:mac::FilePathToNSURL(file_path)]; CHECK(new_bundle) << "Failed to load the bundle at " << file_path.value(); } AssignOverrideBundle(new_bundle, override_bundle); @@ -85,4 +87,4 @@ AssignOverridePath(file_path, &g_override_framework_bundle); } -} // namespace base::mac +} // namespace base::apple
diff --git a/base/base_paths_mac.mm b/base/base_paths_mac.mm index 1a20e54cc..eaa6829 100644 --- a/base/base_paths_mac.mm +++ b/base/base_paths_mac.mm
@@ -10,11 +10,11 @@ #include <mach-o/dyld.h> #include <stdint.h> +#include "base/apple/bundle_locations.h" #include "base/base_paths.h" #include "base/check_op.h" #include "base/files/file_path.h" #include "base/files/file_util.h" -#include "base/mac/bundle_locations.h" #include "base/mac/foundation_util.h" #include "base/notreached.h" #include "base/path_service.h" @@ -123,11 +123,11 @@ return PathService::Get(base::DIR_MODULE, result); } #if BUILDFLAG(IS_IOS_MACCATALYST) - *result = base::mac::MainBundlePath() + *result = base::apple::MainBundlePath() .Append(FILE_PATH_LITERAL("Contents")) .Append(FILE_PATH_LITERAL("Resources")); #else - *result = base::mac::FrameworkBundlePath().Append( + *result = base::apple::FrameworkBundlePath().Append( FILE_PATH_LITERAL("Resources")); #endif // BUILDFLAG(IS_IOS_MACCATALYST) return true;
diff --git a/base/file_version_info_mac.mm b/base/file_version_info_mac.mm index 42488051..616ee657 100644 --- a/base/file_version_info_mac.mm +++ b/base/file_version_info_mac.mm
@@ -6,8 +6,8 @@ #import <Foundation/Foundation.h> +#include "base/apple/bundle_locations.h" #include "base/files/file_path.h" -#include "base/mac/bundle_locations.h" #include "base/mac/foundation_util.h" #include "base/strings/sys_string_conversions.h" #include "build/build_config.h" @@ -21,7 +21,7 @@ // static std::unique_ptr<FileVersionInfo> FileVersionInfo::CreateFileVersionInfoForCurrentModule() { - return CreateFileVersionInfo(base::mac::FrameworkBundlePath()); + return CreateFileVersionInfo(base::apple::FrameworkBundlePath()); } // static
diff --git a/base/files/file_path_watcher_fsevents.mm b/base/files/file_path_watcher_fsevents.cc similarity index 80% rename from base/files/file_path_watcher_fsevents.mm rename to base/files/file_path_watcher_fsevents.cc index 403c0e6..6c9461e 100644 --- a/base/files/file_path_watcher_fsevents.mm +++ b/base/files/file_path_watcher_fsevents.cc
@@ -18,10 +18,6 @@ #include "base/task/sequenced_task_runner.h" #include "base/threading/scoped_blocking_call.h" -#if !defined(__has_feature) || !__has_feature(objc_arc) -#error "This file requires ARC support." -#endif - namespace base { namespace { @@ -34,8 +30,8 @@ const unsigned kMaxLinksToResolve = 255; std::vector<FilePath::StringType> component_vector = path.GetComponents(); - std::list<FilePath::StringType> components(component_vector.begin(), - component_vector.end()); + std::list<FilePath::StringType> + components(component_vector.begin(), component_vector.end()); FilePath result; unsigned resolve_count = 0; @@ -52,9 +48,8 @@ FilePath target; if (ReadSymbolicLink(current, &target)) { - if (target.IsAbsolute()) { + if (target.IsAbsolute()) result.clear(); - } std::vector<FilePath::StringType> target_components = target.GetComponents(); components.insert(components.begin(), target_components.begin(), @@ -65,25 +60,18 @@ } } - if (resolve_count >= kMaxLinksToResolve) { + if (resolve_count >= kMaxLinksToResolve) result.clear(); - } return result; } } // namespace -struct FilePathWatcherFSEvents::ObjCStorage { - // The dispatch queue on which the event stream is scheduled. - dispatch_queue_t __strong queue; -}; - FilePathWatcherFSEvents::FilePathWatcherFSEvents() - : objc_storage_(std::make_unique<ObjCStorage>()) { - objc_storage_->queue = dispatch_queue_create( - base::StringPrintf("org.chromium.base.FilePathWatcher.%p", this).c_str(), - DISPATCH_QUEUE_SERIAL); -} + : queue_(dispatch_queue_create( + base::StringPrintf("org.chromium.base.FilePathWatcher.%p", this) + .c_str(), + DISPATCH_QUEUE_SERIAL)) {} FilePathWatcherFSEvents::~FilePathWatcherFSEvents() { DCHECK(!task_runner() || task_runner()->RunsTasksInCurrentSequence()); @@ -99,9 +87,8 @@ // This class could support non-recursive watches, but that is currently // left to FilePathWatcherKQueue. - if (type != Type::kRecursive) { + if (type != Type::kRecursive) return false; - } set_task_runner(SequencedTaskRunner::GetCurrentDefault()); callback_ = callback; @@ -112,8 +99,8 @@ // captured by the block's scope. const FilePath path_copy(path); - dispatch_async(objc_storage_->queue, ^{ - StartEventStream(start_event, path_copy); + dispatch_async(queue_, ^{ + StartEventStream(start_event, path_copy); }); return true; } @@ -126,7 +113,7 @@ // Switch to the dispatch queue to tear down the event stream. As the queue is // owned by |this|, and this method is called from the destructor, execute the // block synchronously. - dispatch_sync(objc_storage_->queue, ^{ + dispatch_sync(queue_, ^{ if (fsevent_stream_) { DestroyEventStream(); target_.clear(); @@ -149,14 +136,12 @@ std::vector<FilePath> paths; FSEventStreamEventId root_change_at = FSEventStreamGetLatestEventId(stream); for (size_t i = 0; i < num_events; i++) { - if (flags[i] & kFSEventStreamEventFlagRootChanged) { + if (flags[i] & kFSEventStreamEventFlagRootChanged) root_changed = true; - } - if (event_ids[i]) { + if (event_ids[i]) root_change_at = std::min(root_change_at, event_ids[i]); - } - paths.push_back(FilePath(reinterpret_cast<char**>(event_paths)[i]) - .StripTrailingSeparators()); + paths.push_back(FilePath( + reinterpret_cast<char**>(event_paths)[i]).StripTrailingSeparators()); } // Reinitialize the event stream if we find changes to the root. This is @@ -178,11 +163,10 @@ FROM_HERE, BindOnce( [](WeakPtr<FilePathWatcherFSEvents> weak_watcher, FSEventStreamEventId root_change_at) { - if (!weak_watcher) { + if (!weak_watcher) return; - } FilePathWatcherFSEvents* watcher = weak_watcher.get(); - dispatch_async(watcher->objc_storage_->queue, ^{ + dispatch_async(watcher->queue_, ^{ watcher->UpdateEventStream(root_change_at); }); }, @@ -223,35 +207,35 @@ FSEventStreamEventId start_event) { // It can happen that the watcher gets canceled while tasks that call this // function are still in flight, so abort if this situation is detected. - if (resolved_target_.empty()) { + if (resolved_target_.empty()) return; - } - if (fsevent_stream_) { + if (fsevent_stream_) DestroyEventStream(); - } ScopedCFTypeRef<CFStringRef> cf_path(CFStringCreateWithCString( - nullptr, resolved_target_.value().c_str(), kCFStringEncodingMacHFS)); + NULL, resolved_target_.value().c_str(), kCFStringEncodingMacHFS)); ScopedCFTypeRef<CFStringRef> cf_dir_path(CFStringCreateWithCString( - nullptr, resolved_target_.DirName().value().c_str(), + NULL, resolved_target_.DirName().value().c_str(), kCFStringEncodingMacHFS)); - CFStringRef paths_array[] = {cf_path.get(), cf_dir_path.get()}; + CFStringRef paths_array[] = { cf_path.get(), cf_dir_path.get() }; ScopedCFTypeRef<CFArrayRef> watched_paths( - CFArrayCreate(nullptr, reinterpret_cast<const void**>(paths_array), + CFArrayCreate(NULL, reinterpret_cast<const void**>(paths_array), std::size(paths_array), &kCFTypeArrayCallBacks)); FSEventStreamContext context; context.version = 0; context.info = this; - context.retain = nullptr; - context.release = nullptr; - context.copyDescription = nullptr; + context.retain = NULL; + context.release = NULL; + context.copyDescription = NULL; - fsevent_stream_ = FSEventStreamCreate( - nullptr, &FSEventsCallback, &context, watched_paths, start_event, - kEventLatencySeconds, kFSEventStreamCreateFlagWatchRoot); - FSEventStreamSetDispatchQueue(fsevent_stream_, objc_storage_->queue); + fsevent_stream_ = FSEventStreamCreate(NULL, &FSEventsCallback, &context, + watched_paths, + start_event, + kEventLatencySeconds, + kFSEventStreamCreateFlagWatchRoot); + FSEventStreamSetDispatchQueue(fsevent_stream_, queue_); if (!FSEventStreamStart(fsevent_stream_)) { task_runner()->PostTask(FROM_HERE, @@ -283,7 +267,7 @@ FSEventStreamStop(fsevent_stream_); FSEventStreamInvalidate(fsevent_stream_); FSEventStreamRelease(fsevent_stream_); - fsevent_stream_ = nullptr; + fsevent_stream_ = NULL; } void FilePathWatcherFSEvents::StartEventStream(FSEventStreamEventId start_event,
diff --git a/base/files/file_path_watcher_fsevents.h b/base/files/file_path_watcher_fsevents.h index ed929a1..989aed20 100644 --- a/base/files/file_path_watcher_fsevents.h +++ b/base/files/file_path_watcher_fsevents.h
@@ -12,6 +12,7 @@ #include "base/files/file_path.h" #include "base/files/file_path_watcher.h" +#include "base/mac/scoped_dispatch_object.h" #include "base/memory/weak_ptr.h" namespace base { @@ -74,6 +75,9 @@ // (Only accessed from the task_runner() thread.) FilePathWatcher::Callback callback_; + // The dispatch queue on which the event stream is scheduled. + ScopedDispatchObject<dispatch_queue_t> queue_; + // Target path to watch (passed to callback). // (Only accessed from the libdispatch queue.) FilePath target_; @@ -86,9 +90,6 @@ // (Only accessed from the libdispatch queue.) FSEventStreamRef fsevent_stream_ = nullptr; - struct ObjCStorage; - std::unique_ptr<ObjCStorage> objc_storage_; - WeakPtrFactory<FilePathWatcherFSEvents> weak_factory_{this}; };
diff --git a/base/mac/authorization_util.mm b/base/mac/authorization_util.mm index a2cc9e2b..c043835 100644 --- a/base/mac/authorization_util.mm +++ b/base/mac/authorization_util.mm
@@ -10,8 +10,8 @@ #include <string> +#include "base/apple/bundle_locations.h" #include "base/logging.h" -#include "base/mac/bundle_locations.h" #include "base/mac/foundation_util.h" #include "base/mac/mac_logging.h" #include "base/mac/scoped_authorizationref.h" @@ -60,8 +60,8 @@ // product_logo_32.png is used instead of app.icns because Authorization // Services can't deal with .icns files. NSString* icon_path = - [base::mac::FrameworkBundle() pathForResource:@"product_logo_32" - ofType:@"png"]; + [base::apple::FrameworkBundle() pathForResource:@"product_logo_32" + ofType:@"png"]; const char* icon_path_c = [icon_path fileSystemRepresentation]; size_t icon_path_length = icon_path_c ? strlen(icon_path_c) : 0;
diff --git a/base/mac/dispatch_source_mach.cc b/base/mac/dispatch_source_mach.cc new file mode 100644 index 0000000..3ea4f19 --- /dev/null +++ b/base/mac/dispatch_source_mach.cc
@@ -0,0 +1,46 @@ +// Copyright 2014 The Chromium Authors +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "base/mac/dispatch_source_mach.h" + +namespace base { + +DispatchSourceMach::DispatchSourceMach(const char* name, + mach_port_t port, + void (^event_handler)()) + : DispatchSourceMach(dispatch_queue_create(name, DISPATCH_QUEUE_SERIAL), + port, + event_handler) { + // Since the queue was created above in the delegated constructor, and it was + // subsequently retained, release it here. + dispatch_release(queue_); +} + +DispatchSourceMach::DispatchSourceMach(dispatch_queue_t queue, + mach_port_t port, + void (^event_handler)()) + : queue_(queue, base::scoped_policy::RETAIN), + source_(dispatch_source_create(DISPATCH_SOURCE_TYPE_MACH_RECV, + port, 0, queue_)), + source_canceled_(dispatch_semaphore_create(0)) { + dispatch_source_set_event_handler(source_, event_handler); + dispatch_source_set_cancel_handler(source_, ^{ + dispatch_semaphore_signal(source_canceled_); + }); +} + +DispatchSourceMach::~DispatchSourceMach() { + // Cancel the source and wait for the semaphore to be signaled. This will + // ensure the source managed by this class is not used after it is freed. + dispatch_source_cancel(source_); + source_.reset(); + + dispatch_semaphore_wait(source_canceled_, DISPATCH_TIME_FOREVER); +} + +void DispatchSourceMach::Resume() { + dispatch_resume(source_); +} + +} // namespace base
diff --git a/base/mac/dispatch_source_mach.h b/base/mac/dispatch_source_mach.h index 039493aa..1585677 100644 --- a/base/mac/dispatch_source_mach.h +++ b/base/mac/dispatch_source_mach.h
@@ -7,9 +7,8 @@ #include <dispatch/dispatch.h> -#include <memory> - #include "base/base_export.h" +#include "base/mac/scoped_dispatch_object.h" namespace base { @@ -43,11 +42,17 @@ // be received. void Resume(); - dispatch_queue_t queue() const; + dispatch_queue_t queue() const { return queue_.get(); } private: - struct ObjCStorage; - std::unique_ptr<ObjCStorage> objc_storage_; + // The dispatch queue used to service the source_. + ScopedDispatchObject<dispatch_queue_t> queue_; + + // A MACH_RECV dispatch source. + ScopedDispatchObject<dispatch_source_t> source_; + + // Semaphore used to wait on the |source_|'s cancellation in the destructor. + ScopedDispatchObject<dispatch_semaphore_t> source_canceled_; }; } // namespace base
diff --git a/base/mac/dispatch_source_mach.mm b/base/mac/dispatch_source_mach.mm deleted file mode 100644 index 72c72a3..0000000 --- a/base/mac/dispatch_source_mach.mm +++ /dev/null
@@ -1,64 +0,0 @@ -// Copyright 2014 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "base/mac/dispatch_source_mach.h" - -#if !defined(__has_feature) || !__has_feature(objc_arc) -#error "This file requires ARC support." -#endif - -namespace base { - -struct DispatchSourceMach::ObjCStorage { - // The dispatch queue used to service the source_. - dispatch_queue_t __strong queue; - - // A MACH_RECV dispatch source. - dispatch_source_t __strong source; - - // Semaphore used to wait on the |source_|'s cancellation in the destructor. - dispatch_semaphore_t __strong source_canceled; -}; - -DispatchSourceMach::DispatchSourceMach(const char* name, - mach_port_t port, - void (^event_handler)()) - : DispatchSourceMach(dispatch_queue_create(name, DISPATCH_QUEUE_SERIAL), - port, - event_handler) {} - -DispatchSourceMach::DispatchSourceMach(dispatch_queue_t queue, - mach_port_t port, - void (^event_handler)()) - : objc_storage_(std::make_unique<ObjCStorage>()) { - objc_storage_->queue = queue; - objc_storage_->source = dispatch_source_create(DISPATCH_SOURCE_TYPE_MACH_RECV, - port, /*mask=*/0, queue); - objc_storage_->source_canceled = dispatch_semaphore_create(/*value=*/0); - - dispatch_source_set_event_handler(objc_storage_->source, event_handler); - dispatch_source_set_cancel_handler(objc_storage_->source, ^{ - dispatch_semaphore_signal(objc_storage_->source_canceled); - }); -} - -DispatchSourceMach::~DispatchSourceMach() { - // Cancel the source and wait for the semaphore to be signaled. This will - // ensure the source managed by this class is not used after it is freed. - dispatch_source_cancel(objc_storage_->source); - objc_storage_->source = nil; - - dispatch_semaphore_wait(objc_storage_->source_canceled, - DISPATCH_TIME_FOREVER); -} - -void DispatchSourceMach::Resume() { - dispatch_resume(objc_storage_->source); -} - -dispatch_queue_t DispatchSourceMach::queue() const { - return objc_storage_->queue; -} - -} // namespace base
diff --git a/base/mac/foundation_util.mm b/base/mac/foundation_util.mm index d2b217a..be594941 100644 --- a/base/mac/foundation_util.mm +++ b/base/mac/foundation_util.mm
@@ -10,9 +10,9 @@ #include <vector> +#include "base/apple/bundle_locations.h" #include "base/files/file_path.h" #include "base/logging.h" -#include "base/mac/bundle_locations.h" #include "base/mac/mac_logging.h" #include "base/notreached.h" #include "base/numerics/checked_math.h" @@ -55,7 +55,7 @@ return g_override_am_i_bundled_value; // Yes, this is cheap. - return [[base::mac::OuterBundle() bundlePath] hasSuffix:@".app"]; + return [[base::apple::OuterBundle() bundlePath] hasSuffix:@".app"]; #endif } @@ -94,12 +94,12 @@ // This function really does want to examine NSBundle's idea of the main // bundle dictionary. It needs to look at the actual running .app's // Info.plist to access its LSUIElement property. - NSDictionary* info_dictionary = [base::mac::MainBundle() infoDictionary]; + NSDictionary* info_dictionary = [base::apple::MainBundle() infoDictionary]; return [info_dictionary[@"LSUIElement"] boolValue] != NO; } FilePath PathForFrameworkBundleResource(const char* resource_name) { - NSBundle* bundle = base::mac::FrameworkBundle(); + NSBundle* bundle = base::apple::FrameworkBundle(); NSURL* resource_url = [bundle URLForResource:@(resource_name) withExtension:nil]; return NSURLToFilePath(resource_url);
diff --git a/base/mac/mac_util.mm b/base/mac/mac_util.mm index 363052e..c1a97b3 100644 --- a/base/mac/mac_util.mm +++ b/base/mac/mac_util.mm
@@ -15,9 +15,9 @@ #include <sys/utsname.h> #include <sys/xattr.h> +#include "base/apple/bundle_locations.h" #include "base/files/file_path.h" #include "base/logging.h" -#include "base/mac/bundle_locations.h" #include "base/mac/foundation_util.h" #include "base/mac/mac_logging.h" #include "base/mac/scoped_aedesc.h" @@ -96,7 +96,7 @@ } ScopedCFTypeRef<LSSharedFileListItemRef> GetLoginItemForMainApp() { - NSURL* url = [NSURL fileURLWithPath:[base::mac::MainBundle() bundlePath]]; + NSURL* url = [NSURL fileURLWithPath:[base::apple::MainBundle() bundlePath]]; return GetLoginItemForApp(url); }
diff --git a/base/mac/mach_port_rendezvous.mm b/base/mac/mach_port_rendezvous.cc similarity index 94% rename from base/mac/mach_port_rendezvous.mm rename to base/mac/mach_port_rendezvous.cc index ea444d24..892f65f8 100644 --- a/base/mac/mach_port_rendezvous.mm +++ b/base/mac/mach_port_rendezvous.cc
@@ -17,10 +17,6 @@ #include "base/notreached.h" #include "base/strings/stringprintf.h" -#if !defined(__has_feature) || !__has_feature(objc_arc) -#error "This file requires ARC support." -#endif - #if BUILDFLAG(IS_IOS) #include "base/ios/sim_header_shims.h" #else @@ -107,19 +103,6 @@ disposition_ = 0; } -struct MachPortRendezvousServer::ClientData { - ClientData(dispatch_source_t exit_watcher, MachPortsForRendezvous ports) - : exit_watcher(exit_watcher), ports(ports) {} - ClientData(ClientData&&) = default; - ~ClientData() = default; - - // A DISPATCH_SOURCE_TYPE_PROC / DISPATCH_PROC_EXIT dispatch source. When - // the source is triggered, it calls OnClientExited(). - dispatch_source_t __strong exit_watcher; - - MachPortsForRendezvous ports; -}; - // static MachPortRendezvousServer* MachPortRendezvousServer::GetInstance() { static auto* instance = new MachPortRendezvousServer(); @@ -133,9 +116,9 @@ DCHECK_LT(ports.size(), kMaximumRendezvousPorts); DCHECK(!ports.empty()); - dispatch_source_t exit_watcher = dispatch_source_create( + ScopedDispatchObject<dispatch_source_t> exit_watcher(dispatch_source_create( DISPATCH_SOURCE_TYPE_PROC, static_cast<uintptr_t>(pid), - DISPATCH_PROC_EXIT, dispatch_source_->queue()); + DISPATCH_PROC_EXIT, dispatch_source_->queue())); dispatch_source_set_event_handler(exit_watcher, ^{ OnClientExited(pid); }); @@ -146,6 +129,15 @@ DCHECK(it.second); } +MachPortRendezvousServer::ClientData::ClientData( + ScopedDispatchObject<dispatch_source_t> exit_watcher, + MachPortsForRendezvous ports) + : exit_watcher(exit_watcher), ports(ports) {} + +MachPortRendezvousServer::ClientData::ClientData(ClientData&&) = default; + +MachPortRendezvousServer::ClientData::~ClientData() = default; + MachPortRendezvousServer::MachPortRendezvousServer() { std::string bootstrap_name = StringPrintf(kBootstrapNameFormat, mac::BaseBundleID(), getpid()); @@ -162,7 +154,7 @@ dispatch_source_->Resume(); } -MachPortRendezvousServer::~MachPortRendezvousServer() = default; +MachPortRendezvousServer::~MachPortRendezvousServer() {} void MachPortRendezvousServer::HandleRequest() { // Receive the request message, using the kernel audit token to ascertain the @@ -280,7 +272,8 @@ client = nullptr; } return client; - }(); + } + (); return client; }
diff --git a/base/mac/mach_port_rendezvous.h b/base/mac/mach_port_rendezvous.h index 9ef1505..7d460a3 100644 --- a/base/mac/mach_port_rendezvous.h +++ b/base/mac/mach_port_rendezvous.h
@@ -16,6 +16,7 @@ #include "base/base_export.h" #include "base/mac/dispatch_source_mach.h" +#include "base/mac/scoped_dispatch_object.h" #include "base/mac/scoped_mach_port.h" #include "base/synchronization/lock.h" #include "base/thread_annotations.h" @@ -107,6 +108,19 @@ friend class MachPortRendezvousServerTest; friend struct MachPortRendezvousFuzzer; + struct ClientData { + ClientData(ScopedDispatchObject<dispatch_source_t> exit_watcher, + MachPortsForRendezvous ports); + ClientData(ClientData&&); + ~ClientData(); + + // A DISPATCH_SOURCE_TYPE_PROC / DISPATCH_PROC_EXIT dispatch source. When + // the source is triggered, it calls OnClientExited(). + ScopedDispatchObject<dispatch_source_t> exit_watcher; + + MachPortsForRendezvous ports; + }; + MachPortRendezvousServer(); ~MachPortRendezvousServer(); @@ -138,7 +152,6 @@ // Mach message dispatch source for |server_port_|. std::unique_ptr<DispatchSourceMach> dispatch_source_; - struct ClientData; Lock lock_; // Association of pid-to-ports. std::map<pid_t, ClientData> client_data_ GUARDED_BY(lock_);
diff --git a/base/mac/scoped_dispatch_object.h b/base/mac/scoped_dispatch_object.h new file mode 100644 index 0000000..26fda827 --- /dev/null +++ b/base/mac/scoped_dispatch_object.h
@@ -0,0 +1,36 @@ +// Copyright 2016 The Chromium Authors +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef BASE_MAC_SCOPED_DISPATCH_OBJECT_H_ +#define BASE_MAC_SCOPED_DISPATCH_OBJECT_H_ + +#include <dispatch/dispatch.h> + +#include "base/mac/scoped_typeref.h" + +namespace base { + +namespace internal { + +template <typename T> +struct ScopedDispatchObjectTraits { + static constexpr T InvalidValue() { return nullptr; } + static T Retain(T object) { + dispatch_retain(object); + return object; + } + static void Release(T object) { + dispatch_release(object); + } +}; + +} // namespace internal + +template <typename T> +using ScopedDispatchObject = + ScopedTypeRef<T, internal::ScopedDispatchObjectTraits<T>>; + +} // namespace base + +#endif // BASE_MAC_SCOPED_DISPATCH_OBJECT_H_
diff --git a/base/synchronization/waitable_event_watcher.h b/base/synchronization/waitable_event_watcher.h index 19b3685..cae22752 100644 --- a/base/synchronization/waitable_event_watcher.h +++ b/base/synchronization/waitable_event_watcher.h
@@ -16,8 +16,7 @@ #elif BUILDFLAG(IS_APPLE) #include <dispatch/dispatch.h> -#include <memory> - +#include "base/mac/scoped_dispatch_object.h" #include "base/memory/weak_ptr.h" #include "base/synchronization/waitable_event.h" #else @@ -132,8 +131,10 @@ // is waiting. Null if no event is being watched. scoped_refptr<WaitableEvent::ReceiveRight> receive_right_; - struct ObjCStorage; - std::unique_ptr<ObjCStorage> objc_storage_; + // A TYPE_MACH_RECV dispatch source on |receive_right_|. When a receive event + // is delivered, the message queue will be peeked and the bound |callback_| + // may be run. This will be null if nothing is currently being watched. + ScopedDispatchObject<dispatch_source_t> source_; // Used to vend a weak pointer for calling InvokeCallback() from the // |source_| event handler.
diff --git a/base/synchronization/waitable_event_watcher_mac.mm b/base/synchronization/waitable_event_watcher_mac.cc similarity index 67% rename from base/synchronization/waitable_event_watcher_mac.mm rename to base/synchronization/waitable_event_watcher_mac.cc index 143ffab..9c18429 100644 --- a/base/synchronization/waitable_event_watcher_mac.mm +++ b/base/synchronization/waitable_event_watcher_mac.cc
@@ -7,21 +7,9 @@ #include "base/functional/bind.h" #include "base/functional/callback.h" -#if !defined(__has_feature) || !__has_feature(objc_arc) -#error "This file requires ARC support." -#endif - namespace base { -struct WaitableEventWatcher::ObjCStorage { - // A TYPE_MACH_RECV dispatch source on |receive_right_|. When a receive event - // is delivered, the message queue will be peeked and the bound |callback_| - // may be run. This will be null if nothing is currently being watched. - dispatch_source_t __strong source; -}; - -WaitableEventWatcher::WaitableEventWatcher() - : objc_storage_(std::make_unique<ObjCStorage>()), weak_ptr_factory_(this) {} +WaitableEventWatcher::WaitableEventWatcher() : weak_ptr_factory_(this) {} WaitableEventWatcher::~WaitableEventWatcher() { StopWatching(); @@ -32,8 +20,7 @@ EventCallback callback, scoped_refptr<SequencedTaskRunner> task_runner) { DCHECK(task_runner->RunsTasksInCurrentSequence()); - DCHECK(!objc_storage_->source || - dispatch_source_testcancel(objc_storage_->source)); + DCHECK(!source_ || dispatch_source_testcancel(source_)); // Keep a reference to the receive right, so that if the event is deleted // out from under the watcher, a signal can still be observed. @@ -43,9 +30,9 @@ // Use the global concurrent queue here, since it is only used to thunk // to the real callback on the target task runner. - objc_storage_->source = dispatch_source_create( - DISPATCH_SOURCE_TYPE_MACH_RECV, receive_right_->Name(), /*mask=*/0, - dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, /*flags=*/0)); + source_.reset(dispatch_source_create( + DISPATCH_SOURCE_TYPE_MACH_RECV, receive_right_->Name(), 0, + dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0))); // Locals for capture by the block. Accessing anything through the |this| or // |event| pointers is not safe, since either may have been deleted by the @@ -53,10 +40,10 @@ WeakPtr<WaitableEventWatcher> weak_this = weak_ptr_factory_.GetWeakPtr(); const bool auto_reset = event->policy_ == WaitableEvent::ResetPolicy::AUTOMATIC; - dispatch_source_t source = objc_storage_->source; + dispatch_source_t source = source_.get(); mach_port_t name = receive_right_->Name(); - dispatch_source_set_event_handler(objc_storage_->source, ^{ + dispatch_source_set_event_handler(source_, ^{ // For automatic-reset events, only fire the callback if this watcher // can claim/dequeue the event. For manual-reset events, all watchers can // be called back. @@ -71,7 +58,7 @@ task_runner->PostTask( FROM_HERE, BindOnce(&WaitableEventWatcher::InvokeCallback, weak_this)); }); - dispatch_resume(objc_storage_->source); + dispatch_resume(source_); return true; } @@ -79,19 +66,18 @@ void WaitableEventWatcher::StopWatching() { callback_.Reset(); receive_right_ = nullptr; - if (objc_storage_->source) { - dispatch_source_cancel(objc_storage_->source); - objc_storage_->source = nil; + if (source_) { + dispatch_source_cancel(source_); + source_.reset(); } } void WaitableEventWatcher::InvokeCallback() { // The callback can be null if StopWatching() is called between signaling // and the |callback_| getting run on the target task runner. - if (callback_.is_null()) { + if (callback_.is_null()) return; - } - objc_storage_->source = nil; + source_.reset(); receive_right_ = nullptr; std::move(callback_).Run(); }
diff --git a/build/config/android/abi.gni b/build/config/android/abi.gni index e044ac6..1101b4a 100644 --- a/build/config/android/abi.gni +++ b/build/config/android/abi.gni
@@ -88,8 +88,10 @@ assert(false, "Unknown target CPU: $target_cpu") } -# Intentionally do not define android_app_secondary_abi_cpu and -# android_app_secondary_abi for 32-bit target_cpu, since they are not used. +# Do not define android_app_secondary_abi_cpu or android_app_secondary_abi for +# target_cpu's that are 32-bit-only or 64-bit-only, as they are not used. The +# presence of this variable may be used in conjunction with android_64bit_target_cpu +# to identify target_cpu's that are 32-bit-only or 64-bit-only. if (target_cpu == "arm64") { android_secondary_abi_cpu = "arm" android_app_secondary_abi = "armeabi-v7a"
diff --git a/build/util/android_chrome_version.py b/build/util/android_chrome_version.py index b50847f4..f00cd99d 100755 --- a/build/util/android_chrome_version.py +++ b/build/util/android_chrome_version.py
@@ -93,6 +93,16 @@ '64': [ ('CHROME', 'CHROME', '64'), ('CHROME_MODERN', 'CHROME_MODERN', '64'), + ('MONOCHROME', 'MONOCHROME', '64'), + ('TRICHROME', 'TRICHROME', '64'), + ('TRICHROME_BETA', 'TRICHROME_BETA', '64'), + ('WEBVIEW_STABLE', 'WEBVIEW_STABLE', '64'), + ('WEBVIEW_BETA', 'WEBVIEW_BETA', '64'), + ('WEBVIEW_DEV', 'WEBVIEW_DEV', '64'), + ], + 'hybrid': [ + ('CHROME', 'CHROME', '64'), + ('CHROME_MODERN', 'CHROME_MODERN', '64'), ('MONOCHROME', 'MONOCHROME', '32_64'), ('MONOCHROME_32', 'MONOCHROME', '32'), ('MONOCHROME_32_64', 'MONOCHROME', '32_64'), @@ -126,9 +136,12 @@ # Splits input build config architecture to manufacturer and bitness. _ARCH_TO_MFG_AND_BITNESS = { 'arm': ('arm', '32'), - 'arm64': ('arm', '64'), + 'arm64': ('arm', 'hybrid'), + # Until riscv64 needs a unique version code to ship APKs to the store, + # point to the 'arm' bitmask. + 'riscv64': ('arm', '64'), 'x86': ('intel', '32'), - 'x64': ('intel', '64'), + 'x64': ('intel', 'hybrid'), } # Expose the available choices to other scripts.
diff --git a/build/util/android_chrome_version_test.py b/build/util/android_chrome_version_test.py index 6213935..8b97961 100644 --- a/build/util/android_chrome_version_test.py +++ b/build/util/android_chrome_version_test.py
@@ -568,6 +568,69 @@ self.assertEqual(arch_trichrome_64_version_code, '575000039') self.assertEqual(arch_trichrome_auto_64_32_version_code, '575000058') + def testGenerateVersionCodesAndroidArchRiscv64(self): + """Assert it handles different architectures correctly. + + Version codes for different builds need to be distinct and maintain a + certain ordering. + See docs in android_chrome_version._ABIS_TO_BIT_MASK for + reasoning. + """ + output = GenerateVersionCodes(EXAMPLE_GROUPED_VERSION_VALUES, + arch='riscv64', + is_next_build=False) + arch_chrome_version_code = output['CHROME_VERSION_CODE'] + + self.assertEqual(arch_chrome_version_code, '575000004') + + def testGenerateVersionCodesAndroidArchRiscv64Variants(self): + """Assert it handles 64-bit-specific additional version codes correctly. + + Some additional version codes are generated for 64-bit architectures. + See docstring on android_chrome_version.ARCH64_APK_VARIANTS for more info. + """ + output = GenerateVersionCodes(EXAMPLE_GROUPED_VERSION_VALUES, + arch='riscv64', + is_next_build=False) + arch_chrome_version_code = output['CHROME_VERSION_CODE'] + arch_chrome_modern_version_code = output['CHROME_MODERN_VERSION_CODE'] + arch_monochrome_version_code = output['MONOCHROME_VERSION_CODE'] + arch_trichrome_version_code = output['TRICHROME_VERSION_CODE'] + arch_trichrome_beta_version_code = output['TRICHROME_BETA_VERSION_CODE'] + arch_webview_stable_version_code = output['WEBVIEW_STABLE_VERSION_CODE'] + arch_webview_beta_version_code = output['WEBVIEW_BETA_VERSION_CODE'] + arch_webview_dev_version_code = output['WEBVIEW_DEV_VERSION_CODE'] + + self.assertEqual(arch_chrome_version_code, '575000004') + self.assertEqual(arch_chrome_modern_version_code, '575000014') + self.assertEqual(arch_monochrome_version_code, '575000024') + self.assertFalse('MONOCHROME_32_VERSION_CODE' in output) + self.assertFalse('MONOCHROME_32_64_VERSION_CODE' in output) + self.assertFalse('MONOCHROME_64_32_VERSION_CODE' in output) + self.assertFalse('MONOCHROME_64_VERSION_CODE' in output) + self.assertEqual(arch_trichrome_version_code, '575000034') + self.assertFalse('TRICHROME_32_VERSION_CODE' in output) + self.assertFalse('TRICHROME_32_64_VERSION_CODE' in output) + self.assertFalse('TRICHROME_64_32_VERSION_CODE' in output) + self.assertFalse('TRICHROME_64_32_HIGH_VERSION_CODE' in output) + self.assertFalse('TRICHROME_AUTO_64_32_VERSION_CODE' in output) + self.assertFalse('TRICHROME_64_VERSION_CODE' in output) + self.assertEqual(arch_trichrome_beta_version_code, '575000044') + self.assertFalse('TRICHROME_32_BETA_VERSION_CODE' in output) + self.assertFalse('TRICHROME_32_64_BETA_VERSION_CODE' in output) + self.assertFalse('TRICHROME_64_32_BETA_VERSION_CODE' in output) + self.assertFalse('TRICHROME_64_32_HIGH_BETA_VERSION_CODE' in output) + self.assertFalse('TRICHROME_64_BETA_VERSION_CODE' in output) + self.assertEqual(arch_webview_stable_version_code, '575000004') + self.assertEqual(arch_webview_beta_version_code, '575000014') + self.assertEqual(arch_webview_dev_version_code, '575000024') + self.assertFalse('WEBVIEW_64_STABLE_VERSION_CODE' in output) + self.assertFalse('WEBVIEW_64_BETA_VERSION_CODE' in output) + self.assertFalse('WEBVIEW_64_DEV_VERSION_CODE' in output) + self.assertFalse('WEBVIEW_32_STABLE_VERSION_CODE' in output) + self.assertFalse('WEBVIEW_32_BETA_VERSION_CODE' in output) + self.assertFalse('WEBVIEW_32_DEV_VERSION_CODE' in output) + def testGenerateVersionCodesAndroidArchOrderArm(self): """Assert it handles different architectures correctly.
diff --git a/chrome/android/BUILD.gn b/chrome/android/BUILD.gn index 020d271..46bf7e2 100644 --- a/chrome/android/BUILD.gn +++ b/chrome/android/BUILD.gn
@@ -1737,6 +1737,7 @@ "//third_party/junit", "//third_party/metrics_proto:metrics_proto_java", "//third_party/mockito:mockito_java", + "//ui/accessibility:ax_base_java", "//ui/android:clipboard_java_test_support", "//ui/android:ui_java", "//ui/android:ui_java_test_support",
diff --git a/chrome/android/chrome_test_java_sources.gni b/chrome/android/chrome_test_java_sources.gni index 16575fa..e7ba6e3 100644 --- a/chrome/android/chrome_test_java_sources.gni +++ b/chrome/android/chrome_test_java_sources.gni
@@ -187,6 +187,7 @@ "javatests/src/org/chromium/chrome/browser/download/OMADownloadHandlerTest.java", "javatests/src/org/chromium/chrome/browser/download/ServicificationDownloadTest.java", "javatests/src/org/chromium/chrome/browser/download/dialogs/DownloadDialogIncognitoTest.java", + "javatests/src/org/chromium/chrome/browser/environment_integrity/EnvironmentIntegrityTest.java", "javatests/src/org/chromium/chrome/browser/externalnav/UrlOverridingTest.java", "javatests/src/org/chromium/chrome/browser/feature_engagement/ScreenshotTabObserverTest.java", "javatests/src/org/chromium/chrome/browser/feedback/ChromeFeedbackCollectorTest.java",
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/LauncherShortcutActivity.java b/chrome/android/java/src/org/chromium/chrome/browser/LauncherShortcutActivity.java index 997dc20..53049de 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/LauncherShortcutActivity.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/LauncherShortcutActivity.java
@@ -18,7 +18,6 @@ import org.chromium.chrome.R; import org.chromium.chrome.browser.incognito.IncognitoUtils; -import org.chromium.chrome.browser.multiwindow.MultiWindowUtils; import org.chromium.chrome.browser.preferences.ChromePreferenceKeys; import org.chromium.chrome.browser.preferences.SharedPreferencesManager; @@ -54,11 +53,8 @@ Intent newIntent = getChromeLauncherActivityIntent(this, intentAction); // Retain FLAG_ACTIVITY_MULTIPLE_TASK in the intent if present, to support multi-instance - // launch if lesser than the max number of instances is open. If the max number of instances - // is open, fall back to default ChromeLauncherActivity behavior for VIEW intents without - // this flag set. - if ((intent.getFlags() & Intent.FLAG_ACTIVITY_MULTIPLE_TASK) != 0 - && MultiWindowUtils.getInstanceCount() < MultiWindowUtils.getMaxInstances()) { + // launch behavior. + if ((intent.getFlags() & Intent.FLAG_ACTIVITY_MULTIPLE_TASK) != 0) { newIntent.setFlags(newIntent.getFlags() | Intent.FLAG_ACTIVITY_MULTIPLE_TASK); }
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/bookmarks/BookmarkManagerMediator.java b/chrome/android/java/src/org/chromium/chrome/browser/bookmarks/BookmarkManagerMediator.java index 5a233d1..247fc45 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/bookmarks/BookmarkManagerMediator.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/bookmarks/BookmarkManagerMediator.java
@@ -13,7 +13,6 @@ import android.graphics.drawable.Drawable; import android.text.TextUtils; import android.util.Pair; -import android.view.accessibility.AccessibilityManager; import androidx.annotation.Nullable; import androidx.annotation.VisibleForTesting; @@ -57,6 +56,7 @@ import org.chromium.components.feature_engagement.EventConstants; import org.chromium.components.image_fetcher.ImageFetcher; import org.chromium.components.power_bookmarks.PowerBookmarkMeta; +import org.chromium.ui.accessibility.AccessibilityState; import org.chromium.ui.modelutil.MVCListAdapter.ListItem; import org.chromium.ui.modelutil.MVCListAdapter.ModelList; import org.chromium.ui.modelutil.PropertyModel; @@ -81,50 +81,23 @@ private class BookmarkDragStateDelegate implements DragStateDelegate { private BookmarkDelegate mBookmarkDelegate; private SelectionDelegate<BookmarkId> mSelectionDelegate; - private AccessibilityManager mA11yManager; - private AccessibilityManager.AccessibilityStateChangeListener mA11yChangeListener; - private boolean mA11yEnabled; void onBookmarkDelegateInitialized(BookmarkDelegate delegate) { mBookmarkDelegate = delegate; - mSelectionDelegate = delegate.getSelectionDelegate(); - - mA11yManager = - (AccessibilityManager) getSelectableListLayout().getContext().getSystemService( - Context.ACCESSIBILITY_SERVICE); - mA11yEnabled = mA11yManager.isEnabled(); - mA11yChangeListener = enabled -> mA11yEnabled = enabled; - mA11yManager.addAccessibilityStateChangeListener(mA11yChangeListener); - } - - void destroy() { - if (mA11yManager != null) { - mA11yManager.removeAccessibilityStateChangeListener(mA11yChangeListener); - } } // DragStateDelegate implementation @Override public boolean getDragEnabled() { - return !mA11yEnabled && mBookmarkDelegate.getCurrentUiMode() == BookmarkUiMode.FOLDER; + return !AccessibilityState.isPerformGesturesEnabled() + && mBookmarkDelegate.getCurrentUiMode() == BookmarkUiMode.FOLDER; } @Override public boolean getDragActive() { return getDragEnabled() && mSelectionDelegate.isSelectionEnabled(); } - - @VisibleForTesting - @Override - public void setA11yStateForTesting(boolean a11yEnabled) { - if (mA11yManager != null) { - mA11yManager.removeAccessibilityStateChangeListener(mA11yChangeListener); - } - mA11yChangeListener = null; - mA11yManager = null; - mA11yEnabled = a11yEnabled; - } } private final BookmarkModelObserver mBookmarkModelObserver = new BookmarkModelObserver() { @@ -446,7 +419,6 @@ PartnerBookmarksReader.removeFaviconUpdateObserver(this); mBookmarkUndoController.destroy(); - mDragStateDelegate.destroy(); mBookmarkQueryHandler.destroy(); mBookmarkUiPrefs.removeObserver(mBookmarkUiPrefsObserver);
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/tab/TabImpl.java b/chrome/android/java/src/org/chromium/chrome/browser/tab/TabImpl.java index 4b901481..c85f3f6c 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/tab/TabImpl.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/tab/TabImpl.java
@@ -1288,7 +1288,14 @@ mIsLoading = false; RewindableIterator<TabObserver> observers = getTabObservers(); - while (observers.hasNext()) observers.next().onCrash(this); + // When the renderer crashes for a hidden tab, we can skip notifying the observers to crash + // the underlying tab. This is because it is safe to keep the tab around without a renderer + // process, and since the tab is hidden, we don't need to show a sad tab. Since we already + // call setNeedsReload, when the tab goes foreground it will be reloaded instead of showing + // a sad tab. + if (!isHidden()) { + while (observers.hasNext()) observers.next().onCrash(this); + } mIsBeingRestored = false; }
diff --git a/chrome/android/javatests/src/org/chromium/chrome/browser/WarmupManagerTest.java b/chrome/android/javatests/src/org/chromium/chrome/browser/WarmupManagerTest.java index 3849979..54e33d6 100644 --- a/chrome/android/javatests/src/org/chromium/chrome/browser/WarmupManagerTest.java +++ b/chrome/android/javatests/src/org/chromium/chrome/browser/WarmupManagerTest.java
@@ -436,26 +436,26 @@ histogramWatcher.assertExpected(); } - /** Tests that when SpareTab is destroyed when the renderer is killed. */ + /** Tests that when SpareTab is not destroyed when the renderer is killed. */ @Test @MediumTest @Feature({"SpareTab"}) @EnableFeatures(ChromeFeatureList.SPARE_TAB) @UiThreadTest - public void testDestroySpareTabWhenRendererKilled() { + public void testDontDestroySpareTabWhenRendererKilled() { // Set the param to true allowing renderer initialization. WarmupManager.SPARE_TAB_INITIALIZE_RENDERER.setForTesting(true); var histogramWatcher = HistogramWatcher.newSingleRecordWatcher( - HISTOGRAM_SPARE_TAB_FINAL_STATUS, SpareTabFinalStatus.TAB_CRASHED); + HISTOGRAM_SPARE_TAB_FINAL_STATUS, SpareTabFinalStatus.TAB_USED); mWarmupManager.createSpareTab(mActivityTestRule.getActivity().getCurrentTabCreator(), TabLaunchType.FROM_START_SURFACE); - // Kill the renderer process, this should kill the associated spare tab and record - // TAB_CRASHED status. + // Kill the renderer process, this shouldn't kill the associated spare tab and record + // TAB_CREATED status. WebContentsUtils.simulateRendererKilled(mWarmupManager.mSpareTab.getWebContents()); - Assert.assertNull(mWarmupManager.takeSpareTab(false, TabLaunchType.FROM_START_SURFACE)); + Assert.assertNotNull(mWarmupManager.takeSpareTab(false, TabLaunchType.FROM_START_SURFACE)); histogramWatcher.assertExpected(); }
diff --git a/chrome/android/javatests/src/org/chromium/chrome/browser/app/bookmarks/BookmarkTabletTest.java b/chrome/android/javatests/src/org/chromium/chrome/browser/app/bookmarks/BookmarkTabletTest.java index 2f6b850..4c3db36 100644 --- a/chrome/android/javatests/src/org/chromium/chrome/browser/app/bookmarks/BookmarkTabletTest.java +++ b/chrome/android/javatests/src/org/chromium/chrome/browser/app/bookmarks/BookmarkTabletTest.java
@@ -36,6 +36,7 @@ import org.chromium.chrome.test.util.browser.Features; import org.chromium.components.embedder_support.util.UrlConstants; import org.chromium.content_public.browser.test.util.TestThreadUtils; +import org.chromium.ui.accessibility.AccessibilityState; import org.chromium.ui.test.util.UiRestriction; /** Tests for the bookmark manager on tablet. */ @@ -76,7 +77,7 @@ .getManagerForTesting(); TestThreadUtils.runOnUiThreadBlocking( - () -> getBookmarkDelegate().getDragStateDelegate().setA11yStateForTesting(false)); + () -> AccessibilityState.setIsAnyAccessibilityServiceEnabledForTesting(false)); } private BookmarkDelegate getBookmarkDelegate() {
diff --git a/chrome/android/javatests/src/org/chromium/chrome/browser/app/bookmarks/BookmarkTest.java b/chrome/android/javatests/src/org/chromium/chrome/browser/app/bookmarks/BookmarkTest.java index 565e6b34..5b6ace9 100644 --- a/chrome/android/javatests/src/org/chromium/chrome/browser/app/bookmarks/BookmarkTest.java +++ b/chrome/android/javatests/src/org/chromium/chrome/browser/app/bookmarks/BookmarkTest.java
@@ -114,6 +114,7 @@ import org.chromium.content_public.browser.test.util.TestThreadUtils; import org.chromium.content_public.browser.test.util.TouchCommon; import org.chromium.net.test.EmbeddedTestServer; +import org.chromium.ui.accessibility.AccessibilityState; import org.chromium.ui.test.util.NightModeTestUtils; import org.chromium.ui.test.util.UiRestriction; import org.chromium.url.GURL; @@ -1774,7 +1775,8 @@ mAdapter = (DragReorderableRecyclerViewAdapter) mItemsContainer.getAdapter(); mToolbar = mBookmarkManagerCoordinator.getToolbarForTesting(); - runOnUiThreadBlocking(() -> mDelegate.getDragStateDelegate().setA11yStateForTesting(false)); + runOnUiThreadBlocking( + () -> AccessibilityState.setIsAnyAccessibilityServiceEnabledForTesting(false)); } private boolean isItemPresentInBookmarkList(final String expectedTitle) {
diff --git a/chrome/android/javatests/src/org/chromium/chrome/browser/app/bookmarks/ReadingListTest.java b/chrome/android/javatests/src/org/chromium/chrome/browser/app/bookmarks/ReadingListTest.java index 36089500..e59498b 100644 --- a/chrome/android/javatests/src/org/chromium/chrome/browser/app/bookmarks/ReadingListTest.java +++ b/chrome/android/javatests/src/org/chromium/chrome/browser/app/bookmarks/ReadingListTest.java
@@ -72,6 +72,7 @@ import org.chromium.content_public.browser.test.util.TestThreadUtils; import org.chromium.content_public.browser.test.util.TouchCommon; import org.chromium.net.test.EmbeddedTestServer; +import org.chromium.ui.accessibility.AccessibilityState; import org.chromium.ui.test.util.DisableAnimationsTestRule; import org.chromium.ui.test.util.UiRestriction; import org.chromium.url.GURL; @@ -150,7 +151,7 @@ } TestThreadUtils.runOnUiThreadBlocking( - () -> getBookmarkDelegate().getDragStateDelegate().setA11yStateForTesting(false)); + () -> AccessibilityState.setIsAnyAccessibilityServiceEnabledForTesting(false)); RecyclerViewTestUtils.waitForStableRecyclerView(mItemsContainer); }
diff --git a/chrome/android/javatests/src/org/chromium/chrome/browser/bookmarks/BookmarkOpenerTest.java b/chrome/android/javatests/src/org/chromium/chrome/browser/bookmarks/BookmarkOpenerTest.java index f89b319..d97da5ee4 100644 --- a/chrome/android/javatests/src/org/chromium/chrome/browser/bookmarks/BookmarkOpenerTest.java +++ b/chrome/android/javatests/src/org/chromium/chrome/browser/bookmarks/BookmarkOpenerTest.java
@@ -39,6 +39,7 @@ import org.chromium.components.browser_ui.widget.RecyclerViewTestUtils; import org.chromium.components.embedder_support.util.UrlConstants; import org.chromium.content_public.browser.test.util.TestThreadUtils; +import org.chromium.ui.accessibility.AccessibilityState; import org.chromium.url.GURL; import java.util.ArrayList; @@ -103,7 +104,7 @@ } TestThreadUtils.runOnUiThreadBlocking(() -> { - getBookmarkDelegate().getDragStateDelegate().setA11yStateForTesting(false); + AccessibilityState.setIsAnyAccessibilityServiceEnabledForTesting(false); mBookmarkOpener = mBookmarkManagerCoordinator.getBookmarkOpenerForTesting(); }); }
diff --git a/chrome/android/javatests/src/org/chromium/chrome/browser/customtabs/CustomTabsConnectionTest.java b/chrome/android/javatests/src/org/chromium/chrome/browser/customtabs/CustomTabsConnectionTest.java index 1f91dce..e1db3fd 100644 --- a/chrome/android/javatests/src/org/chromium/chrome/browser/customtabs/CustomTabsConnectionTest.java +++ b/chrome/android/javatests/src/org/chromium/chrome/browser/customtabs/CustomTabsConnectionTest.java
@@ -257,7 +257,7 @@ } /** - * Tests that if the renderer backing a hidden tab is killed, the speculation is + * Tests that if the renderer backing a hidden tab is killed, the speculation is not * canceled. */ @Test @@ -277,15 +277,9 @@ mCustomTabsConnection.getSpeculationParamsForTesting()); Tab speculationTab = mCustomTabsConnection.getSpeculationParamsForTesting().tab; Assert.assertNotNull("Null speculation tab", speculationTab); - speculationTab.addObserver(new EmptyTabObserver() { - @Override - public void onDestroyed(Tab tab) { - tabDestroyedHelper.notifyCalled(); - } - }); WebContentsUtils.simulateRendererKilled(speculationTab.getWebContents()); + Assert.assertNotNull("Null speculation tab", speculationTab); }); - tabDestroyedHelper.waitForCallback("The speculated tab was not destroyed", 0); } @Test
diff --git a/chrome/android/javatests/src/org/chromium/chrome/browser/environment_integrity/EnvironmentIntegrityTest.java b/chrome/android/javatests/src/org/chromium/chrome/browser/environment_integrity/EnvironmentIntegrityTest.java new file mode 100644 index 0000000..d0c6ffe --- /dev/null +++ b/chrome/android/javatests/src/org/chromium/chrome/browser/environment_integrity/EnvironmentIntegrityTest.java
@@ -0,0 +1,97 @@ +// Copyright 2023 The Chromium Authors +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +package org.chromium.chrome.browser.environment_integrity; + +import androidx.test.filters.MediumTest; + +import org.junit.After; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Rule; +import org.junit.Test; +import org.junit.runner.RunWith; + +import org.chromium.base.test.util.Batch; +import org.chromium.base.test.util.CallbackHelper; +import org.chromium.base.test.util.CommandLineFlags; +import org.chromium.chrome.browser.flags.ChromeSwitches; +import org.chromium.chrome.browser.tab.EmptyTabObserver; +import org.chromium.chrome.browser.tab.Tab; +import org.chromium.chrome.test.ChromeJUnit4ClassRunner; +import org.chromium.chrome.test.ChromeTabbedActivityTestRule; +import org.chromium.content_public.browser.test.util.TestThreadUtils; +import org.chromium.content_public.common.ContentSwitches; +import org.chromium.net.test.EmbeddedTestServer; + +/** Test suite for navigator.getEnvironmentIntegrity functionality. */ +@RunWith(ChromeJUnit4ClassRunner.class) +@CommandLineFlags.Add({ChromeSwitches.DISABLE_FIRST_RUN_EXPERIENCE, + ContentSwitches.HOST_RESOLVER_RULES + "=MAP * 127.0.0.1", + "enable-features=WebEnvironmentIntegrity", "ignore-certificate-errors"}) +@Batch(Batch.PER_CLASS) +public class EnvironmentIntegrityTest { + @Rule + public ChromeTabbedActivityTestRule mActivityTestRule = new ChromeTabbedActivityTestRule(); + + private static final String TEST_FILE = "/chrome/test/data/android/environment_integrity.html"; + private EmbeddedTestServer mTestServer; + private String mUrl; + private Tab mTab; + private EnvironmentIntegrityUpdateWaiter mUpdateWaiter; + + /** Waits until the JavaScript code supplies a result. */ + private class EnvironmentIntegrityUpdateWaiter extends EmptyTabObserver { + private CallbackHelper mCallbackHelper; + private String mStatus; + + public EnvironmentIntegrityUpdateWaiter() { + mCallbackHelper = new CallbackHelper(); + } + + @Override + public void onTitleUpdated(Tab tab) { + String title = mActivityTestRule.getActivity().getActivityTab().getTitle(); + // Wait until the title indicates either success or failure. + if (!title.startsWith("Success") && !title.startsWith("Fail")) return; + mStatus = title; + mCallbackHelper.notifyCalled(); + } + + public String waitForUpdate() throws Exception { + mCallbackHelper.waitForCallback(0); + return mStatus; + } + } + + @Before + public void setUp() throws Exception { + mActivityTestRule.startMainActivityOnBlankPage(); + mActivityTestRule.getEmbeddedTestServerRule().setServerUsesHttps(true); + mTestServer = mActivityTestRule.getTestServer(); + mUrl = mTestServer.getURLWithHostName("test.host", TEST_FILE); + mTab = mActivityTestRule.getActivity().getActivityTab(); + mUpdateWaiter = new EnvironmentIntegrityUpdateWaiter(); + TestThreadUtils.runOnUiThreadBlocking(() -> mTab.addObserver(mUpdateWaiter)); + } + + @After + public void tearDown() { + TestThreadUtils.runOnUiThreadBlocking(() -> mTab.removeObserver(mUpdateWaiter)); + } + + /** + * Verify that navigator.getEnvironmentIntegrity succeeds. + * + * @throws Exception + */ + @Test + @MediumTest + public void testGetEnvironmentIntegrity() throws Exception { + mActivityTestRule.loadUrl(mUrl); + mActivityTestRule.runJavaScriptCodeInCurrentTab( + "doGetEnvironmentIntegrity('contentBinding')"); + Assert.assertEquals("Success", mUpdateWaiter.waitForUpdate()); + } +}
diff --git a/chrome/android/junit/src/org/chromium/chrome/browser/bookmarks/BookmarkManagerMediatorTest.java b/chrome/android/junit/src/org/chromium/chrome/browser/bookmarks/BookmarkManagerMediatorTest.java index 349a40b..760ecba 100644 --- a/chrome/android/junit/src/org/chromium/chrome/browser/bookmarks/BookmarkManagerMediatorTest.java +++ b/chrome/android/junit/src/org/chromium/chrome/browser/bookmarks/BookmarkManagerMediatorTest.java
@@ -23,10 +23,8 @@ import static org.chromium.ui.test.util.MockitoHelper.doRunnable; import android.app.Activity; -import android.content.Context; import android.graphics.Bitmap; import android.graphics.Color; -import android.view.accessibility.AccessibilityManager; import androidx.annotation.StringRes; import androidx.recyclerview.widget.RecyclerView; @@ -145,8 +143,6 @@ @Mock private BookmarkUndoController mBookmarkUndoController; @Mock - private AccessibilityManager mAccessibilityManager; - @Mock private Runnable mHideKeyboardRunnable; @Mock private UrlFormatter.Natives mUrlFormatterJniMock; @@ -249,9 +245,6 @@ doReturn(mSelectableListLayoutHandleBackPressChangedSupplier) .when(mSelectableListLayout) .getHandleBackPressChangedSupplier(); - doReturn(mAccessibilityManager) - .when(mActivity) - .getSystemService(Context.ACCESSIBILITY_SERVICE); // Setup BookmarkUIObserver. doRunnable(() -> mMediator.removeUiObserver(mBookmarkUiObserver)) @@ -417,7 +410,6 @@ mMediator.onDestroy(); verify(mBookmarkUiObserver).onDestroy(); verify(mBookmarkUndoController).destroy(); - verify(mAccessibilityManager).removeAccessibilityStateChangeListener(any()); } @Test
diff --git a/chrome/android/junit/src/org/chromium/chrome/browser/contextmenu/ContextMenuHeaderMediatorTest.java b/chrome/android/junit/src/org/chromium/chrome/browser/contextmenu/ContextMenuHeaderMediatorTest.java index 96f5d52..54d2606 100644 --- a/chrome/android/junit/src/org/chromium/chrome/browser/contextmenu/ContextMenuHeaderMediatorTest.java +++ b/chrome/android/junit/src/org/chromium/chrome/browser/contextmenu/ContextMenuHeaderMediatorTest.java
@@ -92,7 +92,7 @@ .retrieveImageForContextMenu( anyInt(), anyInt(), mRetrieveImageCallbackCaptor.capture()); verify(mMockLargeIconBridgeJni, times(0)) - .getLargeIconForURL(anyLong(), any(), any(), anyInt(), any()); + .getLargeIconForURL(anyLong(), any(), any(), anyInt(), anyInt(), any()); Assert.assertNotNull( "Retrieve image callback is null.", mRetrieveImageCallbackCaptor.getValue()); @@ -119,7 +119,7 @@ verify(mNativeDelegate, times(0)).retrieveImageForContextMenu(anyInt(), anyInt(), any()); verify(mMockLargeIconBridgeJni, times(0)) - .getLargeIconForURL(anyLong(), any(), any(), anyInt(), any()); + .getLargeIconForURL(anyLong(), any(), any(), anyInt(), anyInt(), any()); Assert.assertNotNull("Header image should be set for videos directly.", model.get(ContextMenuHeaderProperties.IMAGE)); @@ -142,8 +142,8 @@ verify(mNativeDelegate, times(0)).retrieveImageForContextMenu(anyInt(), anyInt(), any()); verify(mMockLargeIconBridgeJni) - .getLargeIconForURL( - anyLong(), any(), any(), anyInt(), mLargeIconCallbackCaptor.capture()); + .getLargeIconForURL(anyLong(), any(), any(), anyInt(), anyInt(), + mLargeIconCallbackCaptor.capture()); Assert.assertNotNull("LargeIconCallback is null.", mLargeIconCallbackCaptor.getValue()); Assert.assertNull("Image should not be set for links before LarIconCallback triggers.",
diff --git a/chrome/app/chrome_command_ids.h b/chrome/app/chrome_command_ids.h index 02d3f635..b9367bf 100644 --- a/chrome/app/chrome_command_ids.h +++ b/chrome/app/chrome_command_ids.h
@@ -127,7 +127,7 @@ #define IDC_FOLLOW 35033 #define IDC_UNFOLLOW 35034 #define IDC_SAVE_IBAN_FOR_PAGE 35035 -#define IDC_AUTOFILL_MENU 35040 +#define IDC_PASSWORDS_AND_AUTOFILL_MENU 35040 #define IDC_SHOW_PASSWORD_MANAGER 35041 #define IDC_SHOW_PAYMENT_METHODS 35042 #define IDC_SHOW_ADDRESSES 35043
diff --git a/chrome/app/chrome_main_mac.h b/chrome/app/chrome_main_mac.h index ded1b9a..1cd3290 100644 --- a/chrome/app/chrome_main_mac.h +++ b/chrome/app/chrome_main_mac.h
@@ -13,10 +13,10 @@ // |user_data_dir| parameter. If no policy is set the parameter is not changed. void CheckUserDataDirPolicy(base::FilePath* user_data_dir); -// Sets the app bundle (base::mac::FrameworkBundle()) to the framework's bundle, -// and sets the base bundle ID (base::mac::BaseBundleID()) to the proper value -// based on the running application. The base bundle ID is the outer browser -// application's bundle ID even when running in a non-browser (helper) +// Sets the app bundle (base::apple::FrameworkBundle()) to the framework's +// bundle, and sets the base bundle ID (base::mac::BaseBundleID()) to the proper +// value based on the running application. The base bundle ID is the outer +// browser application's bundle ID even when running in a non-browser (helper) // process. void SetUpBundleOverrides();
diff --git a/chrome/app/chrome_main_mac.mm b/chrome/app/chrome_main_mac.mm index 2fa38e2..4e8089de 100644 --- a/chrome/app/chrome_main_mac.mm +++ b/chrome/app/chrome_main_mac.mm
@@ -8,9 +8,9 @@ #include <string> +#import "base/apple/bundle_locations.h" #include "base/command_line.h" #include "base/files/file_path.h" -#import "base/mac/bundle_locations.h" #import "base/mac/foundation_util.h" #include "base/path_service.h" #include "base/strings/string_util.h" @@ -22,7 +22,8 @@ void SetUpBundleOverrides() { @autoreleasepool { - base::mac::SetOverrideFrameworkBundlePath(chrome::GetFrameworkBundlePath()); + base::apple::SetOverrideFrameworkBundlePath( + chrome::GetFrameworkBundlePath()); NSBundle* base_bundle = chrome::OuterAppBundle(); base::mac::SetBaseBundleID([[base_bundle bundleIdentifier] UTF8String]);
diff --git a/chrome/app/generated_resources.grd b/chrome/app/generated_resources.grd index e78cb52..c820c79 100644 --- a/chrome/app/generated_resources.grd +++ b/chrome/app/generated_resources.grd
@@ -1141,7 +1141,7 @@ <!-- Page menu. Android has separate strings for its menu --> <if expr="not is_android"> <if expr="not use_titlecase"> - <message name="IDS_ADDRESSES_AND_MORE_SUBMENU_OPTION" desc="The text label of the addresses and more item for the autofill submenu"> + <message name="IDS_ADDRESSES_AND_MORE_SUBMENU_OPTION" desc="The text label of the addresses and more item for the passwords and autofill submenu"> &Addresses and more </message> <message name="IDS_PASSWORDS_AND_AUTOFILL_MENU" desc="The text label of the passwords and autofill menu item"> @@ -1186,10 +1186,10 @@ <message name="IDS_FIND_AND_EDIT_MENU" desc="The text label of the Find and edit sub menu item"> &Find and edit </message> - <message name="IDS_PASSWORD_MANAGER_SUBMENU_OPTION" desc="The text label of the password manager for the autofill submenu"> + <message name="IDS_PASSWORD_MANAGER_SUBMENU_OPTION" desc="The text label of the password manager for the passwords and autofill submenu"> &Google Password Manager </message> - <message name="IDS_PAYMENT_METHOD_SUBMENU_OPTION" desc="The text label of the payment method for the autofill submenu"> + <message name="IDS_PAYMENT_METHOD_SUBMENU_OPTION" desc="The text label of the payment method for the passwords and autofill submenu"> &Payment methods </message> <message name="IDS_SAVE_PAGE" desc="The text label of the Save Page As menu item"> @@ -1242,7 +1242,7 @@ </message> </if> <if expr="use_titlecase"> - <message name="IDS_ADDRESSES_AND_MORE_SUBMENU_OPTION" desc="In Title Case: The text label of the addresses and more item for the autofill submenu"> + <message name="IDS_ADDRESSES_AND_MORE_SUBMENU_OPTION" desc="In Title Case: The text label of the addresses and more item for the passwords and autofill submenu"> &Addresses and More </message> <message name="IDS_PASSWORDS_AND_AUTOFILL_MENU" desc="In Title Case: The text label of the passwords and autofill menu item"> @@ -1287,10 +1287,10 @@ <message name="IDS_FIND_AND_EDIT_MENU" desc="In Title Case: The text label of the Find and edit sub menu item"> &Find and Edit </message> - <message name="IDS_PASSWORD_MANAGER_SUBMENU_OPTION" desc="In Title Case: The text label of the password manager for the autofill submenu"> + <message name="IDS_PASSWORD_MANAGER_SUBMENU_OPTION" desc="In Title Case: The text label of the password manager for the passwords and autofill submenu"> &Google Password Manager </message> - <message name="IDS_PAYMENT_METHOD_SUBMENU_OPTION" desc="In Title Case: The text label of the payment method for the autofill submenu"> + <message name="IDS_PAYMENT_METHOD_SUBMENU_OPTION" desc="In Title Case: The text label of the payment method for the passwords and autofill submenu"> &Payment Methods </message> <message name="IDS_SAVE_PAGE" desc="In Title Case: The text label of the Save Page As menu item"> @@ -14806,12 +14806,12 @@ </message> <if expr="use_titlecase"> <message name="IDS_HIGH_EFFICIENCY_DIALOG_BUTTON_ADD_TO_EXCLUSION_LIST" desc="In Title Case: Label for a button on the page action chip that adds the current active site to the exclusion list when clicked"> - Never Deactivate this Site + Keep Site Active </message> </if> <if expr="not use_titlecase"> <message name="IDS_HIGH_EFFICIENCY_DIALOG_BUTTON_ADD_TO_EXCLUSION_LIST" desc="Label for a button on a dialog that adds the current active site to the exclusion list when clicked"> - Never deactivate this site + Keep site active </message> </if> <if expr="use_titlecase">
diff --git a/chrome/app/generated_resources_grd/IDS_HIGH_EFFICIENCY_DIALOG_BUTTON_ADD_TO_EXCLUSION_LIST.png.sha1 b/chrome/app/generated_resources_grd/IDS_HIGH_EFFICIENCY_DIALOG_BUTTON_ADD_TO_EXCLUSION_LIST.png.sha1 index 27008b04..aca573c 100644 --- a/chrome/app/generated_resources_grd/IDS_HIGH_EFFICIENCY_DIALOG_BUTTON_ADD_TO_EXCLUSION_LIST.png.sha1 +++ b/chrome/app/generated_resources_grd/IDS_HIGH_EFFICIENCY_DIALOG_BUTTON_ADD_TO_EXCLUSION_LIST.png.sha1
@@ -1 +1 @@ -537c9060613314fa9f7b62aba1205baface18507 \ No newline at end of file +448be3c703bd7f7d2ab9597111d653cc3b913e18 \ No newline at end of file
diff --git a/chrome/app_shim/app_shim_controller.mm b/chrome/app_shim/app_shim_controller.mm index 18108af..371952e 100644 --- a/chrome/app_shim/app_shim_controller.mm +++ b/chrome/app_shim/app_shim_controller.mm
@@ -9,12 +9,12 @@ #include <utility> +#include "base/apple/bundle_locations.h" #include "base/base_switches.h" #include "base/command_line.h" #include "base/files/file_util.h" #include "base/functional/bind.h" #include "base/hash/md5.h" -#include "base/mac/bundle_locations.h" #include "base/mac/foundation_util.h" #include "base/mac/launch_application.h" #include "base/mac/mac_util.h" @@ -215,7 +215,7 @@ } // Otherwise, launch Chrome. - base::FilePath chrome_bundle_path = base::mac::OuterBundlePath(); + base::FilePath chrome_bundle_path = base::apple::OuterBundlePath(); LOG(INFO) << "Launching " << chrome_bundle_path.value(); base::CommandLine browser_command_line(base::CommandLine::NO_PROGRAM); browser_command_line.AppendSwitchPath(switches::kUserDataDir, @@ -280,7 +280,7 @@ // Check the process' bundle id. As above, the specified pid could have been // reused by some other process. - NSString* expected_bundle_id = [base::mac::OuterBundle() bundleIdentifier]; + NSString* expected_bundle_id = [base::apple::OuterBundle() bundleIdentifier]; NSString* lock_bundle_id = [process_from_lock bundleIdentifier]; if (![expected_bundle_id isEqualToString:lock_bundle_id]) { LOG(WARNING) << "Singleton lock pid " << pid
diff --git a/chrome/app_shim/chrome_main_app_mode_mac.mm b/chrome/app_shim/chrome_main_app_mode_mac.mm index 11aea43..e0b53f7 100644 --- a/chrome/app_shim/chrome_main_app_mode_mac.mm +++ b/chrome/app_shim/chrome_main_app_mode_mac.mm
@@ -11,6 +11,7 @@ #include <vector> #include "base/allocator/early_zone_registration_mac.h" +#include "base/apple/bundle_locations.h" #include "base/at_exit.h" #include "base/base_switches.h" #include "base/check.h" @@ -19,7 +20,6 @@ #include "base/files/file_path.h" #include "base/files/file_util.h" #include "base/functional/bind.h" -#include "base/mac/bundle_locations.h" #include "base/mac/mac_logging.h" #include "base/message_loop/message_pump_type.h" #include "base/run_loop.h" @@ -80,9 +80,9 @@ chrome::RegisterPathProvider(); // Set bundle paths. This loads the bundles. - base::mac::SetOverrideOuterBundlePath( + base::apple::SetOverrideOuterBundlePath( base::FilePath(info->chrome_outer_bundle_path)); - base::mac::SetOverrideFrameworkBundlePath( + base::apple::SetOverrideFrameworkBundlePath( base::FilePath(info->chrome_framework_path)); // Note that `info->user_data_dir` for shims contains the app data path, @@ -96,12 +96,12 @@ // Calculate the preferred locale used by Chrome. We can't use // l10n_util::OverrideLocaleWithCocoaLocale() because it calls - // [base::mac::OuterBundle() preferredLocalizations] which gets + // [base::apple::OuterBundle() preferredLocalizations] which gets // localizations from the bundle of the running app (i.e. it is equivalent // to [[NSBundle mainBundle] preferredLocalizations]) instead of the target // bundle. NSArray* preferred_languages = [NSLocale preferredLanguages]; - NSArray* supported_languages = [base::mac::OuterBundle() localizations]; + NSArray* supported_languages = [base::apple::OuterBundle() localizations]; std::string preferred_localization; for (NSString* language in preferred_languages) { // We must convert the "-" separator to "_" to be compatible with
diff --git a/chrome/browser/BUILD.gn b/chrome/browser/BUILD.gn index e9be0c5..877e075 100644 --- a/chrome/browser/BUILD.gn +++ b/chrome/browser/BUILD.gn
@@ -4593,6 +4593,11 @@ } if (!is_fuchsia) { + sources += [ + "enterprise/connectors/analysis/print_content_analysis_utils.cc", + "enterprise/connectors/analysis/print_content_analysis_utils.h", + ] + deps += [ "//third_party/crashpad/crashpad/client:common" ] }
diff --git a/chrome/browser/about_flags.cc b/chrome/browser/about_flags.cc index 7da7faf1..23f5cd85 100644 --- a/chrome/browser/about_flags.cc +++ b/chrome/browser/about_flags.cc
@@ -9677,6 +9677,13 @@ kDiscardedTabTreatmentVariations, "DiscardedTabTreatment")}, + {"memory-saver-discard-exceptions-improvements", + flag_descriptions::kHighEfficiencyDiscardExceptionsImprovementsName, + flag_descriptions::kHighEfficiencyDiscardExceptionsImprovementsDescription, + kOsDesktop, + FEATURE_VALUE_TYPE( + performance_manager::features::kDiscardExceptionsImprovements)}, + {"memory-saver-savings-reporting-improvements", flag_descriptions::kHighEfficiencySavingsReportingImprovementsName, flag_descriptions::kHighEfficiencySavingsReportingImprovementsDescription, @@ -9938,11 +9945,6 @@ FEATURE_VALUE_TYPE( autofill::features::kAutofillOfferToSaveCardWithSameLastFour)}, - {"use-mojo-video-decoder-for-pepper", - flag_descriptions::kUseMojoVideoDecoderForPepperName, - flag_descriptions::kUseMojoVideoDecoderForPepperDescription, kOsDesktop, - FEATURE_VALUE_TYPE(media::kUseMojoVideoDecoderForPepper)}, - #if BUILDFLAG(IS_CHROMEOS_ASH) {"app-deduplication-service-fondue", flag_descriptions::kAppDeduplicationServiceFondueName,
diff --git a/chrome/browser/apps/app_service/metrics/app_platform_metrics_service_unittest.cc b/chrome/browser/apps/app_service/metrics/app_platform_metrics_service_unittest.cc index 66dbc88..9459c1aa 100644 --- a/chrome/browser/apps/app_service/metrics/app_platform_metrics_service_unittest.cc +++ b/chrome/browser/apps/app_service/metrics/app_platform_metrics_service_unittest.cc
@@ -1283,7 +1283,7 @@ // Set sync is not allowed. sync_service()->SetDisableReasons( - syncer::SyncService::DISABLE_REASON_ENTERPRISE_POLICY); + {syncer::SyncService::DISABLE_REASON_ENTERPRISE_POLICY}); // Fast forward by 2 hours and verify no usage data is reported to UKM. task_environment_.FastForwardBy(base::Hours(2)); @@ -2152,7 +2152,7 @@ // Disable sync state. sync_service()->SetDisableReasons( - syncer::SyncService::DISABLE_REASON_ENTERPRISE_POLICY); + {syncer::SyncService::DISABLE_REASON_ENTERPRISE_POLICY}); // Fast forward by two hours and verify usage info is cleared from the pref // store. @@ -2222,7 +2222,7 @@ TEST_P(AppPlatformMetricsServiceTest, ShouldNotPersistUsageDataIfSyncDisabled) { // Disable sync state. sync_service()->SetDisableReasons( - syncer::SyncService::DISABLE_REASON_ENTERPRISE_POLICY); + {syncer::SyncService::DISABLE_REASON_ENTERPRISE_POLICY}); // Create a new window for the app. auto window = std::make_unique<aura::Window>(nullptr); @@ -2786,7 +2786,7 @@ TEST_P(AppPlatformMetricsObserverTest, ShouldNotifyObserverOnAppInstalled) { // Observers should be notified even when app sync is disabled. sync_service()->SetDisableReasons( - syncer::SyncService::DISABLE_REASON_ENTERPRISE_POLICY); + {syncer::SyncService::DISABLE_REASON_ENTERPRISE_POLICY}); const std::string app_id(borealis::FakeAppId("borealis-fake")); EXPECT_CALL( @@ -2802,7 +2802,7 @@ TEST_P(AppPlatformMetricsObserverTest, ShouldNotifyObserverOnAppLaunch) { // Observers should be notified even when app sync is disabled. sync_service()->SetDisableReasons( - syncer::SyncService::DISABLE_REASON_ENTERPRISE_POLICY); + {syncer::SyncService::DISABLE_REASON_ENTERPRISE_POLICY}); // Launch a pre-installed app and verify the observer is notified. const std::string& app_id = "a"; @@ -2821,7 +2821,7 @@ TEST_P(AppPlatformMetricsObserverTest, ShouldNotifyObserverOnAppUninstall) { // Observers should be notified even when app sync is disabled. sync_service()->SetDisableReasons( - syncer::SyncService::DISABLE_REASON_ENTERPRISE_POLICY); + {syncer::SyncService::DISABLE_REASON_ENTERPRISE_POLICY}); // Uninstall a pre-installed app and verify the observer is notified. const std::string& app_id = "a"; @@ -2839,7 +2839,7 @@ TEST_P(AppPlatformMetricsObserverTest, ShouldNotifyObserverOnAppUsage) { // Observers should be notified even when app sync is disabled. sync_service()->SetDisableReasons( - syncer::SyncService::DISABLE_REASON_ENTERPRISE_POLICY); + {syncer::SyncService::DISABLE_REASON_ENTERPRISE_POLICY}); // Create a new window for the app. auto window = std::make_unique<aura::Window>(nullptr);
diff --git a/chrome/browser/apps/app_shim/app_shim_manager_mac.cc b/chrome/browser/apps/app_shim/app_shim_manager_mac.cc index 13573079..ad1c9512 100644 --- a/chrome/browser/apps/app_shim/app_shim_manager_mac.cc +++ b/chrome/browser/apps/app_shim/app_shim_manager_mac.cc
@@ -11,6 +11,7 @@ #include <utility> #include "apps/app_lifetime_monitor_factory.h" +#include "base/apple/bundle_locations.h" #include "base/barrier_closure.h" #include "base/debug/dump_without_crashing.h" #include "base/feature_list.h" @@ -20,7 +21,6 @@ #include "base/functional/callback_helpers.h" #include "base/hash/sha1.h" #include "base/logging.h" -#include "base/mac/bundle_locations.h" #include "base/mac/foundation_util.h" #include "base/mac/mac_logging.h" #include "base/memory/raw_ptr.h" @@ -110,7 +110,7 @@ // validating. We are only interested in discovering if the framework bundle // is code-signed, and if so what the designated requirement is. base::ScopedCFTypeRef<CFURLRef> framework_url = - base::mac::FilePathToCFURL(base::mac::FrameworkBundlePath()); + base::mac::FilePathToCFURL(base::apple::FrameworkBundlePath()); base::ScopedCFTypeRef<SecStaticCodeRef> framework_code; OSStatus status = SecStaticCodeCreateWithPath( framework_url, kSecCSDefaultFlags, framework_code.InitializeInto());
diff --git a/chrome/browser/ash/app_list/search/app_discovery_metrics_manager_unittest.cc b/chrome/browser/ash/app_list/search/app_discovery_metrics_manager_unittest.cc index 69446fd..58cbfe78 100644 --- a/chrome/browser/ash/app_list/search/app_discovery_metrics_manager_unittest.cc +++ b/chrome/browser/ash/app_list/search/app_discovery_metrics_manager_unittest.cc
@@ -172,7 +172,7 @@ // Disable app-sync. sync_service()->SetDisableReasons( - syncer::SyncService::DISABLE_REASON_ENTERPRISE_POLICY); + {syncer::SyncService::DISABLE_REASON_ENTERPRISE_POLICY}); TestSearchResult search_result(app_id, app_name, search_result_type);
diff --git a/chrome/browser/ash/app_list/search/omnibox/omnibox_lacros_provider.cc b/chrome/browser/ash/app_list/search/omnibox/omnibox_lacros_provider.cc index bb570b8..b34044b 100644 --- a/chrome/browser/ash/app_list/search/omnibox/omnibox_lacros_provider.cc +++ b/chrome/browser/ash/app_list/search/omnibox/omnibox_lacros_provider.cc
@@ -65,7 +65,8 @@ AutocompleteInput input; SearchSuggestionParser::SuggestResult suggest_result( - query, AutocompleteMatchType::URL_WHAT_YOU_TYPED, /*subtypes=*/{}, + query, AutocompleteMatchType::URL_WHAT_YOU_TYPED, + /*suggest_type=*/omnibox::TYPE_NATIVE_CHROME, /*subtypes=*/{}, /*from_keyword=*/false, /*relevance=*/kMaxOmniboxScore, /*relevance_from_server=*/false, /*input_text=*/query);
diff --git a/chrome/browser/ash/file_manager/copy_or_move_io_task_impl.cc b/chrome/browser/ash/file_manager/copy_or_move_io_task_impl.cc index fbc1a3c..55cd1c7 100644 --- a/chrome/browser/ash/file_manager/copy_or_move_io_task_impl.cc +++ b/chrome/browser/ash/file_manager/copy_or_move_io_task_impl.cc
@@ -660,11 +660,10 @@ // File browsers generally default to preserving mtimes on copy/move so we // should do the same. - storage::FileSystemOperation::CopyOrMoveOptionSet options = - storage::FileSystemOperation::CopyOrMoveOptionSet( - storage::FileSystemOperation::CopyOrMoveOption::kPreserveLastModified, - storage::FileSystemOperation::CopyOrMoveOption:: - kRemovePartiallyCopiedFilesOnError); + storage::FileSystemOperation::CopyOrMoveOptionSet options = { + storage::FileSystemOperation::CopyOrMoveOption::kPreserveLastModified, + storage::FileSystemOperation::CopyOrMoveOption:: + kRemovePartiallyCopiedFilesOnError}; // To ensure progress updates, force cross-filesystem I/O operations when the // source and the destination are on different volumes, or between My files
diff --git a/chrome/browser/ash/file_manager/restore_io_task.cc b/chrome/browser/ash/file_manager/restore_io_task.cc index 381b450..e79d40e9 100644 --- a/chrome/browser/ash/file_manager/restore_io_task.cc +++ b/chrome/browser/ash/file_manager/restore_io_task.cc
@@ -192,8 +192,8 @@ // File browsers generally default to preserving mtimes on copy/move so we // should do the same. - storage::FileSystemOperation::CopyOrMoveOptionSet options( - storage::FileSystemOperation::CopyOrMoveOption::kPreserveLastModified); + storage::FileSystemOperation::CopyOrMoveOptionSet options = { + storage::FileSystemOperation::CopyOrMoveOption::kPreserveLastModified}; auto complete_callback = base::BindPostTaskToCurrentDefault(base::BindOnce( &RestoreIOTask::OnRestoreItem, weak_ptr_factory_.GetWeakPtr(), idx));
diff --git a/chrome/browser/ash/file_manager/trash_io_task.cc b/chrome/browser/ash/file_manager/trash_io_task.cc index 3c0806a..e73619b 100644 --- a/chrome/browser/ash/file_manager/trash_io_task.cc +++ b/chrome/browser/ash/file_manager/trash_io_task.cc
@@ -532,8 +532,8 @@ // File browsers generally default to preserving mtimes on copy/move so we // should do the same. - storage::FileSystemOperation::CopyOrMoveOptionSet options( - storage::FileSystemOperation::CopyOrMoveOption::kPreserveLastModified); + storage::FileSystemOperation::CopyOrMoveOptionSet options = { + storage::FileSystemOperation::CopyOrMoveOption::kPreserveLastModified}; auto complete_callback = base::BindPostTaskToCurrentDefault(base::BindOnce( &TrashIOTask::OnMoveComplete, weak_ptr_factory_.GetWeakPtr(), source_idx,
diff --git a/chrome/browser/ash/fusebox/fusebox_server.cc b/chrome/browser/ash/fusebox/fusebox_server.cc index 7d46cd36..09d258f 100644 --- a/chrome/browser/ash/fusebox/fusebox_server.cc +++ b/chrome/browser/ash/fusebox/fusebox_server.cc
@@ -1172,11 +1172,10 @@ base::BindOnce(&RunRenameCallbackBaseFileError, std::move(callback), src_parsed->fs_context)); - constexpr storage::FileSystemOperation::CopyOrMoveOptionSet options = - storage::FileSystemOperation::CopyOrMoveOptionSet( - storage::FileSystemOperation::CopyOrMoveOption::kPreserveLastModified, - storage::FileSystemOperation::CopyOrMoveOption:: - kRemovePartiallyCopiedFilesOnError); + constexpr storage::FileSystemOperation::CopyOrMoveOptionSet options = { + storage::FileSystemOperation::CopyOrMoveOption::kPreserveLastModified, + storage::FileSystemOperation::CopyOrMoveOption:: + kRemovePartiallyCopiedFilesOnError}; content::GetIOThreadTaskRunner({})->PostTask( FROM_HERE,
diff --git a/chrome/browser/ash/input_method/native_input_method_engine_unittest.cc b/chrome/browser/ash/input_method/native_input_method_engine_unittest.cc index 9a92e995..4359d2f 100644 --- a/chrome/browser/ash/input_method/native_input_method_engine_unittest.cc +++ b/chrome/browser/ash/input_method/native_input_method_engine_unittest.cc
@@ -1215,8 +1215,7 @@ IMEBridge::Get()->SetInputContextHandler(&ime); ukm::TestAutoSetUkmRecorder test_recorder; - test_recorder.UpdateRecording( - ukm::UkmConsentState(ukm::UkmConsentType::MSBB)); + test_recorder.UpdateRecording({ukm::UkmConsentType::MSBB}); ASSERT_EQ(0u, test_recorder.entries_count()); auto metric = ime::mojom::NonCompliantApiMetric::New(); @@ -1261,8 +1260,7 @@ IMEBridge::Get()->SetInputContextHandler(&ime); ukm::TestAutoSetUkmRecorder test_recorder; - test_recorder.UpdateRecording( - ukm::UkmConsentState(ukm::UkmConsentType::MSBB)); + test_recorder.UpdateRecording({ukm::UkmConsentType::MSBB}); ASSERT_EQ(0u, test_recorder.entries_count()); // Should not record when random text is entered.
diff --git a/chrome/browser/ash/login/oobe_quick_start/connectivity/connection.cc b/chrome/browser/ash/login/oobe_quick_start/connectivity/connection.cc index ec6abb4..ebbd45f 100644 --- a/chrome/browser/ash/login/oobe_quick_start/connectivity/connection.cc +++ b/chrome/browser/ash/login/oobe_quick_start/connectivity/connection.cc
@@ -241,13 +241,37 @@ void Connection::WaitForUserVerification( AwaitUserVerificationCallback callback) { - // TODO(b/280604365): Only wait for user verification result if a user - // verification requested message was sent - OnUserVerificationRequested(std::move(callback)); + auto on_decoding_completed = + base::BindOnce(&Connection::OnUserVerificationRequested, + weak_ptr_factory_.GetWeakPtr(), std::move(callback)); + + ConnectionResponseCallback on_message_received = + base::BindOnce(&Connection::DecodeData<mojom::UserVerificationRequested>, + weak_ptr_factory_.GetWeakPtr(), + &mojom::QuickStartDecoder::DecodeUserVerificationRequested, + std::move(on_decoding_completed)); + + nearby_connection_->Read(std::move(on_message_received)); } void Connection::OnUserVerificationRequested( - AwaitUserVerificationCallback callback) { + AwaitUserVerificationCallback callback, + absl::optional<mojom::UserVerificationRequested> + user_verification_request) { + if (!user_verification_request.has_value()) { + QS_LOG(ERROR) << "No user verification request received from phone."; + std::move(callback).Run(absl::nullopt); + return; + } + + if (!user_verification_request->is_awaiting_user_verification) { + QS_LOG(ERROR) << "User verification request received from phone, but " + "is_awaiting_user_verification is false."; + + std::move(callback).Run(absl::nullopt); + return; + } + ConnectionResponseCallback on_response_received = base::BindOnce(&Connection::DecodeData<mojom::UserVerificationResponse>, weak_ptr_factory_.GetWeakPtr(),
diff --git a/chrome/browser/ash/login/oobe_quick_start/connectivity/connection.h b/chrome/browser/ash/login/oobe_quick_start/connectivity/connection.h index 4c5a8db..c461eb8 100644 --- a/chrome/browser/ash/login/oobe_quick_start/connectivity/connection.h +++ b/chrome/browser/ash/login/oobe_quick_start/connectivity/connection.h
@@ -129,8 +129,10 @@ const std::string& challenge_b64url, RequestAccountTransferAssertionCallback callback) override; void WaitForUserVerification(AwaitUserVerificationCallback callback) override; - - void OnUserVerificationRequested(AwaitUserVerificationCallback callback); + void OnUserVerificationRequested( + AwaitUserVerificationCallback callback, + absl::optional<mojom::UserVerificationRequested> + user_verification_request); void OnNotifySourceOfUpdateResponse( NotifySourceOfUpdateCallback callback,
diff --git a/chrome/browser/ash/login/oobe_quick_start/connectivity/connection_unittest.cc b/chrome/browser/ash/login/oobe_quick_start/connectivity/connection_unittest.cc index 607514f..b4ff8d25 100644 --- a/chrome/browser/ash/login/oobe_quick_start/connectivity/connection_unittest.cc +++ b/chrome/browser/ash/login/oobe_quick_start/connectivity/connection_unittest.cc
@@ -453,6 +453,7 @@ } TEST_F(ConnectionTest, TestUserVerificationRequested_ReturnsResult) { + fake_quick_start_decoder_->SetUserVerificationRequested(true); fake_quick_start_decoder_->SetUserVerificationResponse( mojom::UserVerificationResult::kUserVerified, true); @@ -460,24 +461,62 @@ base::test::TestFuture<absl::optional<mojom::UserVerificationResponse>> future; - fake_nearby_connection_->AppendReadableData(kTestBytes); authenticated_connection_->WaitForUserVerification(future.GetCallback()); + fake_nearby_connection_->AppendReadableData(kTestBytes); + fake_nearby_connection_->AppendReadableData(kTestBytes); ASSERT_TRUE(future.Get().has_value()); EXPECT_EQ(mojom::UserVerificationResult::kUserVerified, future.Get()->result); EXPECT_TRUE(future.Get()->is_first_user_verification); } -TEST_F(ConnectionTest, TestUserVerificationRequested_ReturnsEmptyIfError) { +TEST_F(ConnectionTest, + TestUserVerificationRequested_ReturnsEmptyIfRequestIsEmpty) { fake_quick_start_decoder_->SetDecoderError( mojom::QuickStartDecoderError::kMessageDoesNotMatchSchema); + fake_quick_start_decoder_->SetUserVerificationResponse( + mojom::UserVerificationResult::kUserVerified, true); MarkConnectionAuthenticated(); base::test::TestFuture<absl::optional<mojom::UserVerificationResponse>> future; - fake_nearby_connection_->AppendReadableData(kTestBytes); authenticated_connection_->WaitForUserVerification(future.GetCallback()); + fake_nearby_connection_->AppendReadableData(kTestBytes); + + EXPECT_FALSE(future.Get().has_value()); +} + +TEST_F( + ConnectionTest, + TestUserVerificationRequested_ReturnsEmptyIfAwaitingUserVerificationIsFalse) { + fake_quick_start_decoder_->SetUserVerificationRequested(false); + fake_quick_start_decoder_->SetUserVerificationResponse( + mojom::UserVerificationResult::kUserVerified, true); + + MarkConnectionAuthenticated(); + + base::test::TestFuture<absl::optional<mojom::UserVerificationResponse>> + future; + authenticated_connection_->WaitForUserVerification(future.GetCallback()); + fake_nearby_connection_->AppendReadableData(kTestBytes); + + EXPECT_FALSE(future.Get().has_value()); +} + +TEST_F(ConnectionTest, + TestUserVerificationRequested_ReturnsEmptyIfResponseReturnsError) { + fake_quick_start_decoder_->SetUserVerificationRequested(true); + + MarkConnectionAuthenticated(); + + base::test::TestFuture<absl::optional<mojom::UserVerificationResponse>> + future; + authenticated_connection_->WaitForUserVerification(future.GetCallback()); + fake_nearby_connection_->AppendReadableData(kTestBytes); + fake_quick_start_decoder_->SetDecoderError( + mojom::QuickStartDecoderError::kMessageDoesNotMatchSchema); + fake_nearby_connection_->AppendReadableData(kTestBytes); EXPECT_FALSE(future.Get().has_value()); }
diff --git a/chrome/browser/ash/policy/reporting/metrics_reporting/apps/app_usage_collector_unittest.cc b/chrome/browser/ash/policy/reporting/metrics_reporting/apps/app_usage_collector_unittest.cc index c90b2d4d..6102652 100644 --- a/chrome/browser/ash/policy/reporting/metrics_reporting/apps/app_usage_collector_unittest.cc +++ b/chrome/browser/ash/policy/reporting/metrics_reporting/apps/app_usage_collector_unittest.cc
@@ -57,7 +57,7 @@ // Disable sync so we disable UKM reporting and eliminate noise for testing // purposes. sync_service()->SetDisableReasons( - syncer::SyncService::DISABLE_REASON_ENTERPRISE_POLICY); + {syncer::SyncService::DISABLE_REASON_ENTERPRISE_POLICY}); // Pre-install app so it can be used by tests to simulate usage. InstallOneApp(kTestAppId, ::apps::AppType::kArc, /*publisher_id=*/"",
diff --git a/chrome/browser/ash/policy/reporting/metrics_reporting/apps/app_usage_telemetry_sampler_browsertest.cc b/chrome/browser/ash/policy/reporting/metrics_reporting/apps/app_usage_telemetry_sampler_browsertest.cc index 2f833c5a8..1dda521 100644 --- a/chrome/browser/ash/policy/reporting/metrics_reporting/apps/app_usage_telemetry_sampler_browsertest.cc +++ b/chrome/browser/ash/policy/reporting/metrics_reporting/apps/app_usage_telemetry_sampler_browsertest.cc
@@ -360,7 +360,7 @@ ReportUsageDataWhenSyncDisabled) { ASSERT_TRUE(base::FeatureList::IsEnabled(kEnableAppMetricsReporting)); sync_service()->SetDisableReasons( - ::syncer::SyncService::DISABLE_REASON_ENTERPRISE_POLICY); + {::syncer::SyncService::DISABLE_REASON_ENTERPRISE_POLICY}); // Install web app and simulate its usage. const auto& app_id = InstallStandaloneWebApp(GURL(kWebAppUrl));
diff --git a/chrome/browser/ash/sync/sync_appsync_optin_client_unittest.cc b/chrome/browser/ash/sync/sync_appsync_optin_client_unittest.cc index 17ed2ea..2eeed91 100644 --- a/chrome/browser/ash/sync/sync_appsync_optin_client_unittest.cc +++ b/chrome/browser/ash/sync/sync_appsync_optin_client_unittest.cc
@@ -72,8 +72,7 @@ void SetAppsyncOptin(bool opted_in) { if (opted_in) { GetUserSettings()->SetSelectedOsTypes( - false, syncer::UserSelectableOsTypeSet( - syncer::UserSelectableOsType::kOsApps)); + false, {syncer::UserSelectableOsType::kOsApps}); } else { GetUserSettings()->SetSelectedOsTypes(false, syncer::UserSelectableOsTypeSet());
diff --git a/chrome/browser/ash/sync/sync_user_settings_client_ash_unittest.cc b/chrome/browser/ash/sync/sync_user_settings_client_ash_unittest.cc index 88093b4..94d94ace 100644 --- a/chrome/browser/ash/sync/sync_user_settings_client_ash_unittest.cc +++ b/chrome/browser/ash/sync/sync_user_settings_client_ash_unittest.cc
@@ -105,7 +105,7 @@ TEST_F(SyncUserSettingsClientAshTest, ShouldExposeAppsSyncEnabled) { ON_CALL(*sync_user_settings(), GetSelectedOsTypes()) .WillByDefault(Return(syncer::UserSelectableOsTypeSet( - syncer::UserSelectableOsType::kOsApps))); + {syncer::UserSelectableOsType::kOsApps}))); SetupClient(); bool is_apps_sync_enabled = false; @@ -126,7 +126,7 @@ TEST_F(SyncUserSettingsClientAshTest, ShouldSupportMultipleReceivers) { ON_CALL(*sync_user_settings(), GetSelectedOsTypes()) .WillByDefault(Return(syncer::UserSelectableOsTypeSet( - syncer::UserSelectableOsType::kOsApps))); + {syncer::UserSelectableOsType::kOsApps}))); SetupClient(); mojo::Remote<crosapi::mojom::SyncUserSettingsClient> other_remote; @@ -159,7 +159,7 @@ // Mimic apps sync being enabled. ON_CALL(*sync_user_settings(), GetSelectedOsTypes()) .WillByDefault(Return(syncer::UserSelectableOsTypeSet( - syncer::UserSelectableOsType::kOsApps))); + {syncer::UserSelectableOsType::kOsApps}))); client()->OnStateChanged(sync_service()); client()->FlushMojoForTesting(); ASSERT_THAT(observer.GetLastAppsSyncEnabled(), Ne(absl::nullopt)); @@ -188,7 +188,7 @@ // Mimic apps sync being enabled. ON_CALL(*sync_user_settings(), GetSelectedOsTypes()) .WillByDefault(Return(syncer::UserSelectableOsTypeSet( - syncer::UserSelectableOsType::kOsApps))); + {syncer::UserSelectableOsType::kOsApps}))); client()->OnStateChanged(sync_service()); client()->FlushMojoForTesting();
diff --git a/chrome/browser/autocomplete/search_provider_unittest.cc b/chrome/browser/autocomplete/search_provider_unittest.cc index 7406cc148..b1e9713a 100644 --- a/chrome/browser/autocomplete/search_provider_unittest.cc +++ b/chrome/browser/autocomplete/search_provider_unittest.cc
@@ -2845,8 +2845,10 @@ QueryForInput(ASCIIToUTF16(cases[i].input), false, false); SearchSuggestionParser::NavigationResult result( ChromeAutocompleteSchemeClassifier(profile_.get()), GURL(cases[i].url), - AutocompleteMatchType::NAVSUGGEST, {}, std::u16string(), std::string(), - false, 0, false, ASCIIToUTF16(cases[i].input)); + AutocompleteMatchType::NAVSUGGEST, + /*suggest_type=*/omnibox::TYPE_NATIVE_CHROME, /*subtypes=*/{}, + std::u16string(), std::string(), false, 0, false, + ASCIIToUTF16(cases[i].input)); result.set_received_after_last_keystroke(false); AutocompleteMatch match(provider_->NavigationToMatch(result)); EXPECT_EQ(ASCIIToUTF16(cases[i].inline_autocompletion), @@ -2859,8 +2861,10 @@ QueryForInput(ASCIIToUTF16(cases[i].input), true, false); SearchSuggestionParser::NavigationResult result_prevent_inline( ChromeAutocompleteSchemeClassifier(profile_.get()), GURL(cases[i].url), - AutocompleteMatchType::NAVSUGGEST, {}, std::u16string(), std::string(), - false, 0, false, ASCIIToUTF16(cases[i].input)); + AutocompleteMatchType::NAVSUGGEST, + /*suggest_type=*/omnibox::TYPE_NATIVE_CHROME, /*subtypes=*/{}, + std::u16string(), std::string(), false, 0, false, + ASCIIToUTF16(cases[i].input)); result_prevent_inline.set_received_after_last_keystroke(false); AutocompleteMatch match_prevent_inline( provider_->NavigationToMatch(result_prevent_inline)); @@ -2879,8 +2883,9 @@ const std::u16string url(u"http://a.com"); SearchSuggestionParser::NavigationResult result( ChromeAutocompleteSchemeClassifier(profile_.get()), GURL(url), - AutocompleteMatchType::NAVSUGGEST, {}, std::u16string(), std::string(), - false, 0, false, input); + AutocompleteMatchType::NAVSUGGEST, + /*suggest_type=*/omnibox::TYPE_NATIVE_CHROME, /*subtypes=*/{}, + std::u16string(), std::string(), false, 0, false, input); result.set_received_after_last_keystroke(false); // Check the offset and strings when inline autocompletion is allowed. @@ -2905,7 +2910,8 @@ QueryForInput(u"h", false, false); SearchSuggestionParser::NavigationResult result( ChromeAutocompleteSchemeClassifier(profile_.get()), - GURL("http://www.http.com/http"), AutocompleteMatchType::NAVSUGGEST, {}, + GURL("http://www.http.com/http"), AutocompleteMatchType::NAVSUGGEST, + /*suggest_type=*/omnibox::TYPE_NATIVE_CHROME, /*subtypes=*/{}, std::u16string(), std::string(), false, 0, false, u"h"); result.set_received_after_last_keystroke(false); AutocompleteMatch match(provider_->NavigationToMatch(result)); @@ -2931,7 +2937,8 @@ QueryForInput(u"moon", false, false); SearchSuggestionParser::NavigationResult result( ChromeAutocompleteSchemeClassifier(profile_.get()), - GURL("http://moon.com/moon"), AutocompleteMatchType::NAVSUGGEST, {}, + GURL("http://moon.com/moon"), AutocompleteMatchType::NAVSUGGEST, + /*suggest_type=*/omnibox::TYPE_NATIVE_CHROME, /*subtypes=*/{}, std::u16string(), std::string(), false, 0, false, u"moon"); result.set_received_after_last_keystroke(false); AutocompleteMatch match(provider_->NavigationToMatch(result)); @@ -2951,7 +2958,8 @@ QueryForInput(u"acebook", false, false); SearchSuggestionParser::NavigationResult result( ChromeAutocompleteSchemeClassifier(profile_.get()), - GURL("http://www.facebook.com"), AutocompleteMatchType::NAVSUGGEST, {}, + GURL("http://www.facebook.com"), AutocompleteMatchType::NAVSUGGEST, + /*suggest_type=*/omnibox::TYPE_NATIVE_CHROME, /*subtypes=*/{}, std::u16string(), std::string(), false, 0, false, u"acebook"); result.set_received_after_last_keystroke(false); AutocompleteMatch match(provider_->NavigationToMatch(result)); @@ -2969,8 +2977,9 @@ SearchSuggestionParser::NavigationResult result( ChromeAutocompleteSchemeClassifier(profile_.get()), GURL("http://www.yellow-animals.com/duck"), - AutocompleteMatchType::NAVSUGGEST, {}, std::u16string(), std::string(), - false, 0, false, u"duck"); + AutocompleteMatchType::NAVSUGGEST, + /*suggest_type=*/omnibox::TYPE_NATIVE_CHROME, /*subtypes=*/{}, + std::u16string(), std::string(), false, 0, false, u"duck"); result.set_received_after_last_keystroke(false); AutocompleteMatch match(provider_->NavigationToMatch(result)); EXPECT_EQ(u"yellow-animals.com/duck", match.contents); @@ -2990,8 +2999,9 @@ const std::u16string url(u"http://www.facebook.com"); SearchSuggestionParser::NavigationResult result( ChromeAutocompleteSchemeClassifier(profile_.get()), GURL(url), - AutocompleteMatchType::NAVSUGGEST, {}, std::u16string(), std::string(), - false, 0, false, input); + AutocompleteMatchType::NAVSUGGEST, + /*suggest_type=*/omnibox::TYPE_NATIVE_CHROME, /*subtypes=*/{}, + std::u16string(), std::string(), false, 0, false, input); QueryForInput(input, false, false); AutocompleteMatch match_inline(provider_->NavigationToMatch(result)); @@ -3005,8 +3015,9 @@ const std::u16string url(u"http://www.facebook.com"); SearchSuggestionParser::NavigationResult result( ChromeAutocompleteSchemeClassifier(profile_.get()), GURL(url), - AutocompleteMatchType::NAVSUGGEST, {}, std::u16string(), std::string(), - false, 0, false, input); + AutocompleteMatchType::NAVSUGGEST, + /*suggest_type=*/omnibox::TYPE_NATIVE_CHROME, /*subtypes=*/{}, + std::u16string(), std::string(), false, 0, false, input); QueryForInput(input, false, false); AutocompleteMatch match_inline(provider_->NavigationToMatch(result)); @@ -3020,8 +3031,9 @@ const std::u16string url(u"https://www.facebook.com"); SearchSuggestionParser::NavigationResult result( ChromeAutocompleteSchemeClassifier(profile_.get()), GURL(url), - AutocompleteMatchType::NAVSUGGEST, {}, std::u16string(), std::string(), - false, 0, false, input); + AutocompleteMatchType::NAVSUGGEST, + /*suggest_type=*/omnibox::TYPE_NATIVE_CHROME, /*subtypes=*/{}, + std::u16string(), std::string(), false, 0, false, input); QueryForInput(input, false, false); AutocompleteMatch match_inline(provider_->NavigationToMatch(result)); @@ -3034,8 +3046,9 @@ const std::u16string url(u"https://www.facebook.com"); SearchSuggestionParser::NavigationResult result( ChromeAutocompleteSchemeClassifier(profile_.get()), GURL(url), - AutocompleteMatchType::NAVSUGGEST, {}, std::u16string(), std::string(), - false, 0, false, input); + AutocompleteMatchType::NAVSUGGEST, + /*suggest_type=*/omnibox::TYPE_NATIVE_CHROME, /*subtypes=*/{}, + std::u16string(), std::string(), false, 0, false, input); QueryForInput(input, false, false); AutocompleteMatch match_inline(provider_->NavigationToMatch(result)); @@ -3911,7 +3924,8 @@ std::u16string query = u"weather los angeles"; SearchSuggestionParser::SuggestResult suggest_result( query, AutocompleteMatchType::SEARCH_HISTORY, - /*subtypes=*/{}, /*from_keyword_provider=*/false, + /*suggest_type=*/omnibox::TYPE_NATIVE_CHROME, /*subtypes=*/{}, + /*from_keyword_provider=*/false, /*relevance=*/1200, /*relevance_from_server=*/false, /*input_text=*/query); QueryForInput(u"weather l", false, false);
diff --git a/chrome/browser/autofill/android/save_update_address_profile_prompt_controller_unittest.cc b/chrome/browser/autofill/android/save_update_address_profile_prompt_controller_unittest.cc index 555a811..30956c0 100644 --- a/chrome/browser/autofill/android/save_update_address_profile_prompt_controller_unittest.cc +++ b/chrome/browser/autofill/android/save_update_address_profile_prompt_controller_unittest.cc
@@ -270,8 +270,7 @@ ReturnsCorrectStringsToDisplayWhenMigrateLocalAddress) { sync_service_->GetUserSettings()->SetSelectedTypes( /*sync_everything=*/false, - /*types=*/syncer::UserSelectableTypeSet( - syncer::UserSelectableType::kPasswords)); + /*types=*/{syncer::UserSelectableType::kPasswords}); SigninUser(); SetUpController(/*is_update=*/false, /*is_migration_to_account=*/true); @@ -302,8 +301,7 @@ ReturnsCorrectStringsToDisplayWhenMigrateSyncAddress) { sync_service_->GetUserSettings()->SetSelectedTypes( /*sync_everything=*/false, - /*types=*/syncer::UserSelectableTypeSet( - syncer::UserSelectableType::kAutofill)); + /*types=*/{syncer::UserSelectableType::kAutofill}); SigninUser(); SetUpController(/*is_update=*/false, /*is_migration_to_account=*/true);
diff --git a/chrome/browser/browsing_data/browsing_data_model_browsertest.cc b/chrome/browser/browsing_data/browsing_data_model_browsertest.cc index 63f90f2..b21004b 100644 --- a/chrome/browser/browsing_data/browsing_data_model_browsertest.cc +++ b/chrome/browser/browsing_data/browsing_data_model_browsertest.cc
@@ -312,8 +312,9 @@ browsing_data_model.get(), {{kTestHost, blink::StorageKey::CreateFirstParty(testOrigin), - {BrowsingDataModel::StorageType::kSharedStorage, - test_entry_storage_size.Get(), /*cookie_count=*/0}}}); + {{BrowsingDataModel::StorageType::kSharedStorage}, + test_entry_storage_size.Get(), + /*cookie_count=*/0}}}); // Remove origin. { @@ -355,11 +356,13 @@ // Validate that the allowed browsing data model is populated with // SharedStorage entry for `kTestHost`. url::Origin testOrigin = https_test_server()->GetOrigin(kTestHost); - ValidateBrowsingDataEntries(content_settings->allowed_browsing_data_model(), - {{kTestHost, - blink::StorageKey::CreateFirstParty(testOrigin), - {BrowsingDataModel::StorageType::kSharedStorage, - /*storage_size=*/0, /*cookie_count=*/0}}}); + ValidateBrowsingDataEntries( + content_settings->allowed_browsing_data_model(), + {{kTestHost, + blink::StorageKey::CreateFirstParty(testOrigin), + {{BrowsingDataModel::StorageType::kSharedStorage}, + /*storage_size=*/0, + /*cookie_count=*/0}}}); } IN_PROC_BROWSER_TEST_P(BrowsingDataModelBrowserTest, TrustTokenIssuance) { @@ -403,7 +406,7 @@ browsing_data_model.get(), {{kTestHost, https_test_server()->GetOrigin(kTestHost), - {BrowsingDataModel::StorageType::kTrustTokens, 100, 0}}}); + {{BrowsingDataModel::StorageType::kTrustTokens}, 100, 0}}}); // Remove data for the host, and confirm the model updates appropriately. { @@ -443,11 +446,13 @@ url::Origin testOrigin = https_test_server()->GetOrigin(kTestHost); content::InterestGroupManager::InterestGroupDataKey data_key{testOrigin, testOrigin}; - ValidateBrowsingDataEntries(browsing_data_model.get(), - {{kTestHost, - data_key, - {BrowsingDataModel::StorageType::kInterestGroup, - /*storage_size=*/1024, /*cookie_count=*/0}}}); + ValidateBrowsingDataEntries( + browsing_data_model.get(), + {{kTestHost, + data_key, + {{BrowsingDataModel::StorageType::kInterestGroup}, + /*storage_size=*/1024, + /*cookie_count=*/0}}}); // Remove Interest Group. { base::RunLoop run_loop; @@ -483,11 +488,13 @@ url::Origin testOrigin = https_test_server()->GetOrigin(kTestHost); content::InterestGroupManager::InterestGroupDataKey data_key{testOrigin, testOrigin}; - ValidateBrowsingDataEntries(allowed_browsing_data_model, - {{kTestHost, - data_key, - {BrowsingDataModel::StorageType::kInterestGroup, - /*storage_size=*/0, /*cookie_count=*/0}}}); + ValidateBrowsingDataEntries( + allowed_browsing_data_model, + {{kTestHost, + data_key, + {{BrowsingDataModel::StorageType::kInterestGroup}, + /*storage_size=*/0, + /*cookie_count=*/0}}}); } IN_PROC_BROWSER_TEST_P(BrowsingDataModelBrowserTest, @@ -517,11 +524,13 @@ url::Origin testOrigin = https_test_server()->GetOrigin(kTestHost); content::InterestGroupManager::InterestGroupDataKey data_key{testOrigin, testOrigin}; - ValidateBrowsingDataEntries(allowed_browsing_data_model, - {{kTestHost, - data_key, - {BrowsingDataModel::StorageType::kInterestGroup, - /*storage_size=*/0, /*cookie_count=*/0}}}); + ValidateBrowsingDataEntries( + allowed_browsing_data_model, + {{kTestHost, + data_key, + {{BrowsingDataModel::StorageType::kInterestGroup}, + /*storage_size=*/0, + /*cookie_count=*/0}}}); } IN_PROC_BROWSER_TEST_P(BrowsingDataModelBrowserTest, @@ -562,8 +571,9 @@ allowed_browsing_data_model, {{kTestHost, data_key, - {BrowsingDataModel::StorageType::kAttributionReporting, - /*storage_size=*/0, /*cookie_count=*/0}}}); + {{BrowsingDataModel::StorageType::kAttributionReporting}, + /*storage_size=*/0, + /*cookie_count=*/0}}}); } } @@ -593,9 +603,10 @@ allowed_browsing_data_model, {{kTestHost, testOrigin, - {static_cast<BrowsingDataModel::StorageType>( - ChromeBrowsingDataModelDelegate::StorageType::kTopics), - /*storage_size=*/0, /*cookie_count=*/0}}}); + {{static_cast<BrowsingDataModel::StorageType>( + ChromeBrowsingDataModelDelegate::StorageType::kTopics)}, + /*storage_size=*/0, + /*cookie_count=*/0}}}); ASSERT_EQ(allowed_browsing_data_model->size(), 1u); // Clear Topic via BDM @@ -641,14 +652,16 @@ browsing_data_model.get(), {{iwa_url_info1.origin(), iwa_url_info1.origin(), - {static_cast<BrowsingDataModel::StorageType>( - ChromeBrowsingDataModelDelegate::StorageType::kIsolatedWebApp), - /*storage_size=*/105, /*cookie_count=*/0}}, + {{static_cast<BrowsingDataModel::StorageType>( + ChromeBrowsingDataModelDelegate::StorageType::kIsolatedWebApp)}, + /*storage_size=*/105, + /*cookie_count=*/0}}, {iwa_url_info2.origin(), iwa_url_info2.origin(), - {static_cast<BrowsingDataModel::StorageType>( - ChromeBrowsingDataModelDelegate::StorageType::kIsolatedWebApp), - /*storage_size=*/505, /*cookie_count=*/0}}}); + {{static_cast<BrowsingDataModel::StorageType>( + ChromeBrowsingDataModelDelegate::StorageType::kIsolatedWebApp)}, + /*storage_size=*/505, + /*cookie_count=*/0}}}); } IN_PROC_BROWSER_TEST_P(BrowsingDataModelBrowserTest, @@ -681,8 +694,9 @@ browsing_data_model.get(), {{kTestHost, data_key, - {BrowsingDataModel::StorageType::kUnpartitionedQuotaStorage, - /*storage_size=*/0, /*cookie_count=*/0}}}); + {{BrowsingDataModel::StorageType::kUnpartitionedQuotaStorage}, + /*storage_size=*/0, + /*cookie_count=*/0}}}); ASSERT_EQ(browsing_data_model->size(), 1u); // Remove quota entry. @@ -729,8 +743,9 @@ browsing_data_model.get(), {{kTestHost, data_key, - {BrowsingDataModel::StorageType::kLocalStorage, - /*storage_size=*/0, /*cookie_count=*/0}}}); + {{BrowsingDataModel::StorageType::kLocalStorage}, + /*storage_size=*/0, + /*cookie_count=*/0}}}); ASSERT_EQ(browsing_data_model->size(), 1u); // Remove local storage entry.
diff --git a/chrome/browser/browsing_data/counters/sync_aware_counter_browsertest.cc b/chrome/browser/browsing_data/counters/sync_aware_counter_browsertest.cc index 6aae1e7..ef15bf0 100644 --- a/chrome/browser/browsing_data/counters/sync_aware_counter_browsertest.cc +++ b/chrome/browser/browsing_data/counters/sync_aware_counter_browsertest.cc
@@ -212,8 +212,8 @@ EXPECT_FALSE(IsSyncEnabled()); // If password sync is not affected, the counter is not restarted. - syncer::UserSelectableTypeSet only_history( - syncer::UserSelectableType::kHistory); + syncer::UserSelectableTypeSet only_history = { + syncer::UserSelectableType::kHistory}; sync_service->GetUserSettings()->SetSelectedTypes(/*sync_everything=*/false, only_history); sync_blocker = sync_service->GetSetupInProgressHandle(); @@ -286,8 +286,8 @@ EXPECT_FALSE(IsSyncEnabled()); // If the history deletion sync is not affected, the counter is not restarted. - syncer::UserSelectableTypeSet only_passwords( - syncer::UserSelectableType::kPasswords); + syncer::UserSelectableTypeSet only_passwords = { + syncer::UserSelectableType::kPasswords}; sync_service->GetUserSettings()->SetSelectedTypes(/*sync_everything=*/false, only_passwords); sync_blocker = sync_service->GetSetupInProgressHandle(); @@ -298,9 +298,9 @@ EXPECT_FALSE(CountingFinishedSinceLastAsked()); // Same in this case. - syncer::UserSelectableTypeSet autofill_and_passwords( + syncer::UserSelectableTypeSet autofill_and_passwords = { syncer::UserSelectableType::kAutofill, - syncer::UserSelectableType::kPasswords); + syncer::UserSelectableType::kPasswords}; sync_blocker = sync_service->GetSetupInProgressHandle(); sync_service->GetUserSettings()->SetSelectedTypes( /*sync_everything=*/false, autofill_and_passwords);
diff --git a/chrome/browser/chrome_browser_main_mac.mm b/chrome/browser/chrome_browser_main_mac.mm index d495e1a..789d147f 100644 --- a/chrome/browser/chrome_browser_main_mac.mm +++ b/chrome/browser/chrome_browser_main_mac.mm
@@ -6,10 +6,10 @@ #import <Cocoa/Cocoa.h> +#include "base/apple/bundle_locations.h" #include "base/command_line.h" #include "base/feature_list.h" #include "base/functional/bind.h" -#include "base/mac/bundle_locations.h" #import "base/mac/foundation_util.h" #include "base/mac/mac_util.h" #include "base/mac/scoped_nsobject.h"
diff --git a/chrome/browser/chrome_content_browser_client.cc b/chrome/browser/chrome_content_browser_client.cc index 7b839a3..9c5f8632 100644 --- a/chrome/browser/chrome_content_browser_client.cc +++ b/chrome/browser/chrome_content_browser_client.cc
@@ -1580,8 +1580,6 @@ registry->RegisterBooleanPref(prefs::kNewBaseUrlInheritanceBehaviorAllowed, true); registry->RegisterBooleanPref( - policy::policy_prefs::kUseMojoVideoDecoderForPepperAllowed, true); - registry->RegisterBooleanPref( policy::policy_prefs::kPPAPISharedImagesSwapChainAllowed, true); registry->RegisterBooleanPref( policy::policy_prefs::kForceEnablePepperVideoDecoderDevAPI, false); @@ -3008,11 +3006,6 @@ PrefService* local_state = g_browser_process->local_state(); DCHECK(local_state); if (!local_state->GetBoolean( - policy::policy_prefs::kUseMojoVideoDecoderForPepperAllowed)) { - command_line->AppendSwitch( - ::switches::kDisableUseMojoVideoDecoderForPepper); - } - if (!local_state->GetBoolean( policy::policy_prefs::kPPAPISharedImagesSwapChainAllowed)) { command_line->AppendSwitch( ::switches::kDisablePPAPISharedImagesSwapChain);
diff --git a/chrome/browser/content_settings/content_settings_origin_identifier_value_map_unittest.cc b/chrome/browser/content_settings/content_settings_origin_identifier_value_map_unittest.cc index 5940a96..4732141 100644 --- a/chrome/browser/content_settings/content_settings_origin_identifier_value_map_unittest.cc +++ b/chrome/browser/content_settings/content_settings_origin_identifier_value_map_unittest.cc
@@ -15,6 +15,7 @@ TEST(OriginIdentifierValueMapTest, SetGetValue) { content_settings::OriginIdentifierValueMap map; + base::AutoLock lock(map.GetLock()); EXPECT_EQ(nullptr, map.GetValue(GURL("http://www.google.com"), GURL("http://www.google.com"), @@ -45,6 +46,7 @@ TEST(OriginIdentifierValueMapTest, SetDeleteValue) { content_settings::OriginIdentifierValueMap map; + base::AutoLock lock(map.GetLock()); EXPECT_EQ(nullptr, map.GetValue(GURL("http://www.google.com"), GURL("http://www.google.com"), @@ -92,6 +94,7 @@ TEST(OriginIdentifierValueMapTest, Clear) { content_settings::OriginIdentifierValueMap map; + base::AutoLock lock(map.GetLock()); EXPECT_TRUE(map.empty()); // Set two values. @@ -118,6 +121,7 @@ TEST(OriginIdentifierValueMapTest, ListEntryPrecedences) { content_settings::OriginIdentifierValueMap map; + base::AutoLock lock(map.GetLock()); map.SetValue(ContentSettingsPattern::FromString("[*.]google.com"), ContentSettingsPattern::FromString("[*.]google.com"), @@ -147,13 +151,15 @@ TEST(OriginIdentifierValueMapTest, IterateEmpty) { content_settings::OriginIdentifierValueMap map; std::unique_ptr<content_settings::RuleIterator> rule_iterator( - map.GetRuleIterator(ContentSettingsType::COOKIES, nullptr)); + map.GetRuleIterator(ContentSettingsType::COOKIES)); EXPECT_FALSE(rule_iterator); } TEST(OriginIdentifierValueMapTest, IterateNonempty) { // Verify the precedence order. content_settings::OriginIdentifierValueMap map; + + map.GetLock().Acquire(); ContentSettingsPattern pattern = ContentSettingsPattern::FromString("[*.]google.com"); ContentSettingsPattern sub_pattern = @@ -167,8 +173,9 @@ ContentSettingsType::COOKIES, base::Value(2), {.last_modified = t2}); + map.GetLock().Release(); std::unique_ptr<content_settings::RuleIterator> rule_iterator( - map.GetRuleIterator(ContentSettingsType::COOKIES, nullptr)); + map.GetRuleIterator(ContentSettingsType::COOKIES)); ASSERT_TRUE(rule_iterator->HasNext()); content_settings::Rule rule = rule_iterator->Next(); EXPECT_EQ(sub_pattern, rule.primary_pattern); @@ -185,6 +192,7 @@ TEST(OriginIdentifierValueMapTest, UpdateLastModified) { // Verify that the last_modified timestamp is updated. content_settings::OriginIdentifierValueMap map; + map.GetLock().Acquire(); ContentSettingsPattern pattern = ContentSettingsPattern::FromString("[*.]google.com"); ContentSettingsPattern sub_pattern = @@ -202,10 +210,11 @@ .expiration = content_settings::GetConstraintExpiration( base::Seconds(100)), .session_model = content_settings::SessionModel::UserSession}); + map.GetLock().Release(); { std::unique_ptr<content_settings::RuleIterator> rule_iterator( - map.GetRuleIterator(ContentSettingsType::COOKIES, nullptr)); + map.GetRuleIterator(ContentSettingsType::COOKIES)); ASSERT_TRUE(rule_iterator->HasNext()); content_settings::Rule rule = rule_iterator->Next(); EXPECT_EQ(sub_pattern, rule.primary_pattern); @@ -225,14 +234,15 @@ content_settings::SessionModel::Durable); ASSERT_FALSE(rule_iterator->HasNext()); } + map.GetLock().Acquire(); base::Time t2 = t1 + base::Seconds(1); map.SetValue(pattern, ContentSettingsPattern::Wildcard(), ContentSettingsType::COOKIES, base::Value(3), {.last_modified = t2}); - + map.GetLock().Release(); { std::unique_ptr<content_settings::RuleIterator> rule_iterator = - map.GetRuleIterator(ContentSettingsType::COOKIES, nullptr); + map.GetRuleIterator(ContentSettingsType::COOKIES); ASSERT_TRUE(rule_iterator->HasNext()); content_settings::Rule rule = rule_iterator->Next(); EXPECT_EQ(sub_pattern, rule.primary_pattern);
diff --git a/chrome/browser/content_settings/one_time_permission_provider.cc b/chrome/browser/content_settings/one_time_permission_provider.cc index ec7dbcf0..ea3ea62 100644 --- a/chrome/browser/content_settings/one_time_permission_provider.cc +++ b/chrome/browser/content_settings/one_time_permission_provider.cc
@@ -34,7 +34,7 @@ if (!permissions::PermissionUtil::CanPermissionBeAllowedOnce(content_type)) { return nullptr; } - return value_map_.GetRuleIterator(content_type, nullptr); + return value_map_.GetRuleIterator(content_type); } bool OneTimePermissionProvider::SetWebsiteSetting( @@ -48,6 +48,7 @@ return false; } + base::AutoLock lock(value_map_.GetLock()); // This block handles transitions from Allow Once to Ask/Block by clearing // the one time grant and letting the pref provider handle the permission as // usual. @@ -104,6 +105,7 @@ if (permissions::PermissionUtil::CanPermissionBeAllowedOnce(content_type)) { return; } + base::AutoLock lock(value_map_.GetLock()); value_map_.DeleteValues(content_type); } @@ -166,7 +168,7 @@ std::set<content_settings::OriginIdentifierValueMap::PatternPair> patterns_to_delete; std::unique_ptr<content_settings::RuleIterator> rule_iterator( - value_map_.GetRuleIterator(content_setting_type, nullptr)); + value_map_.GetRuleIterator(content_setting_type)); while (rule_iterator && rule_iterator->HasNext()) { auto rule = rule_iterator->Next(); @@ -181,6 +183,7 @@ } rule_iterator.reset(); + base::AutoLock lock(value_map_.GetLock()); for (const auto& pattern : patterns_to_delete) { value_map_.DeleteValue(pattern.primary_pattern, pattern.secondary_pattern, content_setting_type);
diff --git a/chrome/browser/devtools/devtools_ui_bindings_unittest.cc b/chrome/browser/devtools/devtools_ui_bindings_unittest.cc index b90846a9..02cb437 100644 --- a/chrome/browser/devtools/devtools_ui_bindings_unittest.cc +++ b/chrome/browser/devtools/devtools_ui_bindings_unittest.cc
@@ -135,7 +135,7 @@ TEST_F(DevToolsUIBindingsSyncInfoTest, SyncDisabled) { sync_service_->SetDisableReasons( - syncer::SyncService::DISABLE_REASON_NOT_SIGNED_IN); + {syncer::SyncService::DISABLE_REASON_NOT_SIGNED_IN}); base::Value::Dict info = DevToolsUIBindings::GetSyncInformationForProfile(&profile_); @@ -146,8 +146,7 @@ TEST_F(DevToolsUIBindingsSyncInfoTest, PreferencesNotSynced) { sync_service_->GetUserSettings()->SetSelectedTypes( /*sync_everything=*/false, - /*types=*/syncer::UserSelectableTypeSet( - syncer::UserSelectableType::kBookmarks)); + /*types=*/{syncer::UserSelectableType::kBookmarks}); base::Value::Dict info = DevToolsUIBindings::GetSyncInformationForProfile(&profile_);
diff --git a/chrome/browser/download/bubble/download_bubble_ui_controller.cc b/chrome/browser/download/bubble/download_bubble_ui_controller.cc index abd3888..56fa678 100644 --- a/chrome/browser/download/bubble/download_bubble_ui_controller.cc +++ b/chrome/browser/download/bubble/download_bubble_ui_controller.cc
@@ -311,3 +311,8 @@ browser_->profile()); tracker->NotifyEvent("download_bubble_interaction"); } + +base::WeakPtr<DownloadBubbleUIController> +DownloadBubbleUIController::GetWeakPtr() { + return weak_factory_.GetWeakPtr(); +}
diff --git a/chrome/browser/download/bubble/download_bubble_ui_controller.h b/chrome/browser/download/bubble/download_bubble_ui_controller.h index eab7a7b..347f0554 100644 --- a/chrome/browser/download/bubble/download_bubble_ui_controller.h +++ b/chrome/browser/download/bubble/download_bubble_ui_controller.h
@@ -103,6 +103,8 @@ DownloadBubbleUpdateService* update_service() { return update_service_; } + base::WeakPtr<DownloadBubbleUIController> GetWeakPtr(); + private: friend class DownloadBubbleUIControllerTest; friend class DownloadBubbleUIControllerIncognitoTest;
diff --git a/chrome/browser/enterprise/connectors/analysis/print_content_analysis_utils.cc b/chrome/browser/enterprise/connectors/analysis/print_content_analysis_utils.cc new file mode 100644 index 0000000..d281bae3 --- /dev/null +++ b/chrome/browser/enterprise/connectors/analysis/print_content_analysis_utils.cc
@@ -0,0 +1,97 @@ +// Copyright 2023 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/enterprise/connectors/analysis/print_content_analysis_utils.h" + +#include <cstring> +#include <utility> + +#include "base/feature_list.h" +#include "base/memory/read_only_shared_memory_region.h" +#include "chrome/browser/enterprise/connectors/analysis/content_analysis_delegate.h" +#include "chrome/browser/profiles/profile.h" +#include "chrome/browser/safe_browsing/cloud_content_scanning/deep_scanning_utils.h" +#include "components/device_event_log/device_event_log.h" +#include "content/public/browser/web_contents.h" +#include "printing/printing_features.h" +#include "third_party/abseil-cpp/absl/types/optional.h" + +namespace { + +void ScanAndPrint( + scoped_refptr<base::RefCountedMemory> data, + content::WebContents* initiator, + enterprise_connectors::ContentAnalysisDelegate::Data scanning_data, + base::OnceCallback<void(bool)> on_verdict) { + // The preview document bytes are copied so that the content analysis code + // can arbitrarily use them without having to handle ownership issues with + // other printing code. + base::MappedReadOnlyRegion region = + base::ReadOnlySharedMemoryRegion::Create(data->size()); + if (!region.IsValid()) { + // Allow printing if the scan can't happen due to memory failure. + PRINTER_LOG(ERROR) << "Printed without scanning due to memory failure"; + std::move(on_verdict).Run(/*allowed=*/true); + return; + } + std::memcpy(region.mapping.memory(), data->front(), data->size()); + scanning_data.page = std::move(region.region); + + auto on_scan_result = base::BindOnce( + [](base::OnceCallback<void(bool should_proceed)> callback, + const enterprise_connectors::ContentAnalysisDelegate::Data& data, + enterprise_connectors::ContentAnalysisDelegate::Result& result) { + std::move(callback).Run(result.page_result); + }, + std::move(on_verdict)); + enterprise_connectors::ContentAnalysisDelegate::CreateForWebContents( + initiator, std::move(scanning_data), std::move(on_scan_result), + safe_browsing::DeepScanAccessPoint::PRINT); +} + +} // namespace + +namespace enterprise_connectors { + +void PrintIfAllowedByPolicy(scoped_refptr<base::RefCountedMemory> data, + content::WebContents* initiator, + base::OnceCallback<void(bool)> on_verdict, + base::OnceClosure hide_preview) { + ContentAnalysisDelegate::Data scanning_data; + + if (ContentAnalysisDelegate::IsEnabled( + Profile::FromBrowserContext(initiator->GetBrowserContext()), + initiator->GetLastCommittedURL(), &scanning_data, + enterprise_connectors::AnalysisConnector::PRINT) && + base::FeatureList::IsEnabled( + printing::features::kEnablePrintScanAfterPreview) && + scanning_data.settings.cloud_or_local_settings.is_local_analysis()) { + // Hide the preview dialog so it doesn't cover the content analysis dialog + // showing the status of the scanning. + // TODO(b/281087582): May need to be handled differently when the scan + // takes place in the cloud instead of locally. + std::move(hide_preview).Run(); + ScanAndPrint(data, initiator, std::move(scanning_data), + std::move(on_verdict)); + return; + } + std::move(on_verdict).Run(/*allowed=*/true); +} + +absl::optional<enterprise_connectors::ContentAnalysisDelegate::Data> +ShouldAnalyzeBeforePrintPreview(content::WebContents* web_contents) { + enterprise_connectors::ContentAnalysisDelegate::Data scanning_data; + if (enterprise_connectors::ContentAnalysisDelegate::IsEnabled( + Profile::FromBrowserContext(web_contents->GetBrowserContext()), + web_contents->GetOutermostWebContents()->GetLastCommittedURL(), + &scanning_data, enterprise_connectors::AnalysisConnector::PRINT) && + !(base::FeatureList::IsEnabled( + printing::features::kEnablePrintScanAfterPreview) && + scanning_data.settings.cloud_or_local_settings.is_local_analysis())) { + return scanning_data; + } + return absl::nullopt; +} + +} // namespace enterprise_connectors
diff --git a/chrome/browser/enterprise/connectors/analysis/print_content_analysis_utils.h b/chrome/browser/enterprise/connectors/analysis/print_content_analysis_utils.h new file mode 100644 index 0000000..a16bd0d --- /dev/null +++ b/chrome/browser/enterprise/connectors/analysis/print_content_analysis_utils.h
@@ -0,0 +1,36 @@ +// Copyright 2023 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_ENTERPRISE_CONNECTORS_ANALYSIS_PRINT_CONTENT_ANALYSIS_UTILS_H_ +#define CHROME_BROWSER_ENTERPRISE_CONNECTORS_ANALYSIS_PRINT_CONTENT_ANALYSIS_UTILS_H_ + +#include "base/functional/callback_forward.h" +#include "base/memory/ref_counted_memory.h" +#include "base/memory/scoped_refptr.h" +#include "chrome/browser/enterprise/connectors/analysis/content_analysis_delegate.h" +#include "third_party/abseil-cpp/absl/types/optional.h" + +namespace content { +class WebContents; +} + +namespace enterprise_connectors { + +// This function takes something to print (`data`) and scans it if the policy is +// enabled on a managed browser. It `hides_preview` for local content scans. +// On receiving the verdict after the scan this function calls +// `on_verdict` with true or false. In the non enterprise case where no scan is +// required, this function directly calls `on_verdict` with true. This function +// can return asynchronously. +void PrintIfAllowedByPolicy(scoped_refptr<base::RefCountedMemory> data, + content::WebContents* initiator, + base::OnceCallback<void(bool)> on_verdict, + base::OnceClosure hide_preview); + +absl::optional<enterprise_connectors::ContentAnalysisDelegate::Data> +ShouldAnalyzeBeforePrintPreview(content::WebContents* web_contents); + +} // namespace enterprise_connectors + +#endif // CHROME_BROWSER_ENTERPRISE_CONNECTORS_ANALYSIS_PRINT_CONTENT_ANALYSIS_HANDLER_H_
diff --git a/chrome/browser/extensions/activity_log/activity_database.cc b/chrome/browser/extensions/activity_log/activity_database.cc index 0a60882..32fb68b 100644 --- a/chrome/browser/extensions/activity_log/activity_database.cc +++ b/chrome/browser/extensions/activity_log/activity_database.cc
@@ -23,7 +23,7 @@ #include "third_party/sqlite/sqlite3.h" #if BUILDFLAG(IS_MAC) -#include "base/mac/backup_util.h" +#include "base/apple/backup_util.h" #endif namespace extensions { @@ -87,7 +87,7 @@ #if BUILDFLAG(IS_MAC) // Exclude the database from backups. - base::mac::SetBackupExclusion(db_name); + base::apple::SetBackupExclusion(db_name); #endif if (!delegate_->InitDatabase(&db_))
diff --git a/chrome/browser/extensions/external_pref_loader_unittest.cc b/chrome/browser/extensions/external_pref_loader_unittest.cc index 715a168..07313f3 100644 --- a/chrome/browser/extensions/external_pref_loader_unittest.cc +++ b/chrome/browser/extensions/external_pref_loader_unittest.cc
@@ -136,7 +136,7 @@ // Initially CanSyncFeatureStart() returns true, returning false will let // |loader| proceed. sync_service()->SetDisableReasons( - syncer::SyncService::DISABLE_REASON_USER_CHOICE); + {syncer::SyncService::DISABLE_REASON_USER_CHOICE}); ASSERT_FALSE(sync_service()->CanSyncFeatureStart()); sync_service()->FireOnStateChanged(); run_loop.Run();
diff --git a/chrome/browser/feed/android/java/src/org/chromium/chrome/browser/feed/FeedFeatures.java b/chrome/browser/feed/android/java/src/org/chromium/chrome/browser/feed/FeedFeatures.java index 7b10e5b2..939120a 100644 --- a/chrome/browser/feed/android/java/src/org/chromium/chrome/browser/feed/FeedFeatures.java +++ b/chrome/browser/feed/android/java/src/org/chromium/chrome/browser/feed/FeedFeatures.java
@@ -55,7 +55,7 @@ && IdentityServicesProvider.get() .getSigninManager(Profile.getLastUsedRegularProfile()) .getIdentityManager() - .hasPrimaryAccount(ConsentLevel.SYNC) + .hasPrimaryAccount(ConsentLevel.SIGNIN) && !Profile.getLastUsedRegularProfile().isChild(); }
diff --git a/chrome/browser/flag-metadata.json b/chrome/browser/flag-metadata.json index c17ce23..a66f492 100644 --- a/chrome/browser/flag-metadata.json +++ b/chrome/browser/flag-metadata.json
@@ -2908,7 +2908,7 @@ { "name": "enable-new-base-url-inheritance-behavior", "owners": [ "wjmaclean", "creis", "alexmos", "domenic" ], - "expiry_milestone": 115 + "expiry_milestone": 120 }, { "name": "enable-new-download-api", @@ -5006,6 +5006,11 @@ "expiry_milestone": -1 }, { + "name": "memory-saver-discard-exceptions-improvements", + "owners": [ "chrome-performance-ui-team@google.com" ], + "expiry_milestone": 117 + }, + { "name": "memory-saver-discarded-tab-treatment", "owners": [ "chrome-performance-ui-team@google.com" ], "expiry_milestone": 117 @@ -7424,11 +7429,6 @@ "expiry_milestone": -1 }, { - "name": "use-mojo-video-decoder-for-pepper", - "owners": [ "pmolinalopez", "andrescj" ], - "expiry_milestone": 128 - }, - { "name": "use-multi-plane-format-for-hardware-video", "owners": [ "hitawala", "vasilyt" ], "expiry_milestone": 124
diff --git a/chrome/browser/flag_descriptions.cc b/chrome/browser/flag_descriptions.cc index 6e3e1ba7..ca6c9d4 100644 --- a/chrome/browser/flag_descriptions.cc +++ b/chrome/browser/flag_descriptions.cc
@@ -307,12 +307,6 @@ "Use a custom URL as part of the \"Messages\" feature under " "\"Connected Devices\" settings."; -const char kUseMojoVideoDecoderForPepperName[] = - "Use the MojoVideoDecoder for hardware video decoding in Pepper"; -const char kUseMojoVideoDecoderForPepperDescription[] = - "Switches Pepper to use the MojoVideoDecoder for hardware accelerated " - "video decoding instead of the legacy video decoder."; - const char kUseDMSAAForTilesName[] = "Use DMSAA for tiles"; const char kUseDMSAAForTilesDescription[] = "Switches skia to use DMSAA instead of MSAA for tile raster"; @@ -4489,7 +4483,7 @@ "background."; extern const char kHighEfficiencyModeTimeBeforeDiscardName[] = - "Configure discard time for Memory Saver"; + "Configure discard timer for Memory Saver"; extern const char kHighEfficiencyModeTimeBeforeDiscardDescription[] = "When set, this controls the time before memory saver discards a tab."; @@ -4506,6 +4500,13 @@ "When enabled, discarded tabs will have a modified favicon to indicate " "that state."; +extern const char kHighEfficiencyDiscardExceptionsImprovementsName[] = + "Enable improvements to creating tab discard exceptions."; +extern const char kHighEfficiencyDiscardExceptionsImprovementsDescription[] = + "When enabled, tab discard exceptions can be created from the Memory Saver " + "page action chip dialog and they can be created from currently open tabs " + "via the settings page."; + extern const char kHighEfficiencySavingsReportingImprovementsName[] = "Enable improvements to how memory savings are reported."; extern const char kHighEfficiencySavingsReportingImprovementsDescription[] =
diff --git a/chrome/browser/flag_descriptions.h b/chrome/browser/flag_descriptions.h index 306a0a7..996ca50 100644 --- a/chrome/browser/flag_descriptions.h +++ b/chrome/browser/flag_descriptions.h
@@ -201,9 +201,6 @@ extern const char kUseCustomMessagesDomainName[]; extern const char kUseCustomMessagesDomainDescription[]; -extern const char kUseMojoVideoDecoderForPepperName[]; -extern const char kUseMojoVideoDecoderForPepperDescription[]; - extern const char kEnableAutoDisableAccessibilityName[]; extern const char kEnableAutoDisableAccessibilityDescription[]; @@ -2574,6 +2571,9 @@ extern const char kHighEfficiencyDiscardedTabTreatmentName[]; extern const char kHighEfficiencyDiscardedTabTreatmentDescription[]; +extern const char kHighEfficiencyDiscardExceptionsImprovementsName[]; +extern const char kHighEfficiencyDiscardExceptionsImprovementsDescription[]; + extern const char kHighEfficiencySavingsReportingImprovementsName[]; extern const char kHighEfficiencySavingsReportingImprovementsDescription[];
diff --git a/chrome/browser/flags/android/chrome_feature_list.cc b/chrome/browser/flags/android/chrome_feature_list.cc index dc288ac..2a1b2800 100644 --- a/chrome/browser/flags/android/chrome_feature_list.cc +++ b/chrome/browser/flags/android/chrome_feature_list.cc
@@ -115,7 +115,6 @@ &features::kPWAsDefaultOfflinePage, &features::kEarlyLibraryLoad, &features::kGenericSensorExtraClasses, - &features::kAsyncSensorCalls, &features::kBackForwardCache, &features::kBackForwardTransitions, &features::kBlockMidiByDefault,
diff --git a/chrome/browser/lacros/lacros_extension_apps_controller.cc b/chrome/browser/lacros/lacros_extension_apps_controller.cc index d0fa77d..3025b2c7 100644 --- a/chrome/browser/lacros/lacros_extension_apps_controller.cc +++ b/chrome/browser/lacros/lacros_extension_apps_controller.cc
@@ -40,6 +40,7 @@ #include "extensions/common/constants.h" #include "extensions/common/extension.h" #include "extensions/common/extension_urls.h" +#include "extensions/common/manifest_handlers/web_file_handlers_info.h" #include "ui/base/window_open_disposition.h" #include "ui/events/event_constants.h" @@ -329,6 +330,18 @@ std::move(callback).Run(std::move(result)); } else if (which_type_.IsExtensions()) { + // Web File Handlers use the `file_handlers` manifest key for registration. + if (extensions::WebFileHandlers::SupportsWebFileHandlers( + extension->manifest_version())) { + // Launch Web File Handlers. + params.container = apps::LaunchContainer::kLaunchContainerTab; + OpenApplication(profile, std::move(params)); + result->instance_id = base::UnguessableToken::Create(); + result->state = crosapi::mojom::LaunchResultState::kSuccess; + std::move(callback).Run(std::move(result)); + return; + } + // This code path is used only by fileBrowserHandler to open Lacros // extension, and is triggered by user using a Lacros extension to handle // file open. Therefore we check |launch_params| first, and if that passes,
diff --git a/chrome/browser/language/android/BUILD.gn b/chrome/browser/language/android/BUILD.gn index d0dd7718..a1be7f4 100644 --- a/chrome/browser/language/android/BUILD.gn +++ b/chrome/browser/language/android/BUILD.gn
@@ -72,6 +72,7 @@ "//third_party/androidx:androidx_fragment_fragment_java", "//third_party/androidx:androidx_preference_preference_java", "//third_party/androidx:androidx_recyclerview_recyclerview_java", + "//ui/accessibility:ax_base_java", "//ui/android:ui_full_java", "//ui/android:ui_no_recycler_view_java", ]
diff --git a/chrome/browser/language/android/java/src/org/chromium/chrome/browser/language/settings/LanguageListBaseAdapter.java b/chrome/browser/language/android/java/src/org/chromium/chrome/browser/language/settings/LanguageListBaseAdapter.java index 1a1c4c1..4d289c5 100644 --- a/chrome/browser/language/android/java/src/org/chromium/chrome/browser/language/settings/LanguageListBaseAdapter.java +++ b/chrome/browser/language/android/java/src/org/chromium/chrome/browser/language/settings/LanguageListBaseAdapter.java
@@ -10,8 +10,6 @@ import android.view.MotionEvent; import android.view.View; import android.view.ViewGroup; -import android.view.accessibility.AccessibilityManager; -import android.view.accessibility.AccessibilityManager.AccessibilityStateChangeListener; import android.widget.ImageView; import android.widget.TextView; @@ -28,6 +26,7 @@ import org.chromium.components.browser_ui.widget.listmenu.ListMenuButton; import org.chromium.components.browser_ui.widget.listmenu.ListMenuButtonDelegate; import org.chromium.components.browser_ui.widget.selectable_list.SelectableListUtils; +import org.chromium.ui.accessibility.AccessibilityState; import java.util.ArrayList; import java.util.Collection; @@ -122,26 +121,16 @@ /** * Keeps track of whether drag is enabled / active for language preference lists. */ - private class LanguageDragStateDelegate implements DragStateDelegate { - private AccessibilityManager mA11yManager; - private AccessibilityStateChangeListener mA11yListener; - private boolean mA11yEnabled; - + private class LanguageDragStateDelegate + implements DragStateDelegate, AccessibilityState.Listener { public LanguageDragStateDelegate() { - mA11yManager = - (AccessibilityManager) mContext.getSystemService(Context.ACCESSIBILITY_SERVICE); - mA11yEnabled = mA11yManager.isEnabled(); - mA11yListener = enabled -> { - mA11yEnabled = enabled; - notifyDataSetChanged(); - }; - mA11yManager.addAccessibilityStateChangeListener(mA11yListener); + AccessibilityState.addListener(this); } // DragStateDelegate implementation @Override public boolean getDragEnabled() { - return !mA11yEnabled; + return !AccessibilityState.isPerformGesturesEnabled(); } @Override @@ -150,11 +139,9 @@ } @Override - public void setA11yStateForTesting(boolean a11yEnabled) { - mA11yManager.removeAccessibilityStateChangeListener(mA11yListener); - mA11yListener = null; - mA11yManager = null; - mA11yEnabled = a11yEnabled; + public void onAccessibilityStateChanged(AccessibilityState.State oldAccessibilityState, + AccessibilityState.State newAccessibilityState) { + notifyDataSetChanged(); } }
diff --git a/chrome/browser/mac/dock.mm b/chrome/browser/mac/dock.mm index 3a1aa55..c35de6b 100644 --- a/chrome/browser/mac/dock.mm +++ b/chrome/browser/mac/dock.mm
@@ -11,8 +11,8 @@ #include <tuple> +#include "base/apple/bundle_locations.h" #include "base/logging.h" -#include "base/mac/bundle_locations.h" #include "base/mac/foundation_util.h" #include "base/mac/launchd.h" #include "base/mac/scoped_cftyperef.h" @@ -190,7 +190,7 @@ return ChromeInDockFailure; } - NSString* launch_path = [base::mac::OuterBundle() bundlePath]; + NSString* launch_path = [base::apple::OuterBundle() bundlePath]; return [PersistentAppPaths(persistent_apps) containsObject:launch_path] ? ChromeInDockTrue
diff --git a/chrome/browser/mac/install_from_dmg.mm b/chrome/browser/mac/install_from_dmg.mm index 3298cafa..f9fcfaed 100644 --- a/chrome/browser/mac/install_from_dmg.mm +++ b/chrome/browser/mac/install_from_dmg.mm
@@ -19,12 +19,12 @@ #include <algorithm> +#include "base/apple/bundle_locations.h" #include "base/auto_reset.h" #include "base/command_line.h" #include "base/files/file_path.h" #include "base/logging.h" #include "base/mac/authorization_util.h" -#include "base/mac/bundle_locations.h" #include "base/mac/foundation_util.h" #include "base/mac/mac_logging.h" #include "base/mac/mac_util.h" @@ -437,7 +437,7 @@ DiskImageStatus IsAppRunningFromReadOnlyDiskImage( std::string* dmg_bsd_device_name) { return IsPathOnReadOnlyDiskImage( - base::mac::OuterBundle().bundlePath.fileSystemRepresentation, + base::apple::OuterBundle().bundlePath.fileSystemRepresentation, dmg_bsd_device_name); } @@ -469,7 +469,7 @@ return false; } - NSString* source_path = base::mac::OuterBundle().bundlePath; + NSString* source_path = base::apple::OuterBundle().bundlePath; NSString* application_name = source_path.lastPathComponent; NSString* target_path = [application_directory stringByAppendingPathComponent:application_name]; @@ -481,8 +481,8 @@ } NSURL* installer_url = - [base::mac::FrameworkBundle() URLForResource:@"install" - withExtension:@"sh"]; + [base::apple::FrameworkBundle() URLForResource:@"install" + withExtension:@"sh"]; if (!installer_url) { VLOG(1) << "Could not locate install.sh"; return false;
diff --git a/chrome/browser/mac/keystone_glue.mm b/chrome/browser/mac/keystone_glue.mm index 7eda97a..8b61bac 100644 --- a/chrome/browser/mac/keystone_glue.mm +++ b/chrome/browser/mac/keystone_glue.mm
@@ -12,12 +12,12 @@ #include <vector> #include "base/apple/bridging.h" +#include "base/apple/bundle_locations.h" #include "base/file_version_info.h" #include "base/functional/bind.h" #include "base/location.h" #include "base/logging.h" #include "base/mac/authorization_util.h" -#include "base/mac/bundle_locations.h" #include "base/mac/foundation_util.h" #include "base/mac/mac_logging.h" #include "base/memory/ref_counted.h" @@ -277,12 +277,12 @@ } - (NSDictionary*)infoDictionary { - // Use base::mac::OuterBundle() to get the Chrome app's own bundle identifier - // and path, not the framework's. For auto-update, the application is - // what's significant here: it's used to locate the outermost part of the + // Use base::apple::OuterBundle() to get the Chrome app's own bundle + // identifier and path, not the framework's. For auto-update, the application + // is what's significant here: it's used to locate the outermost part of the // application for the existence checker and other operations that need to // see the entire application bundle. - return base::mac::OuterBundle().infoDictionary; + return base::apple::OuterBundle().infoDictionary; } - (NSString*)productID { @@ -302,7 +302,7 @@ } - (void)loadParameters { - NSBundle* appBundle = base::mac::OuterBundle(); + NSBundle* appBundle = base::apple::OuterBundle(); NSDictionary* infoDictionary = self.infoDictionary; NSString* productID = @@ -437,8 +437,8 @@ } // Load the KeystoneRegistration framework bundle if present. It lives - // inside the framework, so use base::mac::FrameworkBundle(); - NSString* ksrPath = [base::mac::FrameworkBundle().privateFrameworksPath + // inside the framework, so use base::apple::FrameworkBundle(); + NSString* ksrPath = [base::apple::FrameworkBundle().privateFrameworksPath stringByAppendingPathComponent:@"KeystoneRegistration.framework"]; NSBundle* ksrBundle = [NSBundle bundleWithPath:ksrPath]; [ksrBundle load]; @@ -883,8 +883,8 @@ // authenticating, may actually result in different ownership being applied // to files and directories. NSFileManager* fileManager = NSFileManager.defaultManager; - NSString* executablePath = base::mac::OuterBundle().executablePath; - NSString* frameworkPath = base::mac::FrameworkBundle().bundlePath; + NSString* executablePath = base::apple::OuterBundle().executablePath; + NSString* frameworkPath = base::apple::FrameworkBundle().bundlePath; return ![fileManager isWritableFileAtPath:_appPath] || ![fileManager isWritableFileAtPath:executablePath] || ![fileManager isWritableFileAtPath:frameworkPath]; @@ -961,10 +961,9 @@ // preflight now does, and then the preflight script can be removed instead. // However, preflight operation (and promotion) should only be asynchronous if // the synchronous parameter is NO. - NSString* preflightPath = - [base::mac::FrameworkBundle() - pathForResource:@"keystone_promote_preflight" - ofType:@"sh"]; + NSString* preflightPath = [base::apple::FrameworkBundle() + pathForResource:@"keystone_promote_preflight" + ofType:@"sh"]; const char* preflightPathC = preflightPath.fileSystemRepresentation; // This is typically a once per machine operation, so it is not worth caching @@ -1076,7 +1075,7 @@ // thread to run the tool. DCHECK(NSThread.isMainThread); - NSString* toolPath = [base::mac::FrameworkBundle() + NSString* toolPath = [base::apple::FrameworkBundle() pathForResource:@"keystone_promote_postflight" ofType:@"sh"];
diff --git a/chrome/browser/mac/relauncher.mm b/chrome/browser/mac/relauncher.mm index d3251fd..b96deee 100644 --- a/chrome/browser/mac/relauncher.mm +++ b/chrome/browser/mac/relauncher.mm
@@ -18,11 +18,11 @@ #include <string> #include <vector> +#include "base/apple/bundle_locations.h" #include "base/files/file_path.h" #include "base/files/file_util.h" #include "base/files/scoped_file.h" #include "base/logging.h" -#include "base/mac/bundle_locations.h" #include "base/mac/launch_application.h" #include "base/mac/mac_logging.h" #include "base/mac/scoped_nsobject.h" @@ -116,7 +116,7 @@ // The first item of `args` is the path to the executable, but launch APIs // require the path to the bundle. Rather than try to derive the bundle path // from the executable path, substitute in the bundle path. - relaunch_args.push_back(base::mac::OuterBundlePath().value()); + relaunch_args.push_back(base::apple::OuterBundlePath().value()); for (size_t i = 1; i < args.size(); ++i) { // Strip any PSN arguments, as they apply to a specific process. if (args[i].compare(0, strlen(kPSNArg), kPSNArg) != 0 &&
diff --git a/chrome/browser/metrics/chrome_metrics_service_client_ash_unittest.cc b/chrome/browser/metrics/chrome_metrics_service_client_ash_unittest.cc index 861423087..4ff6c4c 100644 --- a/chrome/browser/metrics/chrome_metrics_service_client_ash_unittest.cc +++ b/chrome/browser/metrics/chrome_metrics_service_client_ash_unittest.cc
@@ -121,7 +121,7 @@ GetUserSettings()->SetSelectedTypes( /*sync_everything=*/false, /*types=*/history_enabled ? syncer::UserSelectableTypeSet( - syncer::UserSelectableType::kHistory) + {syncer::UserSelectableType::kHistory}) : syncer::UserSelectableTypeSet()); // It doesn't matter what exactly we set here, it's only relevant that the
diff --git a/chrome/browser/metrics/ukm_browsertest.cc b/chrome/browser/metrics/ukm_browsertest.cc index 6e69686..4e4a91d 100644 --- a/chrome/browser/metrics/ukm_browsertest.cc +++ b/chrome/browser/metrics/ukm_browsertest.cc
@@ -1551,7 +1551,7 @@ base::FeatureList::IsEnabled(ukm::kAppMetricsOnlyRelyOnAppSync)); observer.ExpectAllowedStateChanged( base::FeatureList::IsEnabled(ukm::kAppMetricsOnlyRelyOnAppSync) - ? ukm::UkmConsentState(ukm::APPS) + ? ukm::UkmConsentState({ukm::APPS}) : ukm::UkmConsentState()); #endif
diff --git a/chrome/browser/navigation_predictor/anchor_element_preloader.cc b/chrome/browser/navigation_predictor/anchor_element_preloader.cc index c1ceeb95..7c54621 100644 --- a/chrome/browser/navigation_predictor/anchor_element_preloader.cc +++ b/chrome/browser/navigation_predictor/anchor_element_preloader.cc
@@ -10,12 +10,14 @@ #include "chrome/browser/prefetch/prefetch_prefs.h" #include "chrome/browser/preloading/chrome_preloading.h" #include "content/public/browser/browser_context.h" +#include "content/public/browser/navigation_handle.h" #include "content/public/browser/preloading.h" #include "content/public/browser/preloading_data.h" #include "content/public/browser/web_contents.h" #include "services/metrics/public/cpp/ukm_builders.h" #include "services/metrics/public/cpp/ukm_recorder.h" #include "third_party/blink/public/common/features.h" +#include "ui/base/page_transition_types.h" #include "url/scheme_host_port.h" namespace { @@ -37,7 +39,21 @@ AnchorElementPreloader::AnchorElementPreloader( content::RenderFrameHost& render_frame_host) - : render_frame_host_(render_frame_host) {} + : render_frame_host_(render_frame_host) { + content::PreloadingData* preloading_data = + content::PreloadingData::GetOrCreateForWebContents( + content::WebContents::FromRenderFrameHost(&*render_frame_host_)); + preloading_data->SetIsNavigationInDomainCallback( + chrome_preloading_predictor::kPointerDownOnAnchor, + base::BindRepeating( + [](content::NavigationHandle* navigation_handle) -> bool { + return ui::PageTransitionCoreTypeIs( + navigation_handle->GetPageTransition(), + ui::PageTransition::PAGE_TRANSITION_LINK) && + ui::PageTransitionIsNewNavigation( + navigation_handle->GetPageTransition()); + })); +} void AnchorElementPreloader::MaybePreconnect(const GURL& target) { content::PreloadingData* preloading_data =
diff --git a/chrome/browser/navigation_predictor/anchor_element_preloader_browsertest.cc b/chrome/browser/navigation_predictor/anchor_element_preloader_browsertest.cc index 19b70ccc3..50272d3e9 100644 --- a/chrome/browser/navigation_predictor/anchor_element_preloader_browsertest.cc +++ b/chrome/browser/navigation_predictor/anchor_element_preloader_browsertest.cc
@@ -48,9 +48,15 @@ return {}; } + virtual base::FieldTrialParams GetNavigationPredictorFieldTrialParams() { + return {}; + } + void SetUp() override { feature_list_.InitWithFeaturesAndParameters( - {{blink::features::kAnchorElementInteraction, + {{blink::features::kNavigationPredictor, + GetNavigationPredictorFieldTrialParams()}, + {blink::features::kAnchorElementInteraction, GetAnchorElementInteractionFieldTrialParams()}, {blink::features::kSpeculationRulesPointerDownHeuristics, {}}}, {blink::features::kSpeculationRulesPointerHoverHeuristics, @@ -484,4 +490,51 @@ << content::test::ActualVsExpectedUkmEntriesToString(ukm_entries, expected_entries); } + +class AnchorElementSetIsNavigationInDomainBrowserTest + : public AnchorElementPreloaderBrowserTest { + public: + base::FieldTrialParams GetNavigationPredictorFieldTrialParams() override { + return {{"random_anchor_sampling_period", "1"}}; + } +}; + +IN_PROC_BROWSER_TEST_F(AnchorElementSetIsNavigationInDomainBrowserTest, + TestPointerDownOnAnchor) { + base::HistogramTester histogram_tester; + GURL url = GetTestURL("/one_anchor.html"); + EXPECT_TRUE(ui_test_utils::NavigateToURL(browser(), url)); + // Add a new link and trigger a mouse down event. + EXPECT_TRUE(content::ExecJs(web_contents(), + R"( + let a = document.createElement("a"); + a.id = "link"; + a.href = "https://www.example.com"; + a.innerHTML = '<div style="width:100vw;height:100vh;">Example<div>'; + document.body.appendChild(a); + )")); + base::RunLoop().RunUntilIdle(); + content::InputEventAckWaiter waiter( + web_contents()->GetPrimaryMainFrame()->GetRenderWidgetHost(), + blink::WebInputEvent::Type::kMouseDown); + SimulateMouseEvent(web_contents(), blink::WebInputEvent::Type::kMouseDown, + blink::WebPointerProperties::Button::kLeft, + gfx::Point(150, 150)); + waiter.Wait(); + // Add another link and click on it. + EXPECT_TRUE(content::ExecJs(web_contents(), + R"( + let google = document.createElement("a"); + google.id = "link"; + google.href = "https://www.google.com"; + google.innerHTML = "google"; + document.body.appendChild(google); + google.click(); + )")); + base::RunLoop().RunUntilIdle(); + histogram_tester.ExpectBucketCount( + "Preloading.Predictor.PointerDownOnAnchor.Recall", + /*content::PredictorConfusionMatrix::kFalseNegative*/ 3, 1); +} + } // namespace
diff --git a/chrome/browser/optimization_guide/optimization_guide_keyed_service.cc b/chrome/browser/optimization_guide/optimization_guide_keyed_service.cc index f6f4a042..f66e3018 100644 --- a/chrome/browser/optimization_guide/optimization_guide_keyed_service.cc +++ b/chrome/browser/optimization_guide/optimization_guide_keyed_service.cc
@@ -159,6 +159,7 @@ base::WeakPtr<optimization_guide::OptimizationGuideStore> hint_store; base::WeakPtr<optimization_guide::OptimizationGuideStore> prediction_model_and_features_store; + base::FilePath model_downloads_dir; if (profile->IsOffTheRecord()) { OptimizationGuideKeyedService* original_ogks = OptimizationGuideKeyedServiceFactory::GetForProfile( @@ -211,12 +212,20 @@ hint_store = hint_store_ ? hint_store_->AsWeakPtr() : nullptr; if (!optimization_guide::features::IsInstallWideModelStoreEnabled()) { + // Do not explicitly hand off the model downloads directory to + // off-the-record profiles. Underneath the hood, this variable is only + // used in non off-the-record profiles to know where to download the model + // files to. Off-the-record profiles read the model locations from the + // original profiles they are associated with. + model_downloads_dir = profile_path.Append( + optimization_guide::kOptimizationGuidePredictionModelDownloads); prediction_model_and_features_store_ = std::make_unique<optimization_guide::OptimizationGuideStore>( proto_db_provider, profile_path.Append( optimization_guide:: kOptimizationGuidePredictionModelMetadataStore), + model_downloads_dir, base::ThreadPool::CreateSequencedTaskRunner( {base::MayBlock(), base::TaskPriority::BEST_EFFORT}), profile->GetPrefs()); @@ -231,17 +240,6 @@ tab_url_provider_.get(), url_loader_factory, MaybeCreatePushNotificationManager(profile), optimization_guide_logger_.get()); - base::FilePath model_downloads_dir; - if (!optimization_guide::features::IsInstallWideModelStoreEnabled() && - !profile->IsOffTheRecord()) { - // Do not explicitly hand off the model downloads directory to - // off-the-record profiles. Underneath the hood, this variable is only used - // in non off-the-record profiles to know where to download the model files - // to. Off-the-record profiles read the model locations from the original - // profiles they are associated with. - model_downloads_dir = profile_path.Append( - optimization_guide::kOptimizationGuidePredictionModelDownloads); - } prediction_manager_ = std::make_unique<optimization_guide::PredictionManager>( prediction_model_and_features_store,
diff --git a/chrome/browser/optimization_guide/prediction/prediction_manager_browsertest.cc b/chrome/browser/optimization_guide/prediction/prediction_manager_browsertest.cc index a8ae6e6..101a1785 100644 --- a/chrome/browser/optimization_guide/prediction/prediction_manager_browsertest.cc +++ b/chrome/browser/optimization_guide/prediction/prediction_manager_browsertest.cc
@@ -228,8 +228,9 @@ PredictionModelsFetcherRemoteResponseType::kSuccessfulWithValidModelFile; }; -class PredictionManagerBrowserTest : public testing::WithParamInterface<bool>, - public PredictionManagerBrowserTestBase { +class PredictionManagerBrowserTest + : public testing::WithParamInterface<std::tuple<bool, bool>>, + public PredictionManagerBrowserTestBase { public: PredictionManagerBrowserTest() = default; ~PredictionManagerBrowserTest() override = default; @@ -238,7 +239,12 @@ PredictionManagerBrowserTest& operator=(const PredictionManagerBrowserTest&) = delete; - bool ShouldEnableInstallWideModelStore() const { return GetParam(); } + bool ShouldEnableInstallWideModelStore() const { + return std::get<0>(GetParam()); + } + bool ShouldEnableModelStoreUseRelativePath() const { + return std::get<1>(GetParam()); + } private: void InitializeFeatureList() override { @@ -257,9 +263,12 @@ } }; -INSTANTIATE_TEST_SUITE_P(All, - PredictionManagerBrowserTest, - /*use_install_wide_model_store=*/testing::Bool()); +INSTANTIATE_TEST_SUITE_P( + All, + PredictionManagerBrowserTest, + testing::Combine( + /*ShouldEnableInstallWideModelStore=*/testing::Bool(), + /*ShouldEnableModelStoreUseRelativePath=*/testing::Bool())); IN_PROC_BROWSER_TEST_P(PredictionManagerBrowserTest, ComponentUpdatesPrefDisabled) { @@ -386,15 +395,22 @@ features::kOptimizationGuideInstallWideModelStore, base::FieldTrialParams()); } + if (ShouldEnableModelStoreUseRelativePath()) { + enabled_features.emplace_back(features::kModelStoreUseRelativePath, + base::FieldTrialParams()); + } scoped_feature_list_.InitWithFeaturesAndParameters(enabled_features, {}); } std::unique_ptr<ModelFileObserver> model_file_observer_; }; -INSTANTIATE_TEST_SUITE_P(All, - PredictionManagerModelDownloadingBrowserTest, - /*ShouldEnableInstallWideModelStore=*/testing::Bool()); +INSTANTIATE_TEST_SUITE_P( + All, + PredictionManagerModelDownloadingBrowserTest, + testing::Combine( + /*ShouldEnableInstallWideModelStore=*/testing::Bool(), + /*ShouldEnableModelStoreUseRelativePath=*/testing::Bool())); // Flaky on various bots. See https://crbug.com/1266318 IN_PROC_BROWSER_TEST_P(PredictionManagerModelDownloadingBrowserTest, @@ -539,12 +555,13 @@ std::unique_ptr<base::RunLoop> run_loop = std::make_unique<base::RunLoop>(); model_file_observer()->set_model_file_received_callback(base::BindOnce( - [](base::RunLoop* run_loop, proto::OptimizationTarget optimization_target, + [](base::RunLoop* run_loop, bool should_enable_install_wide_model_store, + proto::OptimizationTarget optimization_target, const ModelInfo& model_info) { EXPECT_EQ(optimization_target, proto::OPTIMIZATION_TARGET_PAINFUL_PAGE_LOAD); - if (!GetParam()) { + if (!should_enable_install_wide_model_store) { // Regression test for crbug/1327975. // Make sure model file path downloaded into profile dir. base::FilePath profile_dir = @@ -553,7 +570,7 @@ } run_loop->Quit(); }, - run_loop.get())); + run_loop.get(), ShouldEnableInstallWideModelStore())); // Registering should initiate the fetch and receive a response with a model // containing a download URL and then subsequently downloaded.
diff --git a/chrome/browser/password_manager/android/password_sync_controller_delegate_android_unittest.cc b/chrome/browser/password_manager/android/password_sync_controller_delegate_android_unittest.cc index 7f5ba65..55df7f0 100644 --- a/chrome/browser/password_manager/android/password_sync_controller_delegate_android_unittest.cc +++ b/chrome/browser/password_manager/android/password_sync_controller_delegate_android_unittest.cc
@@ -105,7 +105,7 @@ TEST_F(PasswordSyncControllerDelegateAndroidTest, OnSyncStatusDisabledOnStartup) { sync_service()->SetDisableReasons( - syncer::SyncService::DISABLE_REASON_NOT_SIGNED_IN); + {syncer::SyncService::DISABLE_REASON_NOT_SIGNED_IN}); EXPECT_CALL(*bridge(), NotifyCredentialManagerWhenNotSyncing); sync_controller_delegate()->OnSyncServiceInitialized(sync_service()); @@ -119,7 +119,7 @@ TEST_F(PasswordSyncControllerDelegateAndroidTest, OnSyncStatusChangedToEnabledAfterStartup) { sync_service()->SetDisableReasons( - syncer::SyncService::DISABLE_REASON_NOT_SIGNED_IN); + {syncer::SyncService::DISABLE_REASON_NOT_SIGNED_IN}); EXPECT_CALL(*bridge(), NotifyCredentialManagerWhenNotSyncing()); sync_controller_delegate()->OnSyncServiceInitialized(sync_service()); @@ -162,7 +162,7 @@ sync_controller_delegate()->OnSyncServiceInitialized(sync_service()); sync_service()->SetDisableReasons( - syncer::SyncService::DISABLE_REASON_NOT_SIGNED_IN); + {syncer::SyncService::DISABLE_REASON_NOT_SIGNED_IN}); EXPECT_CALL(*bridge(), NotifyCredentialManagerWhenNotSyncing()); sync_controller_delegate()->OnStateChanged(sync_service());
diff --git a/chrome/browser/password_manager/chrome_password_manager_client_unittest.cc b/chrome/browser/password_manager/chrome_password_manager_client_unittest.cc index 23027ac..7b6b01c 100644 --- a/chrome/browser/password_manager/chrome_password_manager_client_unittest.cc +++ b/chrome/browser/password_manager/chrome_password_manager_client_unittest.cc
@@ -407,8 +407,7 @@ TEST_F(ChromePasswordManagerClientTest, GetPasswordSyncState) { sync_service_->GetUserSettings()->SetSelectedTypes( /*sync_everything=*/false, - /*types=*/syncer::UserSelectableTypeSet( - syncer::UserSelectableType::kPasswords)); + /*types=*/{syncer::UserSelectableType::kPasswords}); sync_service_->SetIsUsingExplicitPassphrase(false); ChromePasswordManagerClient* client = GetClient(); @@ -432,8 +431,7 @@ // Report correctly if we aren't syncing passwords. sync_service_->GetUserSettings()->SetSelectedTypes( /*sync_everything=*/false, - /*types=*/syncer::UserSelectableTypeSet( - syncer::UserSelectableType::kBookmarks)); + /*types=*/{syncer::UserSelectableType::kBookmarks}); EXPECT_EQ(password_manager::SyncState::kNotSyncing, client->GetPasswordSyncState());
diff --git a/chrome/browser/password_manager/password_manager_util_mac.mm b/chrome/browser/password_manager/password_manager_util_mac.mm index 90b69a75..8e687ea1 100644 --- a/chrome/browser/password_manager/password_manager_util_mac.mm +++ b/chrome/browser/password_manager/password_manager_util_mac.mm
@@ -8,8 +8,8 @@ #import <Foundation/Foundation.h> #include <Security/Authorization.h> +#include "base/apple/bundle_locations.h" #include "base/mac/authorization_util.h" -#include "base/mac/bundle_locations.h" #include "base/mac/foundation_util.h" #include "base/mac/mac_logging.h" #include "base/mac/scoped_authorizationref.h" @@ -24,7 +24,7 @@ // The authentication right name is of the form // `org.chromium.Chromium.access-passwords` or // `com.google.Chrome.access-passwords`. - return [[base::mac::MainBundle() bundleIdentifier] + return [[base::apple::MainBundle() bundleIdentifier] stringByAppendingString:@".access-passwords"]; }
diff --git a/chrome/browser/policy/configuration_policy_handler_list_factory.cc b/chrome/browser/policy/configuration_policy_handler_list_factory.cc index 70f4718..6ec5b13d 100644 --- a/chrome/browser/policy/configuration_policy_handler_list_factory.cc +++ b/chrome/browser/policy/configuration_policy_handler_list_factory.cc
@@ -1879,9 +1879,6 @@ base::Value::Type::INTEGER }, #endif // BUILDFLAG(IS_WIN) #if BUILDFLAG(ENABLE_PPAPI) - { key::kUseMojoVideoDecoderForPepperAllowed, - policy::policy_prefs::kUseMojoVideoDecoderForPepperAllowed, - base::Value::Type::BOOLEAN }, { key::kPPAPISharedImagesSwapChainAllowed, policy::policy_prefs::kPPAPISharedImagesSwapChainAllowed, base::Value::Type::BOOLEAN },
diff --git a/chrome/browser/predictors/autocomplete_action_predictor.cc b/chrome/browser/predictors/autocomplete_action_predictor.cc index b1ca592..6b63ad2 100644 --- a/chrome/browser/predictors/autocomplete_action_predictor.cc +++ b/chrome/browser/predictors/autocomplete_action_predictor.cc
@@ -37,10 +37,29 @@ #include "components/omnibox/browser/base_search_provider.h" #include "components/omnibox/browser/omnibox_log.h" #include "content/public/browser/browser_thread.h" +#include "content/public/browser/navigation_handle.h" #include "content/public/browser/preloading_data.h" #include "content/public/browser/web_contents_delegate.h" #include "content/public/common/content_features.h" #include "third_party/blink/public/common/features.h" +#include "ui/base/page_transition_types.h" + +namespace { +void SetIsNavigationInDomainCallback(content::PreloadingData* preloading_data) { + preloading_data->SetIsNavigationInDomainCallback( + chrome_preloading_predictor::kOmniboxDirectURLInput, + base::BindRepeating( + [](content::NavigationHandle* navigation_handle) -> bool { + auto transition_type = navigation_handle->GetPageTransition(); + return (transition_type & ui::PAGE_TRANSITION_FROM_ADDRESS_BAR) && + ui::PageTransitionCoreTypeIs( + transition_type, + ui::PageTransition::PAGE_TRANSITION_TYPED) && + ui::PageTransitionIsNewNavigation( + navigation_handle->GetPageTransition()); + })); +} +} // namespace namespace { @@ -207,6 +226,8 @@ content::PreloadingURLMatchCallback same_url_matcher = content::PreloadingData::GetSameURLMatcher(url); + SetIsNavigationInDomainCallback(preloading_data); + if (prerender_utils::IsDirectUrlInputPrerenderEnabled()) { // Create new PreloadingAttempt and pass all the values corresponding to // this prerendering attempt for Prerender. @@ -308,6 +329,7 @@ auto* preloading_data = content::PreloadingData::GetOrCreateForWebContents(web_contents); + SetIsNavigationInDomainCallback(preloading_data); // We multiply confidence by 100 to pass the percentage and cast it into int // for logs.
diff --git a/chrome/browser/prefs/browser_prefs.cc b/chrome/browser/prefs/browser_prefs.cc index 0378f83..f05d21d7 100644 --- a/chrome/browser/prefs/browser_prefs.cc +++ b/chrome/browser/prefs/browser_prefs.cc
@@ -815,6 +815,10 @@ "video_tutorials.last_updated_time"; #endif // BUILDFLAG(IS_ANDROID) +// Deprecated 05/2023 +const char kUseMojoVideoDecoderForPepperAllowed[] = + "policy.use_mojo_video_decoder_for_pepper_allowed"; + // Register local state used only for migration (clearing or moving to a new // key). void RegisterLocalStatePrefsForMigration(PrefRegistrySimple* registry) { @@ -904,6 +908,9 @@ registry->RegisterTimePref(kLastChromadMigrationAttemptTime, /*default_value=*/base::Time()); #endif // BUILDFLAG(IS_CHROMEOS_ASH) + + // Deprecated 05/2023. + registry->RegisterBooleanPref(kUseMojoVideoDecoderForPepperAllowed, true); } // Register prefs used only for migration (clearing or moving to a new key). @@ -1885,6 +1892,9 @@ local_state->ClearPref(kLastChromadMigrationAttemptTime); #endif // BUILDFLAG(IS_CHROMEOS_ASH) + // Added 05/2023. + local_state->ClearPref(kUseMojoVideoDecoderForPepperAllowed); + // Please don't delete the following line. It is used by PRESUBMIT.py. // END_MIGRATE_OBSOLETE_LOCAL_STATE_PREFS
diff --git a/chrome/browser/preloading/prefetch/search_prefetch/search_prefetch_service.cc b/chrome/browser/preloading/prefetch/search_prefetch/search_prefetch_service.cc index 15fb962..f140698f 100644 --- a/chrome/browser/preloading/prefetch/search_prefetch/search_prefetch_service.cc +++ b/chrome/browser/preloading/prefetch/search_prefetch/search_prefetch_service.cc
@@ -39,6 +39,7 @@ #include "components/prefs/pref_registry_simple.h" #include "components/prefs/pref_service.h" #include "components/search_engines/template_url_service.h" +#include "content/public/browser/navigation_handle.h" #include "content/public/browser/preloading_data.h" #include "content/public/browser/web_contents.h" #include "net/base/load_flags.h" @@ -50,6 +51,28 @@ using omnibox::mojom::NavigationPredictor; namespace { +void SetIsNavigationInDomainCallback(content::PreloadingData* preloading_data) { + constexpr content::PreloadingPredictor kPredictors[] = { + chrome_preloading_predictor::kDefaultSearchEngine, + chrome_preloading_predictor::kOmniboxSearchSuggestDefaultMatch, + chrome_preloading_predictor::kOmniboxMousePredictor, + chrome_preloading_predictor::kOmniboxSearchPredictor}; + for (const auto& predictor : kPredictors) { + preloading_data->SetIsNavigationInDomainCallback( + predictor, + base::BindRepeating( + [](content::NavigationHandle* navigation_handle) -> bool { + auto transition_type = navigation_handle->GetPageTransition(); + return (transition_type & ui::PAGE_TRANSITION_FROM_ADDRESS_BAR) && + ui::PageTransitionCoreTypeIs( + transition_type, + ui::PageTransition::PAGE_TRANSITION_GENERATED); + })); + } +} +} // namespace + +namespace { // Recomputes the destination URL for |match| with the updated prefetch // information (does not modify |destination_url|). Passing true to @@ -247,7 +270,7 @@ auto* preloading_data = content::PreloadingData::GetOrCreateForWebContents(web_contents); - + SetIsNavigationInDomainCallback(preloading_data); // Create new PreloadingAttempt and pass all the values corresponding to // this DefaultSearchEngine or OmniboxSearchPredictor prefetch attempt when // |navigation_prefetch| is true. @@ -686,6 +709,7 @@ int64_t confidence = BaseSearchProvider::ShouldPrerender(match) ? 80 : 60; auto* preloading_data = content::PreloadingData::GetOrCreateForWebContents(web_contents); + SetIsNavigationInDomainCallback(preloading_data); GURL canonical_search_url; HasCanoncialPreloadingOmniboxSearchURL(match.destination_url, profile_, &canonical_search_url); @@ -834,7 +858,7 @@ } }; auto predictor = navigation_likely_event_to_predictor(navigation_predictor); - + SetIsNavigationInDomainCallback(preloading_data); // Create PreloadingPrediction for this match. We set the confidence to 100 as // when the user changed the selected match, we always trigger prefetch. preloading_data->AddPreloadingPrediction(predictor, 100, @@ -1043,6 +1067,7 @@ // this prerendering attempt. auto* preloading_data = content::PreloadingData::GetOrCreateForWebContents(web_contents); + SetIsNavigationInDomainCallback(preloading_data); content::PreloadingAttempt* preloading_attempt = preloading_data->AddPreloadingAttempt( chrome_preloading_predictor::kDefaultSearchEngine,
diff --git a/chrome/browser/printing/print_browsertest.cc b/chrome/browser/printing/print_browsertest.cc index 4f9eda4..e6dd15e 100644 --- a/chrome/browser/printing/print_browsertest.cc +++ b/chrome/browser/printing/print_browsertest.cc
@@ -26,7 +26,6 @@ #include "base/threading/thread_restrictions.h" #include "build/build_config.h" #include "build/chromeos_buildflags.h" -#include "chrome/browser/enterprise/connectors/analysis/content_analysis_dialog.h" #include "chrome/browser/extensions/extension_browsertest.h" #include "chrome/browser/printing/browser_printing_context_factory_for_test.h" #include "chrome/browser/printing/print_error_dialog.h" @@ -80,7 +79,6 @@ #include "printing/printing_context.h" #include "printing/printing_context_factory_for_test.h" #include "printing/printing_features.h" -#include "printing/printing_utils.h" #include "printing/test_printing_context.h" #include "printing/units.h" #include "testing/gmock/include/gmock/gmock.h" @@ -100,13 +98,6 @@ #include "chrome/services/printing/public/mojom/print_backend_service.mojom.h" #endif -#if BUILDFLAG(ENABLE_PRINT_CONTENT_ANALYSIS) -#include "chrome/browser/enterprise/connectors/analysis/fake_content_analysis_delegate.h" -#include "chrome/browser/enterprise/connectors/common.h" -#include "chrome/browser/policy/dm_token_utils.h" -#include "chrome/browser/safe_browsing/cloud_content_scanning/deep_scanning_test_utils.h" -#endif // BUILDFLAG(ENABLE_PRINT_CONTENT_ANALYSIS) - namespace printing { using testing::_; @@ -153,10 +144,6 @@ ] })"; -#if BUILDFLAG(ENABLE_PRINT_CONTENT_ANALYSIS) -constexpr char kFakeDmToken[] = "fake-dm-token"; -#endif // BUILDFLAG(ENABLE_PRINT_CONTENT_ANALYSIS) - class KillPrintRenderFrame : public mojom::PrintRenderFrameInterceptorForTesting { public: @@ -423,160 +410,6 @@ PrintAllowance allowance_ = PrintAllowance::kUnknown; }; -#if BUILDFLAG(ENABLE_PRINT_CONTENT_ANALYSIS) -class TestPrintViewManagerForContentAnalysis : public TestPrintViewManager { - public: - class Observer : public PrintViewManagerBase::Observer { - public: - void OnPrintNow(const content::RenderFrameHost* rfh) override { - print_now_called_ = true; - } - - void OnScriptedPrint() override { scripted_print_called_ = true; } - - bool print_now_called() const { return print_now_called_; } - - bool scripted_print_called() const { return scripted_print_called_; } - - private: - bool print_now_called_ = false; - bool scripted_print_called_ = false; - }; - - static TestPrintViewManagerForContentAnalysis* CreateForWebContents( - content::WebContents* web_contents) { - auto manager = - std::make_unique<TestPrintViewManagerForContentAnalysis>(web_contents); - auto* manager_ptr = manager.get(); - web_contents->SetUserData(PrintViewManager::UserDataKey(), - std::move(manager)); - return manager_ptr; - } - - explicit TestPrintViewManagerForContentAnalysis( - content::WebContents* web_contents) - : TestPrintViewManager(web_contents) { - AddObserver(observer_); - PrintViewManager::SetReceiverImplForTesting(this); - } - - ~TestPrintViewManagerForContentAnalysis() override { - PrintViewManager::SetReceiverImplForTesting(nullptr); - } - - void WaitOnScanning() { scanning_run_loop_.Run(); } - - void WaitOnPreview() { preview_run_loop_.Run(); } - - bool print_now_called() const { return observer_.print_now_called(); } - - bool scripted_print_called() const { - return observer_.scripted_print_called(); - } - - const absl::optional<bool>& preview_allowed() const { - return preview_allowed_; - } - -#if BUILDFLAG(IS_CHROMEOS) - void set_allowed_by_dlp(bool allowed) { allowed_by_dlp_ = allowed; } -#endif // BUILDFLAG(IS_CHROMEOS) - - protected: - void OnGotSnapshotCallback( - base::OnceCallback<void(bool should_proceed)> callback, - enterprise_connectors::ContentAnalysisDelegate::Data data, - content::GlobalRenderFrameHostId rfh_id, - mojom::DidPrintDocumentParamsPtr params) override { - ASSERT_TRUE(web_contents()); - ASSERT_TRUE(params); - EXPECT_TRUE(params->content->metafile_data_region.IsValid()); - EXPECT_EQ(data.url, - web_contents()->GetOutermostWebContents()->GetLastCommittedURL()); - - PrintViewManager::OnGotSnapshotCallback( - std::move(callback), std::move(data), rfh_id, std::move(params)); - } - - void OnCompositedForContentAnalysis( - base::OnceCallback<void(bool should_proceed)> callback, - enterprise_connectors::ContentAnalysisDelegate::Data data, - content::GlobalRenderFrameHostId rfh_id, - mojom::PrintCompositor::Status status, - base::ReadOnlySharedMemoryRegion page_region) override { - EXPECT_TRUE(content::RenderFrameHost::FromID(rfh_id)); - EXPECT_EQ(status, mojom::PrintCompositor::Status::kSuccess); - - // The settings passed to this function should match the content of the - // print Connector policy. - EXPECT_EQ(data.settings.tags.size(), 1u); - EXPECT_TRUE(base::Contains(data.settings.tags, "dlp")); - EXPECT_TRUE(data.settings.cloud_or_local_settings.is_cloud_analysis()); - EXPECT_EQ(data.settings.cloud_or_local_settings.dm_token(), kFakeDmToken); - EXPECT_EQ(data.settings.block_until_verdict, - enterprise_connectors::BlockUntilVerdict::kBlock); - EXPECT_TRUE(data.settings.block_large_files); - EXPECT_EQ(data.url, - web_contents()->GetOutermostWebContents()->GetLastCommittedURL()); - - // The snapshot should be valid and populated. - EXPECT_TRUE(LooksLikePdf(page_region.Map().GetMemoryAsSpan<char>())); - - PrintViewManager::OnCompositedForContentAnalysis( - base::BindOnce( - [](base::OnceCallback<void(bool should_proceed)> callback, - base::RunLoop* scanning_run_loop, bool allowed) { - std::move(callback).Run(allowed); - scanning_run_loop->Quit(); - }, - std::move(callback), &scanning_run_loop_), - std::move(data), rfh_id, status, std::move(page_region)); - } - -#if BUILDFLAG(IS_CHROMEOS) - void OnDlpPrintingRestrictionsChecked( - content::GlobalRenderFrameHostId rfh_id, - base::OnceCallback<void(bool should_proceed)> callback, - bool should_proceed) override { - PrintViewManager::OnDlpPrintingRestrictionsChecked( - rfh_id, std::move(callback), allowed_by_dlp_); - } -#endif // BUILDFLAG(IS_CHROMEOS) - - void CompleteScriptedPrint(content::RenderFrameHost* rfh, - mojom::ScriptedPrintParamsPtr params, - ScriptedPrintCallback callback) override { - std::move(callback).Run(nullptr); - - for (auto& observer : GetObservers()) - observer.OnScriptedPrint(); - } - - private: - void PrintPreviewRejectedForTesting() override { - preview_allowed_ = false; - preview_run_loop_.Quit(); - } - - void PrintPreviewAllowedForTesting() override { - preview_allowed_ = true; - preview_run_loop_.Quit(); - } - -#if BUILDFLAG(IS_CHROMEOS) - bool allowed_by_dlp_ = true; -#endif // BUILDFLAG(IS_CHROMEOS) - - // Indicates whether the preview was allowed after checking against content - // analysis and DLP (if on CrOS). This is unpopulated until then. - absl::optional<bool> preview_allowed_; - - base::RunLoop preview_run_loop_; - base::RunLoop scanning_run_loop_; - Observer observer_; -}; -#endif // BUILDFLAG(ENABLE_PRINT_CONTENT_ANALYSIS) - PrintBrowserTest::PrintBrowserTest() = default; PrintBrowserTest::~PrintBrowserTest() = default; @@ -2083,253 +1916,4 @@ RunPrintTest("document.execCommand('print');"); } -#if BUILDFLAG(ENABLE_PRINT_CONTENT_ANALYSIS) -struct ContentAnalysisTestCase { - bool content_analysis_allows_print = false; - bool oop_enabled = false; -}; - -class ContentAnalysisPrintBrowserTest - : public PrintBrowserTest, - public testing::WithParamInterface<ContentAnalysisTestCase> { - public: - ContentAnalysisPrintBrowserTest() { - policy::SetDMTokenForTesting( - policy::DMToken::CreateValidToken(kFakeDmToken)); - enterprise_connectors::ContentAnalysisDelegate::SetFactoryForTesting( - base::BindRepeating( - &enterprise_connectors::FakeContentAnalysisDelegate::Create, - base::DoNothing(), - base::BindRepeating( - &ContentAnalysisPrintBrowserTest::ScanningResponse, - base::Unretained(this)), - kFakeDmToken)); - enterprise_connectors::ContentAnalysisDialog::SetShowDialogDelayForTesting( - base::Milliseconds(0)); - } - - void SetUp() override { - if (oop_enabled()) { - feature_list_.InitWithFeaturesAndParameters( - { - {features::kEnableOopPrintDrivers, - {{features::kEnableOopPrintDriversJobPrint.name, "true"}}}, - }, - {}); - } - - test_printing_context_factory()->SetPrinterNameForSubsequentContexts( - "printer_name"); - PrintBrowserTest::SetUp(); - } - - void SetUpOnMainThread() override { - safe_browsing::SetAnalysisConnector( - browser()->profile()->GetPrefs(), - enterprise_connectors::AnalysisConnector::PRINT, - R"({ - "service_provider": "google", - "enable": [ {"url_list": ["*"], "tags": ["dlp"]} ], - "block_until_verdict": 1, - "block_large_files": true - })"); - PrintBrowserTest::SetUpOnMainThread(); - } - - bool content_analysis_allows_print() const { - return GetParam().content_analysis_allows_print; - } - bool oop_enabled() { return GetParam().oop_enabled; } - - enterprise_connectors::ContentAnalysisResponse ScanningResponse( - const std::string& contents, - const base::FilePath& path) { - enterprise_connectors::ContentAnalysisResponse response; - - auto* result = response.add_results(); - result->set_tag("dlp"); - result->set_status( - enterprise_connectors::ContentAnalysisResponse::Result::SUCCESS); - - if (!content_analysis_allows_print()) { - auto* rule = result->add_triggered_rules(); - rule->set_rule_name("blocking_rule_name"); - rule->set_action(enterprise_connectors::TriggeredRule::BLOCK); - } - - return response; - } - - int new_document_called_count() { - return test_printing_context_factory()->new_document_called_count(); - } - - private: - base::test::ScopedFeatureList feature_list_; -}; - -class ContentAnalysisScriptedPreviewlessPrintBrowserTest - : public ContentAnalysisPrintBrowserTest { - public: - void SetUpCommandLine(base::CommandLine* cmd_line) override { - cmd_line->AppendSwitch(switches::kDisablePrintPreview); - ContentAnalysisPrintBrowserTest::SetUpCommandLine(cmd_line); - } - - void RunScriptedPrintTest(const std::string& script) { - AddPrinter("printer_name"); - ASSERT_TRUE(embedded_test_server()->Started()); - GURL url(embedded_test_server()->GetURL("/printing/test1.html")); - ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), url)); - - content::WebContents* web_contents = - browser()->tab_strip_model()->GetActiveWebContents(); - ASSERT_TRUE(web_contents); - auto* print_view_manager = - TestPrintViewManagerForContentAnalysis::CreateForWebContents( - web_contents); - content::ExecuteScriptAsync(web_contents->GetPrimaryMainFrame(), script); - - print_view_manager->WaitOnScanning(); - ASSERT_EQ(print_view_manager->scripted_print_called(), - content_analysis_allows_print()); - - // Validate that `NewDocument` was never call as that can needlessly - // prompt the user. - ASSERT_EQ(new_document_called_count(), 0); - } -}; - -#if !BUILDFLAG(IS_CHROMEOS) -IN_PROC_BROWSER_TEST_P(ContentAnalysisPrintBrowserTest, PrintNow) { -#if BUILDFLAG(IS_WIN) - // TODO(crbug.com/1396386): Remove this when tests are fixed. - if (oop_enabled()) - return; -#endif - - AddPrinter("printer_name"); - ASSERT_TRUE(embedded_test_server()->Started()); - GURL url(embedded_test_server()->GetURL("/printing/test1.html")); - ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), url)); - - content::WebContents* web_contents = - browser()->tab_strip_model()->GetActiveWebContents(); - ASSERT_TRUE(web_contents); - auto* print_view_manager = - TestPrintViewManagerForContentAnalysis::CreateForWebContents( - web_contents); - - StartPrint(browser()->tab_strip_model()->GetActiveWebContents(), -#if BUILDFLAG(IS_CHROMEOS_ASH) - /*print_renderer=*/mojo::NullAssociatedRemote(), -#endif - /*print_preview_disabled=*/true, - /*has_selection=*/false); - - print_view_manager->WaitOnScanning(); - - // PrintNow uses the same code path as scripted prints to scan printed pages, - // so print_now_called() should always happen and scripted_print_called() - // should be called with the same result that is expected from scanning. - ASSERT_TRUE(print_view_manager->print_now_called()); - ASSERT_EQ(print_view_manager->scripted_print_called(), - content_analysis_allows_print()); - - // Validate that `NewDocument` was never call as that can needlessly - // prompt the user. - ASSERT_EQ(new_document_called_count(), 0); -} - -IN_PROC_BROWSER_TEST_P(ContentAnalysisPrintBrowserTest, PrintWithPreview) { - AddPrinter("printer_name"); - ASSERT_TRUE(embedded_test_server()->Started()); - GURL url(embedded_test_server()->GetURL("/printing/test1.html")); - ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), url)); - - content::WebContents* web_contents = - browser()->tab_strip_model()->GetActiveWebContents(); - ASSERT_TRUE(web_contents); - auto* print_view_manager = - TestPrintViewManagerForContentAnalysis::CreateForWebContents( - web_contents); - - test::StartPrint(browser()->tab_strip_model()->GetActiveWebContents()); - - print_view_manager->WaitOnScanning(); - ASSERT_EQ(print_view_manager->preview_allowed(), - content_analysis_allows_print()); - - // Validate that `NewDocument` was never call as that can needlessly - // prompt the user. - ASSERT_EQ(new_document_called_count(), 0); -} - -IN_PROC_BROWSER_TEST_P(ContentAnalysisScriptedPreviewlessPrintBrowserTest, - DocumentExecPrint) { - RunScriptedPrintTest("document.execCommand('print');"); -} - -IN_PROC_BROWSER_TEST_P(ContentAnalysisScriptedPreviewlessPrintBrowserTest, - WindowPrint) { - RunScriptedPrintTest("window.print()"); -} - -#endif // !BUILDFLAG(IS_CHROMEOS) - -#if BUILDFLAG(IS_CHROMEOS) -IN_PROC_BROWSER_TEST_P(ContentAnalysisPrintBrowserTest, - BlockedByDLPThenNoContentAnalysis) { - AddPrinter("printer_name"); - ASSERT_TRUE(embedded_test_server()->Started()); - GURL url(embedded_test_server()->GetURL("/printing/test1.html")); - ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), url)); - - content::WebContents* web_contents = - browser()->tab_strip_model()->GetActiveWebContents(); - ASSERT_TRUE(web_contents); - auto* print_view_manager = - TestPrintViewManagerForContentAnalysis::CreateForWebContents( - web_contents); - print_view_manager->set_allowed_by_dlp(false); - - test::StartPrint(browser()->tab_strip_model()->GetActiveWebContents()); - - print_view_manager->WaitOnPreview(); - ASSERT_TRUE(print_view_manager->preview_allowed().has_value()); - ASSERT_FALSE(print_view_manager->preview_allowed().value()); - - // This is always 0 because printing is always blocked by the DLP policy. - ASSERT_EQ(new_document_called_count(), 0); -} -#endif // BUILDFLAG(IS_CHROMEOS) - -INSTANTIATE_TEST_SUITE_P( - All, - ContentAnalysisPrintBrowserTest, - testing::Values( - ContentAnalysisTestCase{/*content_analysis_allows_print=*/true, - /*oop_enabled=*/true}, - ContentAnalysisTestCase{/*content_analysis_allows_print=*/true, - /*oop_enabled=*/false}, - ContentAnalysisTestCase{/*content_analysis_allows_print=*/false, - /*oop_enabled=*/true}, - ContentAnalysisTestCase{/*content_analysis_allows_print=*/false, - /*oop_enabled=*/false})); - -#if BUILDFLAG(ENABLE_BASIC_PRINT_DIALOG) -INSTANTIATE_TEST_SUITE_P( - All, - ContentAnalysisScriptedPreviewlessPrintBrowserTest, - // TODO(crbug.com/1396386): Add back oop_enabled=true values when tests are - // fixed. - testing::Values( - ContentAnalysisTestCase{/*content_analysis_allows_print=*/true, - /*oop_enabled=*/false}, - ContentAnalysisTestCase{/*content_analysis_allows_print=*/false, - /*oop_enabled=*/false})); -#endif // BUILDFLAG(ENABLE_BASIC_PRINT_DIALOG) - -#endif // BUILDFLAG(ENABLE_PRINT_SCANNING) - } // namespace printing
diff --git a/chrome/browser/printing/print_view_manager.cc b/chrome/browser/printing/print_view_manager.cc index eb38b4a..cbafc20a 100644 --- a/chrome/browser/printing/print_view_manager.cc +++ b/chrome/browser/printing/print_view_manager.cc
@@ -27,14 +27,15 @@ #include "mojo/public/cpp/bindings/associated_remote.h" #include "printing/buildflags/buildflags.h" #include "printing/printing_features.h" +#include "third_party/abseil-cpp/absl/types/optional.h" #if BUILDFLAG(IS_CHROMEOS) #include "chrome/browser/chromeos/policy/dlp/dlp_content_manager.h" #endif #if BUILDFLAG(ENABLE_PRINT_CONTENT_ANALYSIS) -#include "chrome/browser/enterprise/connectors/analysis/content_analysis_delegate.h" -#endif // BUILDFLAG(ENABLE_PRINT_CONTENT_ANALYSIS) +#include "chrome/browser/enterprise/connectors/analysis/print_content_analysis_utils.h" +#endif using content::BrowserThread; @@ -276,17 +277,15 @@ void PrintViewManager::RejectPrintPreviewRequestIfRestrictedByContentAnalysis( content::GlobalRenderFrameHostId rfh_id, base::OnceCallback<void(bool should_proceed)> callback) { - enterprise_connectors::ContentAnalysisDelegate::Data scanning_data; + absl::optional<enterprise_connectors::ContentAnalysisDelegate::Data> + scanning_data = enterprise_connectors::ShouldAnalyzeBeforePrintPreview( + web_contents()); content::RenderFrameHost* rfh = content::RenderFrameHost::FromID(rfh_id); - if (rfh && - enterprise_connectors::ContentAnalysisDelegate::IsEnabled( - Profile::FromBrowserContext(web_contents()->GetBrowserContext()), - web_contents()->GetOutermostWebContents()->GetLastCommittedURL(), - &scanning_data, enterprise_connectors::AnalysisConnector::PRINT)) { + if (rfh && scanning_data) { set_snapshotting_for_content_analysis(); GetPrintRenderFrame(rfh)->SnapshotForContentAnalysis(base::BindOnce( &PrintViewManager::OnGotSnapshotCallback, weak_factory_.GetWeakPtr(), - std::move(callback), std::move(scanning_data), rfh_id)); + std::move(callback), std::move(*scanning_data), rfh_id)); return; }
diff --git a/chrome/browser/printing/print_view_manager_base.cc b/chrome/browser/printing/print_view_manager_base.cc index d35cfe8..95cd7d23 100644 --- a/chrome/browser/printing/print_view_manager_base.cc +++ b/chrome/browser/printing/print_view_manager_base.cc
@@ -75,6 +75,10 @@ #include "chrome/browser/printing/print_job_utils_lacros.h" #endif +#if BUILDFLAG(ENABLE_PRINT_CONTENT_ANALYSIS) +#include "chrome/browser/enterprise/connectors/analysis/print_content_analysis_utils.h" +#endif + namespace printing { namespace { @@ -598,9 +602,8 @@ !snapshotting_for_content_analysis_ && #endif !query_with_ui_client_id_.has_value()) { - // Renderer process has requested settings outside of the expected setup. - GetDefaultPrintSettingsReply(std::move(callback), nullptr); - return; + // Script initiated print, this is first signal of start of printing. + RegisterSystemPrintClient(); } #endif @@ -752,13 +755,11 @@ return; } #endif - #if BUILDFLAG(ENABLE_PRINT_CONTENT_ANALYSIS) - enterprise_connectors::ContentAnalysisDelegate::Data scanning_data; - if (enterprise_connectors::ContentAnalysisDelegate::IsEnabled( - Profile::FromBrowserContext(web_contents()->GetBrowserContext()), - web_contents()->GetOutermostWebContents()->GetLastCommittedURL(), - &scanning_data, enterprise_connectors::AnalysisConnector::PRINT)) { + absl::optional<enterprise_connectors::ContentAnalysisDelegate::Data> + scanning_data = enterprise_connectors::ShouldAnalyzeBeforePrintPreview( + web_contents()); + if (scanning_data) { auto scanning_done_callback = base::BindOnce( &PrintViewManagerBase::CompleteScriptedPrintAfterContentAnalysis, weak_ptr_factory_.GetWeakPtr(), std::move(params), std::move(callback)); @@ -767,7 +768,7 @@ ->SnapshotForContentAnalysis(base::BindOnce( &PrintViewManagerBase::OnGotSnapshotCallback, weak_ptr_factory_.GetWeakPtr(), std::move(scanning_done_callback), - std::move(scanning_data), render_frame_host->GetGlobalId())); + std::move(*scanning_data), render_frame_host->GetGlobalId())); return; } #endif // BUILDFLAG(ENABLE_PRINT_CONTENT_ANALYSIS)
diff --git a/chrome/browser/printing/system_access_process_print_browsertest.cc b/chrome/browser/printing/system_access_process_print_browsertest.cc index e00c7d5..dc77e84a 100644 --- a/chrome/browser/printing/system_access_process_print_browsertest.cc +++ b/chrome/browser/printing/system_access_process_print_browsertest.cc
@@ -11,6 +11,7 @@ #include "base/memory/raw_ptr.h" #include "base/test/scoped_feature_list.h" #include "build/build_config.h" +#include "chrome/browser/enterprise/connectors/analysis/content_analysis_dialog.h" #include "chrome/browser/printing/print_browsertest.h" #include "chrome/browser/printing/print_job.h" #include "chrome/browser/printing/print_test_utils.h" @@ -21,6 +22,7 @@ #include "chrome/browser/printing/test_print_view_manager.h" #include "chrome/browser/ui/browser.h" #include "chrome/browser/ui/tabs/tab_strip_model.h" +#include "chrome/common/chrome_switches.h" #include "chrome/test/base/ui_test_utils.h" #include "content/public/browser/global_routing_id.h" #include "content/public/browser/web_contents.h" @@ -32,6 +34,7 @@ #include "printing/mojom/print.mojom.h" #include "printing/printing_context.h" #include "printing/printing_features.h" +#include "printing/printing_utils.h" #include "testing/gtest/include/gtest/gtest.h" #include "third_party/abseil-cpp/absl/types/optional.h" @@ -43,6 +46,13 @@ #include "chrome/services/printing/public/mojom/print_backend_service.mojom.h" #endif +#if BUILDFLAG(ENABLE_PRINT_CONTENT_ANALYSIS) +#include "chrome/browser/enterprise/connectors/analysis/fake_content_analysis_delegate.h" +#include "chrome/browser/enterprise/connectors/common.h" +#include "chrome/browser/policy/dm_token_utils.h" +#include "chrome/browser/safe_browsing/cloud_content_scanning/deep_scanning_test_utils.h" +#endif // BUILDFLAG(ENABLE_PRINT_CONTENT_ANALYSIS) + #if BUILDFLAG(IS_CHROMEOS) // TODO(crbug.com/822505) ChromeOS uses different testing setup that isn't // hooked up to make use of `TestPrintingContext` yet. @@ -66,6 +76,10 @@ constexpr gfx::Size kLegalExpectedContentSize = gfx::Size(556, 952); #endif // !BUILDFLAG(IS_CHROMEOS) +#if BUILDFLAG(ENABLE_PRINT_CONTENT_ANALYSIS) +constexpr char kFakeDmToken[] = "fake-dm-token"; +#endif // BUILDFLAG(ENABLE_PRINT_CONTENT_ANALYSIS) + } // namespace #if BUILDFLAG(ENABLE_OOP_PRINTING) @@ -352,6 +366,10 @@ &SystemAccessProcessPrintBrowserTestBase::OnDidCancel, base::Unretained(this)); } else { + feature_list_.InitWithFeatures( + /*enabled_features=*/{}, + /*disabled_features=*/{features::kEnableOopPrintDrivers}); + test_print_job_worker_callbacks_.did_use_default_settings_callback = base::BindRepeating( &SystemAccessProcessPrintBrowserTestBase::OnUseDefaultSettings, @@ -396,6 +414,15 @@ ASSERT_EQ(print_job_construction_count(), print_job_destruction_count()); } + // `PrintBackendServiceTestImpl` does a debug check on shutdown that there + // are no residual persistent printing contexts left in the service. For + // tests which are known to break this (either by design, for test simplicity + // or because a related change is only partly implemented), use this method + // to notify the service to not DCHECK on such a condition. + void SkipPersistentContextsCheckOnShutdown() { + print_backend_service_->SkipPersistentContextsCheckOnShutdown(); + } + // PrintViewManagerBase::Observer: void OnRegisterSystemPrintClient(bool succeeded) override { system_print_registration_succeeded_ = succeeded; @@ -1936,4 +1963,410 @@ #endif // BUILDFLAG(ENABLE_OOP_PRINTING) +#if BUILDFLAG(ENABLE_PRINT_CONTENT_ANALYSIS) +class TestPrintViewManagerForContentAnalysis : public TestPrintViewManager { + public: + class Observer : public PrintViewManagerBase::Observer { + public: + void OnPrintNow(const content::RenderFrameHost* rfh) override { + print_now_called_ = true; + } + + void OnScriptedPrint() override { scripted_print_called_ = true; } + + bool print_now_called() const { return print_now_called_; } + + bool scripted_print_called() const { return scripted_print_called_; } + + private: + bool print_now_called_ = false; + bool scripted_print_called_ = false; + }; + + static TestPrintViewManagerForContentAnalysis* CreateForWebContents( + content::WebContents* web_contents) { + auto manager = + std::make_unique<TestPrintViewManagerForContentAnalysis>(web_contents); + auto* manager_ptr = manager.get(); + web_contents->SetUserData(PrintViewManager::UserDataKey(), + std::move(manager)); + return manager_ptr; + } + + explicit TestPrintViewManagerForContentAnalysis( + content::WebContents* web_contents) + : TestPrintViewManager(web_contents) { + AddObserver(observer_); + PrintViewManager::SetReceiverImplForTesting(this); + } + + ~TestPrintViewManagerForContentAnalysis() override { + PrintViewManager::SetReceiverImplForTesting(nullptr); + } + + void WaitOnScanning() { scanning_run_loop_.Run(); } + + void WaitOnPreview() { preview_run_loop_.Run(); } + + bool print_now_called() const { return observer_.print_now_called(); } + + bool scripted_print_called() const { + return observer_.scripted_print_called(); + } + + const absl::optional<bool>& preview_allowed() const { + return preview_allowed_; + } + +#if BUILDFLAG(IS_CHROMEOS) + void set_allowed_by_dlp(bool allowed) { allowed_by_dlp_ = allowed; } +#endif // BUILDFLAG(IS_CHROMEOS) + + protected: + void OnGotSnapshotCallback( + base::OnceCallback<void(bool should_proceed)> callback, + enterprise_connectors::ContentAnalysisDelegate::Data data, + content::GlobalRenderFrameHostId rfh_id, + mojom::DidPrintDocumentParamsPtr params) override { + ASSERT_TRUE(web_contents()); + ASSERT_TRUE(params); + EXPECT_TRUE(params->content->metafile_data_region.IsValid()); + EXPECT_EQ(data.url, + web_contents()->GetOutermostWebContents()->GetLastCommittedURL()); + + PrintViewManager::OnGotSnapshotCallback( + std::move(callback), std::move(data), rfh_id, std::move(params)); + } + + void OnCompositedForContentAnalysis( + base::OnceCallback<void(bool should_proceed)> callback, + enterprise_connectors::ContentAnalysisDelegate::Data data, + content::GlobalRenderFrameHostId rfh_id, + mojom::PrintCompositor::Status status, + base::ReadOnlySharedMemoryRegion page_region) override { + EXPECT_TRUE(content::RenderFrameHost::FromID(rfh_id)); + EXPECT_EQ(status, mojom::PrintCompositor::Status::kSuccess); + + // The settings passed to this function should match the content of the + // print Connector policy. + EXPECT_EQ(data.settings.tags.size(), 1u); + EXPECT_TRUE(base::Contains(data.settings.tags, "dlp")); + EXPECT_TRUE(data.settings.cloud_or_local_settings.is_cloud_analysis()); + EXPECT_EQ(data.settings.cloud_or_local_settings.dm_token(), kFakeDmToken); + EXPECT_EQ(data.settings.block_until_verdict, + enterprise_connectors::BlockUntilVerdict::kBlock); + EXPECT_TRUE(data.settings.block_large_files); + EXPECT_EQ(data.url, + web_contents()->GetOutermostWebContents()->GetLastCommittedURL()); + + // The snapshot should be valid and populated. + EXPECT_TRUE(LooksLikePdf(page_region.Map().GetMemoryAsSpan<char>())); + + PrintViewManager::OnCompositedForContentAnalysis( + base::BindOnce( + [](base::OnceCallback<void(bool should_proceed)> callback, + base::RunLoop* scanning_run_loop, bool allowed) { + std::move(callback).Run(allowed); + scanning_run_loop->Quit(); + }, + std::move(callback), &scanning_run_loop_), + std::move(data), rfh_id, status, std::move(page_region)); + } + +#if BUILDFLAG(IS_CHROMEOS) + void OnDlpPrintingRestrictionsChecked( + content::GlobalRenderFrameHostId rfh_id, + base::OnceCallback<void(bool should_proceed)> callback, + bool should_proceed) override { + PrintViewManager::OnDlpPrintingRestrictionsChecked( + rfh_id, std::move(callback), allowed_by_dlp_); + } +#endif // BUILDFLAG(IS_CHROMEOS) + + void CompleteScriptedPrint(content::RenderFrameHost* rfh, + mojom::ScriptedPrintParamsPtr params, + ScriptedPrintCallback callback) override { + std::move(callback).Run(nullptr); + + for (auto& observer : GetObservers()) { + observer.OnScriptedPrint(); + } + } + + private: + void PrintPreviewRejectedForTesting() override { + preview_allowed_ = false; + preview_run_loop_.Quit(); + } + + void PrintPreviewAllowedForTesting() override { + preview_allowed_ = true; + preview_run_loop_.Quit(); + } + +#if BUILDFLAG(IS_CHROMEOS) + bool allowed_by_dlp_ = true; +#endif // BUILDFLAG(IS_CHROMEOS) + + // Indicates whether the preview was allowed after checking against content + // analysis and DLP (if on CrOS). This is unpopulated until then. + absl::optional<bool> preview_allowed_; + + base::RunLoop preview_run_loop_; + base::RunLoop scanning_run_loop_; + Observer observer_; +}; + +struct ContentAnalysisTestCase { + bool content_analysis_allows_print = false; + bool oop_enabled = false; +}; + +class ContentAnalysisPrintBrowserTest + : public SystemAccessProcessPrintBrowserTestBase, + public testing::WithParamInterface<ContentAnalysisTestCase> { + public: + ContentAnalysisPrintBrowserTest() { + policy::SetDMTokenForTesting( + policy::DMToken::CreateValidToken(kFakeDmToken)); + enterprise_connectors::ContentAnalysisDelegate::SetFactoryForTesting( + base::BindRepeating( + &enterprise_connectors::FakeContentAnalysisDelegate::Create, + base::DoNothing(), + base::BindRepeating( + &ContentAnalysisPrintBrowserTest::ScanningResponse, + base::Unretained(this)), + kFakeDmToken)); + enterprise_connectors::ContentAnalysisDialog::SetShowDialogDelayForTesting( + base::Milliseconds(0)); + } + + void SetUp() override { + test_printing_context_factory()->SetPrinterNameForSubsequentContexts( + "printer_name"); + SystemAccessProcessPrintBrowserTestBase::SetUp(); + } + + void SetUpOnMainThread() override { + safe_browsing::SetAnalysisConnector( + browser()->profile()->GetPrefs(), + enterprise_connectors::AnalysisConnector::PRINT, + R"({ + "service_provider": "google", + "enable": [ {"url_list": ["*"], "tags": ["dlp"]} ], + "block_until_verdict": 1, + "block_large_files": true + })"); + SystemAccessProcessPrintBrowserTestBase::SetUpOnMainThread(); + } + + bool content_analysis_allows_print() const { + return GetParam().content_analysis_allows_print; + } + bool UseService() override { return GetParam().oop_enabled; } + bool SandboxService() override { return true; } + + enterprise_connectors::ContentAnalysisResponse ScanningResponse( + const std::string& contents, + const base::FilePath& path) { + enterprise_connectors::ContentAnalysisResponse response; + + auto* result = response.add_results(); + result->set_tag("dlp"); + result->set_status( + enterprise_connectors::ContentAnalysisResponse::Result::SUCCESS); + + if (!content_analysis_allows_print()) { + auto* rule = result->add_triggered_rules(); + rule->set_rule_name("blocking_rule_name"); + rule->set_action(enterprise_connectors::TriggeredRule::BLOCK); + } + + return response; + } + + int new_document_called_count() { + return test_printing_context_factory()->new_document_called_count(); + } +}; + +class ContentAnalysisScriptedPreviewlessPrintBrowserTest + : public ContentAnalysisPrintBrowserTest { + public: + void SetUpCommandLine(base::CommandLine* cmd_line) override { + cmd_line->AppendSwitch(switches::kDisablePrintPreview); + ContentAnalysisPrintBrowserTest::SetUpCommandLine(cmd_line); + } + + void RunScriptedPrintTest(const std::string& script) { + AddPrinter("printer_name"); + + if (UseService()) { + // Test does not do extra cleanup beyond the check for analysis + // permission. + SkipPersistentContextsCheckOnShutdown(); + } + + ASSERT_TRUE(embedded_test_server()->Started()); + GURL url(embedded_test_server()->GetURL("/printing/test1.html")); + ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), url)); + + content::WebContents* web_contents = + browser()->tab_strip_model()->GetActiveWebContents(); + ASSERT_TRUE(web_contents); + auto* print_view_manager = + TestPrintViewManagerForContentAnalysis::CreateForWebContents( + web_contents); + content::ExecuteScriptAsync(web_contents->GetPrimaryMainFrame(), script); + + print_view_manager->WaitOnScanning(); + ASSERT_EQ(print_view_manager->scripted_print_called(), + content_analysis_allows_print()); + + // Validate that `NewDocument` was never call as that can needlessly + // prompt the user. + ASSERT_EQ(new_document_called_count(), 0); + } +}; + +#if !BUILDFLAG(IS_CHROMEOS) +IN_PROC_BROWSER_TEST_P(ContentAnalysisPrintBrowserTest, PrintNow) { + AddPrinter("printer_name"); + + if (UseService()) { + // Test does not do extra cleanup beyond the check for analysis permission. + SkipPersistentContextsCheckOnShutdown(); + } + + ASSERT_TRUE(embedded_test_server()->Started()); + GURL url(embedded_test_server()->GetURL("/printing/test1.html")); + ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), url)); + + content::WebContents* web_contents = + browser()->tab_strip_model()->GetActiveWebContents(); + ASSERT_TRUE(web_contents); + auto* print_view_manager = + TestPrintViewManagerForContentAnalysis::CreateForWebContents( + web_contents); + + StartPrint(browser()->tab_strip_model()->GetActiveWebContents(), +#if BUILDFLAG(IS_CHROMEOS_ASH) + /*print_renderer=*/mojo::NullAssociatedRemote(), +#endif + /*print_preview_disabled=*/true, + /*has_selection=*/false); + + print_view_manager->WaitOnScanning(); + + // PrintNow uses the same code path as scripted prints to scan printed pages, + // so print_now_called() should always happen and scripted_print_called() + // should be called with the same result that is expected from scanning. + ASSERT_TRUE(print_view_manager->print_now_called()); + ASSERT_EQ(print_view_manager->scripted_print_called(), + content_analysis_allows_print()); + + // Validate that `NewDocument` was never call as that can needlessly + // prompt the user. + ASSERT_EQ(new_document_called_count(), 0); +} + +IN_PROC_BROWSER_TEST_P(ContentAnalysisPrintBrowserTest, PrintWithPreview) { + AddPrinter("printer_name"); + + if (UseService()) { + // Test does not do extra cleanup beyond the check for analysis permission. + SkipPersistentContextsCheckOnShutdown(); + } + + ASSERT_TRUE(embedded_test_server()->Started()); + GURL url(embedded_test_server()->GetURL("/printing/test1.html")); + ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), url)); + + content::WebContents* web_contents = + browser()->tab_strip_model()->GetActiveWebContents(); + ASSERT_TRUE(web_contents); + auto* print_view_manager = + TestPrintViewManagerForContentAnalysis::CreateForWebContents( + web_contents); + + test::StartPrint(browser()->tab_strip_model()->GetActiveWebContents()); + + print_view_manager->WaitOnScanning(); + ASSERT_EQ(print_view_manager->preview_allowed(), + content_analysis_allows_print()); + + // Validate that `NewDocument` was never call as that can needlessly + // prompt the user. + ASSERT_EQ(new_document_called_count(), 0); +} + +IN_PROC_BROWSER_TEST_P(ContentAnalysisScriptedPreviewlessPrintBrowserTest, + DocumentExecPrint) { + RunScriptedPrintTest("document.execCommand('print');"); +} + +IN_PROC_BROWSER_TEST_P(ContentAnalysisScriptedPreviewlessPrintBrowserTest, + WindowPrint) { + RunScriptedPrintTest("window.print()"); +} + +#endif // !BUILDFLAG(IS_CHROMEOS) + +#if BUILDFLAG(IS_CHROMEOS) +IN_PROC_BROWSER_TEST_P(ContentAnalysisPrintBrowserTest, + BlockedByDLPThenNoContentAnalysis) { + AddPrinter("printer_name"); + ASSERT_TRUE(embedded_test_server()->Started()); + GURL url(embedded_test_server()->GetURL("/printing/test1.html")); + ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), url)); + + content::WebContents* web_contents = + browser()->tab_strip_model()->GetActiveWebContents(); + ASSERT_TRUE(web_contents); + auto* print_view_manager = + TestPrintViewManagerForContentAnalysis::CreateForWebContents( + web_contents); + print_view_manager->set_allowed_by_dlp(false); + + test::StartPrint(browser()->tab_strip_model()->GetActiveWebContents()); + + print_view_manager->WaitOnPreview(); + ASSERT_TRUE(print_view_manager->preview_allowed().has_value()); + ASSERT_FALSE(print_view_manager->preview_allowed().value()); + + // This is always 0 because printing is always blocked by the DLP policy. + ASSERT_EQ(new_document_called_count(), 0); +} +#endif // BUILDFLAG(IS_CHROMEOS) + +INSTANTIATE_TEST_SUITE_P( + All, + ContentAnalysisPrintBrowserTest, + testing::Values( + ContentAnalysisTestCase{/*content_analysis_allows_print=*/true, + /*oop_enabled=*/true}, + ContentAnalysisTestCase{/*content_analysis_allows_print=*/true, + /*oop_enabled=*/false}, + ContentAnalysisTestCase{/*content_analysis_allows_print=*/false, + /*oop_enabled=*/true}, + ContentAnalysisTestCase{/*content_analysis_allows_print=*/false, + /*oop_enabled=*/false})); + +#if BUILDFLAG(ENABLE_BASIC_PRINT_DIALOG) +INSTANTIATE_TEST_SUITE_P( + All, + ContentAnalysisScriptedPreviewlessPrintBrowserTest, + testing::Values( + ContentAnalysisTestCase{/*content_analysis_allows_print=*/true, + /*oop_enabled=*/true}, + ContentAnalysisTestCase{/*content_analysis_allows_print=*/true, + /*oop_enabled=*/false}, + ContentAnalysisTestCase{/*content_analysis_allows_print=*/false, + /*oop_enabled=*/true}, + ContentAnalysisTestCase{/*content_analysis_allows_print=*/false, + /*oop_enabled=*/false})); +#endif // BUILDFLAG(ENABLE_BASIC_PRINT_DIALOG) + +#endif // BUILDFLAG(ENABLE_PRINT_CONTENT_ANALYSIS) + } // namespace printing
diff --git a/chrome/browser/privacy/privacy_metrics_service_unittest.cc b/chrome/browser/privacy/privacy_metrics_service_unittest.cc index 71fb5d54..14d12e62 100644 --- a/chrome/browser/privacy/privacy_metrics_service_unittest.cc +++ b/chrome/browser/privacy/privacy_metrics_service_unittest.cc
@@ -65,7 +65,7 @@ sync_service()->SetTransportState( syncer::SyncService::TransportState::DISABLED); sync_service()->SetDisableReasons( - syncer::SyncService::DISABLE_REASON_NOT_SIGNED_IN); + {syncer::SyncService::DISABLE_REASON_NOT_SIGNED_IN}); sync_service()->FireStateChanged(); }
diff --git a/chrome/browser/safe_browsing/incident_reporting/binary_integrity_analyzer_mac.cc b/chrome/browser/safe_browsing/incident_reporting/binary_integrity_analyzer_mac.cc index 10de2a8..350ca40 100644 --- a/chrome/browser/safe_browsing/incident_reporting/binary_integrity_analyzer_mac.cc +++ b/chrome/browser/safe_browsing/incident_reporting/binary_integrity_analyzer_mac.cc
@@ -9,9 +9,9 @@ #include <memory> #include <utility> +#include "base/apple/bundle_locations.h" #include "base/files/file_util.h" #include "base/logging.h" -#include "base/mac/bundle_locations.h" #include "chrome/browser/safe_browsing/incident_reporting/binary_integrity_incident.h" #include "chrome/browser/safe_browsing/incident_reporting/incident_receiver.h" #include "chrome/browser/safe_browsing/signature_evaluator_mac.h" @@ -113,9 +113,9 @@ // clang-format on critical_binaries.push_back( - PathAndRequirement(base::mac::OuterBundlePath(), requirement)); + PathAndRequirement(base::apple::OuterBundlePath(), requirement)); critical_binaries.push_back( - PathAndRequirement(base::mac::FrameworkBundlePath(), requirement)); + PathAndRequirement(base::apple::FrameworkBundlePath(), requirement)); return critical_binaries; }
diff --git a/chrome/browser/safe_browsing/incident_reporting/binary_integrity_analyzer_mac_unittest.cc b/chrome/browser/safe_browsing/incident_reporting/binary_integrity_analyzer_mac_unittest.cc index cac0749d..8dde41f 100644 --- a/chrome/browser/safe_browsing/incident_reporting/binary_integrity_analyzer_mac_unittest.cc +++ b/chrome/browser/safe_browsing/incident_reporting/binary_integrity_analyzer_mac_unittest.cc
@@ -9,10 +9,10 @@ #include <memory> +#include "base/apple/bundle_locations.h" #include "base/files/file.h" #include "base/files/file_util.h" #include "base/files/scoped_temp_dir.h" -#include "base/mac/bundle_locations.h" #include "base/mac/foundation_util.h" #include "base/mac/scoped_cftyperef.h" #include "base/path_service.h" @@ -87,9 +87,9 @@ "certificate leaf[field.1.2.840.113635.100.6.1.13] and " "certificate leaf[subject.OU] = EQHXZ8M8AV"; paths_and_requirements_expected.push_back( - PathAndRequirement(base::mac::OuterBundlePath(), expected_req)); + PathAndRequirement(base::apple::OuterBundlePath(), expected_req)); paths_and_requirements_expected.push_back( - PathAndRequirement(base::mac::FrameworkBundlePath(), expected_req)); + PathAndRequirement(base::apple::FrameworkBundlePath(), expected_req)); std::vector<PathAndRequirement> paths_and_requirements = GetCriticalPathsAndRequirements();
diff --git a/chrome/browser/sharing/sharing_device_registration_unittest.cc b/chrome/browser/sharing/sharing_device_registration_unittest.cc index 9ad376a..e702c4c 100644 --- a/chrome/browser/sharing/sharing_device_registration_unittest.cc +++ b/chrome/browser/sharing/sharing_device_registration_unittest.cc
@@ -256,8 +256,7 @@ TEST_F(SharingDeviceRegistrationTest, RegisterDeviceTest_Success) { test_sync_service_.GetUserSettings()->SetSelectedTypes( /*sync_everything=*/false, - /*types=*/syncer::UserSelectableTypeSet( - syncer::UserSelectableType::kPreferences)); + /*types=*/{syncer::UserSelectableType::kPreferences}); SetInstanceIDFCMResult(instance_id::InstanceID::Result::SUCCESS); SetInstanceIDFCMToken(kVapidFCMToken); fake_device_info_sync_service_.GetDeviceInfoTracker()->Add( @@ -294,7 +293,7 @@ TEST_F(SharingDeviceRegistrationTest, RegisterDeviceTest_Vapid_Only) { // Make sync unavailable to force using vapid. - test_sync_service_.SetFailedDataTypes(syncer::SHARING_MESSAGE); + test_sync_service_.SetFailedDataTypes({syncer::SHARING_MESSAGE}); SetInstanceIDFCMResult(instance_id::InstanceID::Result::SUCCESS); SetInstanceIDFCMToken(kVapidFCMToken); fake_device_info_sync_service_.GetDeviceInfoTracker()->Add( @@ -340,7 +339,7 @@ TEST_F(SharingDeviceRegistrationTest, RegisterDeviceTest_InternalError) { // Make sync unavailable to force using vapid. - test_sync_service_.SetFailedDataTypes(syncer::SHARING_MESSAGE); + test_sync_service_.SetFailedDataTypes({syncer::SHARING_MESSAGE}); test_sync_service_.GetUserSettings()->SetSelectedTypes( /*sync_everything=*/false, /*types=*/syncer::UserSelectableTypeSet());
diff --git a/chrome/browser/sharing/sharing_fcm_sender_unittest.cc b/chrome/browser/sharing/sharing_fcm_sender_unittest.cc index b96a748..1c52e76 100644 --- a/chrome/browser/sharing/sharing_fcm_sender_unittest.cc +++ b/chrome/browser/sharing/sharing_fcm_sender_unittest.cc
@@ -205,7 +205,7 @@ TEST_F(SharingFCMSenderTest, NoFcmRegistration) { // Make sync unavailable to force using vapid. - test_sync_service_.SetFailedDataTypes(syncer::SHARING_MESSAGE); + test_sync_service_.SetFailedDataTypes({syncer::SHARING_MESSAGE}); sync_prefs_.ClearFCMRegistration(); std::unique_ptr<crypto::ECPrivateKey> vapid_key = @@ -239,7 +239,7 @@ TEST_F(SharingFCMSenderTest, NoVapidKey) { // Make sync unavailable to force using vapid. - test_sync_service_.SetFailedDataTypes(syncer::SHARING_MESSAGE); + test_sync_service_.SetFailedDataTypes({syncer::SHARING_MESSAGE}); sync_prefs_.SetFCMRegistration(SharingSyncPreference::FCMRegistration( kAuthorizedEntity, base::Time::Now()));
diff --git a/chrome/browser/sharing/sharing_service_unittest.cc b/chrome/browser/sharing/sharing_service_unittest.cc index 07143cc..7c19746 100644 --- a/chrome/browser/sharing/sharing_service_unittest.cc +++ b/chrome/browser/sharing/sharing_service_unittest.cc
@@ -314,8 +314,7 @@ syncer::SyncService::TransportState::ACTIVE); test_sync_service_.GetUserSettings()->SetSelectedTypes( /*sync_everything=*/false, - /*types=*/syncer::UserSelectableTypeSet( - syncer::UserSelectableType::kPreferences)); + /*types=*/{syncer::UserSelectableType::kPreferences}); EXPECT_EQ(SharingService::State::DISABLED, GetSharingService()->GetStateForTesting()); @@ -355,7 +354,7 @@ test_sync_service_.GetUserSettings()->SetSelectedTypes( /*sync_everything=*/false, /*types=*/syncer::UserSelectableTypeSet()); - test_sync_service_.SetFailedDataTypes(syncer::SHARING_MESSAGE); + test_sync_service_.SetFailedDataTypes({syncer::SHARING_MESSAGE}); EXPECT_EQ(SharingService::State::DISABLED, GetSharingService()->GetStateForTesting()); @@ -390,8 +389,7 @@ syncer::SyncService::TransportState::ACTIVE); test_sync_service_.GetUserSettings()->SetSelectedTypes( /*sync_everything=*/false, - /*types=*/syncer::UserSelectableTypeSet( - syncer::UserSelectableType::kPreferences)); + /*types=*/{syncer::UserSelectableType::kPreferences}); EXPECT_EQ(SharingService::State::DISABLED, GetSharingService()->GetStateForTesting()); @@ -432,8 +430,7 @@ syncer::SyncService::TransportState::ACTIVE); test_sync_service_.GetUserSettings()->SetSelectedTypes( /*sync_everything=*/false, - /*types=*/syncer::UserSelectableTypeSet( - syncer::UserSelectableType::kPreferences)); + /*types=*/{syncer::UserSelectableType::kPreferences}); // Create new SharingService instance with feature enabled at constructor. GetSharingService(); @@ -513,8 +510,7 @@ syncer::SyncService::TransportState::ACTIVE); test_sync_service_.GetUserSettings()->SetSelectedTypes( /*sync_everything=*/false, - /*types=*/syncer::UserSelectableTypeSet( - syncer::UserSelectableType::kPreferences)); + /*types=*/{syncer::UserSelectableType::kPreferences}); // Create new SharingService instance with FCM already registered at // constructor.
diff --git a/chrome/browser/sharing/sharing_utils_unittest.cc b/chrome/browser/sharing/sharing_utils_unittest.cc index b1bfa64..d8d5c825 100644 --- a/chrome/browser/sharing/sharing_utils_unittest.cc +++ b/chrome/browser/sharing/sharing_utils_unittest.cc
@@ -42,8 +42,7 @@ // PREFERENCES is actively synced. test_sync_service_.GetUserSettings()->SetSelectedTypes( /*sync_everything=*/false, - /*types=*/syncer::UserSelectableTypeSet( - syncer::UserSelectableType::kPreferences)); + /*types=*/{syncer::UserSelectableType::kPreferences}); EXPECT_TRUE(IsSyncEnabledForSharing(&test_sync_service_)); EXPECT_FALSE(IsSyncDisabledForSharing(&test_sync_service_)); @@ -89,8 +88,7 @@ syncer::SyncService::TransportState::DISABLED); test_sync_service_.GetUserSettings()->SetSelectedTypes( /*sync_everything=*/false, - /*types=*/syncer::UserSelectableTypeSet( - syncer::UserSelectableType::kPreferences)); + /*types=*/{syncer::UserSelectableType::kPreferences}); EXPECT_FALSE(IsSyncEnabledForSharing(&test_sync_service_)); EXPECT_TRUE(IsSyncDisabledForSharing(&test_sync_service_)); @@ -101,8 +99,7 @@ syncer::SyncService::TransportState::CONFIGURING); test_sync_service_.GetUserSettings()->SetSelectedTypes( /*sync_everything=*/false, - /*types=*/syncer::UserSelectableTypeSet( - syncer::UserSelectableType::kPreferences)); + /*types=*/{syncer::UserSelectableType::kPreferences}); EXPECT_FALSE(IsSyncEnabledForSharing(&test_sync_service_)); EXPECT_FALSE(IsSyncDisabledForSharing(&test_sync_service_));
diff --git a/chrome/browser/shell_integration_mac.mm b/chrome/browser/shell_integration_mac.mm index 0299d27..7bb33b1e 100644 --- a/chrome/browser/shell_integration_mac.mm +++ b/chrome/browser/shell_integration_mac.mm
@@ -7,7 +7,7 @@ #include <AppKit/AppKit.h> #include <UniformTypeIdentifiers/UniformTypeIdentifiers.h> -#include "base/mac/bundle_locations.h" +#include "base/apple/bundle_locations.h" #include "base/mac/foundation_util.h" #include "base/mac/mac_util.h" #include "base/mac/scoped_cftyperef.h" @@ -43,7 +43,7 @@ if (@available(macOS 12, *)) { // We really do want the outer bundle here, not the main bundle since // setting a shortcut to Chrome as the default browser doesn't make sense. - NSURL* app_bundle = base::mac::OuterBundleURL(); + NSURL* app_bundle = base::apple::OuterBundleURL(); if (!app_bundle) { return false; } @@ -67,7 +67,7 @@ // We really do want the outer bundle here, not the main bundle since // setting a shortcut to Chrome as the default browser doesn't make sense. CFStringRef identifier = - base::mac::NSToCFCast(base::mac::OuterBundle().bundleIdentifier); + base::mac::NSToCFCast(base::apple::OuterBundle().bundleIdentifier); if (!identifier) { return false; } @@ -116,7 +116,7 @@ if (@available(macOS 12, *)) { // We really do want the main bundle here since it makes sense to set an // app shortcut as a default scheme handler. - NSURL* app_bundle = base::mac::MainBundleURL(); + NSURL* app_bundle = base::apple::MainBundleURL(); if (!app_bundle) { return false; } @@ -134,7 +134,7 @@ } else { // We really do want the main bundle here since it makes sense to set an // app shortcut as a default scheme handler. - NSString* identifier = base::mac::MainBundle().bundleIdentifier; + NSString* identifier = base::apple::MainBundle().bundleIdentifier; if (!identifier) { return false; } @@ -208,7 +208,7 @@ DefaultWebClientState GetDefaultBrowser() { // We really do want the outer bundle here, since this we want to know the // status of the main Chrome bundle and not a shortcut. - NSString* my_identifier = base::mac::OuterBundle().bundleIdentifier; + NSString* my_identifier = base::apple::OuterBundle().bundleIdentifier; if (!my_identifier) { return UNKNOWN_DEFAULT; } @@ -257,7 +257,7 @@ // We really do want the main bundle here since it makes sense to set an // app shortcut as a default scheme handler. - NSString* my_identifier = base::mac::MainBundle().bundleIdentifier; + NSString* my_identifier = base::apple::MainBundle().bundleIdentifier; if (!my_identifier) { return UNKNOWN_DEFAULT; }
diff --git a/chrome/browser/signin/signin_util_unittest.cc b/chrome/browser/signin/signin_util_unittest.cc index 131af1c..e3c3c5a 100644 --- a/chrome/browser/signin/signin_util_unittest.cc +++ b/chrome/browser/signin/signin_util_unittest.cc
@@ -60,18 +60,18 @@ EXPECT_EQ(signin_util::GetProfileSeparationPolicyState(profile.get(), "primary_account"), ProfileSeparationPolicyStateSet( - ProfileSeparationPolicyState::kEnforcedByInterceptedAccount)); + {ProfileSeparationPolicyState::kEnforcedByInterceptedAccount})); EXPECT_EQ(signin_util::GetProfileSeparationPolicyState( profile.get(), "primary_account_keep_existing_data"), ProfileSeparationPolicyStateSet( - ProfileSeparationPolicyState::kEnforcedByInterceptedAccount, - ProfileSeparationPolicyState::kKeepsBrowsingData)); + {ProfileSeparationPolicyState::kEnforcedByInterceptedAccount, + ProfileSeparationPolicyState::kKeepsBrowsingData})); EXPECT_EQ(signin_util::GetProfileSeparationPolicyState( profile.get(), "primary_account_strict_keep_existing_data"), ProfileSeparationPolicyStateSet( - ProfileSeparationPolicyState::kEnforcedByInterceptedAccount, - ProfileSeparationPolicyState::kStrict, - ProfileSeparationPolicyState::kKeepsBrowsingData)); + {ProfileSeparationPolicyState::kEnforcedByInterceptedAccount, + ProfileSeparationPolicyState::kStrict, + ProfileSeparationPolicyState::kKeepsBrowsingData})); // Active profile has "none" as a user level policy. profile->GetPrefs()->SetString(prefs::kManagedAccountsSigninRestriction, @@ -86,23 +86,23 @@ EXPECT_EQ(signin_util::GetProfileSeparationPolicyState(profile.get(), "primary_account"), ProfileSeparationPolicyStateSet( - ProfileSeparationPolicyState::kEnforcedByInterceptedAccount)); + {ProfileSeparationPolicyState::kEnforcedByInterceptedAccount})); EXPECT_EQ(signin_util::GetProfileSeparationPolicyState( profile.get(), "primary_account_strict"), ProfileSeparationPolicyStateSet( - ProfileSeparationPolicyState::kStrict, - ProfileSeparationPolicyState::kEnforcedByInterceptedAccount)); + {ProfileSeparationPolicyState::kStrict, + ProfileSeparationPolicyState::kEnforcedByInterceptedAccount})); EXPECT_EQ(signin_util::GetProfileSeparationPolicyState( profile.get(), "primary_account_keep_existing_data"), ProfileSeparationPolicyStateSet( - ProfileSeparationPolicyState::kEnforcedByInterceptedAccount, - ProfileSeparationPolicyState::kKeepsBrowsingData)); + {ProfileSeparationPolicyState::kEnforcedByInterceptedAccount, + ProfileSeparationPolicyState::kKeepsBrowsingData})); EXPECT_EQ(signin_util::GetProfileSeparationPolicyState( profile.get(), "primary_account_strict_keep_existing_data"), ProfileSeparationPolicyStateSet( - ProfileSeparationPolicyState::kEnforcedByInterceptedAccount, - ProfileSeparationPolicyState::kKeepsBrowsingData, - ProfileSeparationPolicyState::kStrict)); + {ProfileSeparationPolicyState::kEnforcedByInterceptedAccount, + ProfileSeparationPolicyState::kKeepsBrowsingData, + ProfileSeparationPolicyState::kStrict})); // Active profile has "none" as a machine level policy. profile->GetPrefs()->SetString(prefs::kManagedAccountsSigninRestriction, @@ -117,23 +117,23 @@ EXPECT_EQ(signin_util::GetProfileSeparationPolicyState(profile.get(), "primary_account"), ProfileSeparationPolicyStateSet( - ProfileSeparationPolicyState::kEnforcedByInterceptedAccount)); + {ProfileSeparationPolicyState::kEnforcedByInterceptedAccount})); EXPECT_EQ(signin_util::GetProfileSeparationPolicyState( profile.get(), "primary_account_strict"), ProfileSeparationPolicyStateSet( - ProfileSeparationPolicyState::kStrict, - ProfileSeparationPolicyState::kEnforcedByInterceptedAccount)); + {ProfileSeparationPolicyState::kStrict, + ProfileSeparationPolicyState::kEnforcedByInterceptedAccount})); EXPECT_EQ(signin_util::GetProfileSeparationPolicyState( profile.get(), "primary_account_keep_existing_data"), ProfileSeparationPolicyStateSet( - ProfileSeparationPolicyState::kEnforcedByInterceptedAccount, - ProfileSeparationPolicyState::kKeepsBrowsingData)); + {ProfileSeparationPolicyState::kEnforcedByInterceptedAccount, + ProfileSeparationPolicyState::kKeepsBrowsingData})); EXPECT_EQ(signin_util::GetProfileSeparationPolicyState( profile.get(), "primary_account_strict_keep_existing_data"), ProfileSeparationPolicyStateSet( - ProfileSeparationPolicyState::kEnforcedByInterceptedAccount, - ProfileSeparationPolicyState::kKeepsBrowsingData, - ProfileSeparationPolicyState::kStrict)); + {ProfileSeparationPolicyState::kEnforcedByInterceptedAccount, + ProfileSeparationPolicyState::kKeepsBrowsingData, + ProfileSeparationPolicyState::kStrict})); // Active profile has "primary_account" as a user level policy. profile->GetPrefs()->SetString(prefs::kManagedAccountsSigninRestriction, @@ -142,32 +142,32 @@ prefs::kManagedAccountsSigninRestrictionScopeMachine, false); EXPECT_EQ(signin_util::GetProfileSeparationPolicyState(profile.get()), ProfileSeparationPolicyStateSet( - ProfileSeparationPolicyState::kEnforcedByExistingProfile)); + {ProfileSeparationPolicyState::kEnforcedByExistingProfile})); EXPECT_EQ(signin_util::GetProfileSeparationPolicyState(profile.get(), "none"), ProfileSeparationPolicyStateSet( - ProfileSeparationPolicyState::kEnforcedByExistingProfile)); + {ProfileSeparationPolicyState::kEnforcedByExistingProfile})); EXPECT_EQ(signin_util::GetProfileSeparationPolicyState(profile.get(), "primary_account"), ProfileSeparationPolicyStateSet( - ProfileSeparationPolicyState::kEnforcedByExistingProfile, - ProfileSeparationPolicyState::kEnforcedByInterceptedAccount)); + {ProfileSeparationPolicyState::kEnforcedByExistingProfile, + ProfileSeparationPolicyState::kEnforcedByInterceptedAccount})); EXPECT_EQ(signin_util::GetProfileSeparationPolicyState( profile.get(), "primary_account_strict"), ProfileSeparationPolicyStateSet( - ProfileSeparationPolicyState::kEnforcedByExistingProfile, - ProfileSeparationPolicyState::kStrict, - ProfileSeparationPolicyState::kEnforcedByInterceptedAccount)); + {ProfileSeparationPolicyState::kEnforcedByExistingProfile, + ProfileSeparationPolicyState::kStrict, + ProfileSeparationPolicyState::kEnforcedByInterceptedAccount})); EXPECT_EQ(signin_util::GetProfileSeparationPolicyState( profile.get(), "primary_account_keep_existing_data"), ProfileSeparationPolicyStateSet( - ProfileSeparationPolicyState::kEnforcedByExistingProfile, - ProfileSeparationPolicyState::kEnforcedByInterceptedAccount)); + {ProfileSeparationPolicyState::kEnforcedByExistingProfile, + ProfileSeparationPolicyState::kEnforcedByInterceptedAccount})); EXPECT_EQ(signin_util::GetProfileSeparationPolicyState( profile.get(), "primary_account_strict_keep_existing_data"), ProfileSeparationPolicyStateSet( - ProfileSeparationPolicyState::kEnforcedByExistingProfile, - ProfileSeparationPolicyState::kEnforcedByInterceptedAccount, - ProfileSeparationPolicyState::kStrict)); + {ProfileSeparationPolicyState::kEnforcedByExistingProfile, + ProfileSeparationPolicyState::kEnforcedByInterceptedAccount, + ProfileSeparationPolicyState::kStrict})); // Active profile has "primary_account_strict" as a user level // policy. @@ -177,36 +177,36 @@ prefs::kManagedAccountsSigninRestrictionScopeMachine, false); EXPECT_EQ(signin_util::GetProfileSeparationPolicyState(profile.get()), ProfileSeparationPolicyStateSet( - ProfileSeparationPolicyState::kEnforcedByExistingProfile, - ProfileSeparationPolicyState::kStrict)); + {ProfileSeparationPolicyState::kEnforcedByExistingProfile, + ProfileSeparationPolicyState::kStrict})); EXPECT_EQ(signin_util::GetProfileSeparationPolicyState(profile.get(), "none"), ProfileSeparationPolicyStateSet( - ProfileSeparationPolicyState::kEnforcedByExistingProfile, - ProfileSeparationPolicyState::kStrict)); + {ProfileSeparationPolicyState::kEnforcedByExistingProfile, + ProfileSeparationPolicyState::kStrict})); EXPECT_EQ(signin_util::GetProfileSeparationPolicyState(profile.get(), "primary_account"), ProfileSeparationPolicyStateSet( - ProfileSeparationPolicyState::kEnforcedByExistingProfile, - ProfileSeparationPolicyState::kEnforcedByInterceptedAccount, - ProfileSeparationPolicyState::kStrict)); + {ProfileSeparationPolicyState::kEnforcedByExistingProfile, + ProfileSeparationPolicyState::kEnforcedByInterceptedAccount, + ProfileSeparationPolicyState::kStrict})); EXPECT_EQ(signin_util::GetProfileSeparationPolicyState( profile.get(), "primary_account_strict"), ProfileSeparationPolicyStateSet( - ProfileSeparationPolicyState::kEnforcedByExistingProfile, - ProfileSeparationPolicyState::kEnforcedByInterceptedAccount, - ProfileSeparationPolicyState::kStrict)); + {ProfileSeparationPolicyState::kEnforcedByExistingProfile, + ProfileSeparationPolicyState::kEnforcedByInterceptedAccount, + ProfileSeparationPolicyState::kStrict})); EXPECT_EQ(signin_util::GetProfileSeparationPolicyState( profile.get(), "primary_account_keep_existing_data"), ProfileSeparationPolicyStateSet( - ProfileSeparationPolicyState::kEnforcedByExistingProfile, - ProfileSeparationPolicyState::kEnforcedByInterceptedAccount, - ProfileSeparationPolicyState::kStrict)); + {ProfileSeparationPolicyState::kEnforcedByExistingProfile, + ProfileSeparationPolicyState::kEnforcedByInterceptedAccount, + ProfileSeparationPolicyState::kStrict})); EXPECT_EQ(signin_util::GetProfileSeparationPolicyState( profile.get(), "primary_account_strict_keep_existing_data"), ProfileSeparationPolicyStateSet( - ProfileSeparationPolicyState::kEnforcedByExistingProfile, - ProfileSeparationPolicyState::kEnforcedByInterceptedAccount, - ProfileSeparationPolicyState::kStrict)); + {ProfileSeparationPolicyState::kEnforcedByExistingProfile, + ProfileSeparationPolicyState::kEnforcedByInterceptedAccount, + ProfileSeparationPolicyState::kStrict})); // Active profile has "primary_account" as a machine level policy. profile->GetPrefs()->SetString(prefs::kManagedAccountsSigninRestriction, @@ -215,38 +215,38 @@ prefs::kManagedAccountsSigninRestrictionScopeMachine, true); EXPECT_EQ(signin_util::GetProfileSeparationPolicyState(profile.get()), ProfileSeparationPolicyStateSet( - ProfileSeparationPolicyState::kEnforcedByExistingProfile, - ProfileSeparationPolicyState::kEnforcedOnMachineLevel)); + {ProfileSeparationPolicyState::kEnforcedByExistingProfile, + ProfileSeparationPolicyState::kEnforcedOnMachineLevel})); EXPECT_EQ(signin_util::GetProfileSeparationPolicyState(profile.get(), "none"), ProfileSeparationPolicyStateSet( - ProfileSeparationPolicyState::kEnforcedByExistingProfile, - ProfileSeparationPolicyState::kEnforcedOnMachineLevel)); + {ProfileSeparationPolicyState::kEnforcedByExistingProfile, + ProfileSeparationPolicyState::kEnforcedOnMachineLevel})); EXPECT_EQ(signin_util::GetProfileSeparationPolicyState(profile.get(), "primary_account"), ProfileSeparationPolicyStateSet( - ProfileSeparationPolicyState::kEnforcedByExistingProfile, - ProfileSeparationPolicyState::kEnforcedOnMachineLevel, - ProfileSeparationPolicyState::kEnforcedByInterceptedAccount)); + {ProfileSeparationPolicyState::kEnforcedByExistingProfile, + ProfileSeparationPolicyState::kEnforcedOnMachineLevel, + ProfileSeparationPolicyState::kEnforcedByInterceptedAccount})); EXPECT_EQ(signin_util::GetProfileSeparationPolicyState( profile.get(), "primary_account_strict"), ProfileSeparationPolicyStateSet( - ProfileSeparationPolicyState::kEnforcedByExistingProfile, - ProfileSeparationPolicyState::kEnforcedOnMachineLevel, - ProfileSeparationPolicyState::kStrict, - ProfileSeparationPolicyState::kEnforcedByInterceptedAccount)); + {ProfileSeparationPolicyState::kEnforcedByExistingProfile, + ProfileSeparationPolicyState::kEnforcedOnMachineLevel, + ProfileSeparationPolicyState::kStrict, + ProfileSeparationPolicyState::kEnforcedByInterceptedAccount})); EXPECT_EQ(signin_util::GetProfileSeparationPolicyState( profile.get(), "primary_account_keep_existing_data"), ProfileSeparationPolicyStateSet( - ProfileSeparationPolicyState::kEnforcedByExistingProfile, - ProfileSeparationPolicyState::kEnforcedOnMachineLevel, - ProfileSeparationPolicyState::kEnforcedByInterceptedAccount)); + {ProfileSeparationPolicyState::kEnforcedByExistingProfile, + ProfileSeparationPolicyState::kEnforcedOnMachineLevel, + ProfileSeparationPolicyState::kEnforcedByInterceptedAccount})); EXPECT_EQ(signin_util::GetProfileSeparationPolicyState( profile.get(), "primary_account_strict_keep_existing_data"), ProfileSeparationPolicyStateSet( - ProfileSeparationPolicyState::kEnforcedByExistingProfile, - ProfileSeparationPolicyState::kEnforcedOnMachineLevel, - ProfileSeparationPolicyState::kEnforcedByInterceptedAccount, - ProfileSeparationPolicyState::kStrict)); + {ProfileSeparationPolicyState::kEnforcedByExistingProfile, + ProfileSeparationPolicyState::kEnforcedOnMachineLevel, + ProfileSeparationPolicyState::kEnforcedByInterceptedAccount, + ProfileSeparationPolicyState::kStrict})); // Active profile has "primary_account_keep_existing_data" as a // machine level policy. @@ -256,42 +256,42 @@ prefs::kManagedAccountsSigninRestrictionScopeMachine, true); EXPECT_EQ(signin_util::GetProfileSeparationPolicyState(profile.get()), ProfileSeparationPolicyStateSet( - ProfileSeparationPolicyState::kEnforcedByExistingProfile, - ProfileSeparationPolicyState::kEnforcedOnMachineLevel, - ProfileSeparationPolicyState::kKeepsBrowsingData)); + {ProfileSeparationPolicyState::kEnforcedByExistingProfile, + ProfileSeparationPolicyState::kEnforcedOnMachineLevel, + ProfileSeparationPolicyState::kKeepsBrowsingData})); EXPECT_EQ(signin_util::GetProfileSeparationPolicyState(profile.get(), "none"), ProfileSeparationPolicyStateSet( - ProfileSeparationPolicyState::kEnforcedByExistingProfile, - ProfileSeparationPolicyState::kEnforcedOnMachineLevel, - ProfileSeparationPolicyState::kKeepsBrowsingData)); + {ProfileSeparationPolicyState::kEnforcedByExistingProfile, + ProfileSeparationPolicyState::kEnforcedOnMachineLevel, + ProfileSeparationPolicyState::kKeepsBrowsingData})); EXPECT_EQ(signin_util::GetProfileSeparationPolicyState(profile.get(), "primary_account"), ProfileSeparationPolicyStateSet( - ProfileSeparationPolicyState::kEnforcedByExistingProfile, - ProfileSeparationPolicyState::kEnforcedOnMachineLevel, - ProfileSeparationPolicyState::kEnforcedByInterceptedAccount)); + {ProfileSeparationPolicyState::kEnforcedByExistingProfile, + ProfileSeparationPolicyState::kEnforcedOnMachineLevel, + ProfileSeparationPolicyState::kEnforcedByInterceptedAccount})); EXPECT_EQ(signin_util::GetProfileSeparationPolicyState( profile.get(), "primary_account_strict"), ProfileSeparationPolicyStateSet( - ProfileSeparationPolicyState::kEnforcedByExistingProfile, - ProfileSeparationPolicyState::kEnforcedOnMachineLevel, - ProfileSeparationPolicyState::kStrict, - ProfileSeparationPolicyState::kEnforcedByInterceptedAccount)); + {ProfileSeparationPolicyState::kEnforcedByExistingProfile, + ProfileSeparationPolicyState::kEnforcedOnMachineLevel, + ProfileSeparationPolicyState::kStrict, + ProfileSeparationPolicyState::kEnforcedByInterceptedAccount})); EXPECT_EQ(signin_util::GetProfileSeparationPolicyState( profile.get(), "primary_account_keep_existing_data"), ProfileSeparationPolicyStateSet( - ProfileSeparationPolicyState::kEnforcedByExistingProfile, - ProfileSeparationPolicyState::kEnforcedOnMachineLevel, - ProfileSeparationPolicyState::kEnforcedByInterceptedAccount, - ProfileSeparationPolicyState::kKeepsBrowsingData)); + {ProfileSeparationPolicyState::kEnforcedByExistingProfile, + ProfileSeparationPolicyState::kEnforcedOnMachineLevel, + ProfileSeparationPolicyState::kEnforcedByInterceptedAccount, + ProfileSeparationPolicyState::kKeepsBrowsingData})); EXPECT_EQ(signin_util::GetProfileSeparationPolicyState( profile.get(), "primary_account_strict_keep_existing_data"), ProfileSeparationPolicyStateSet( - ProfileSeparationPolicyState::kEnforcedByExistingProfile, - ProfileSeparationPolicyState::kEnforcedOnMachineLevel, - ProfileSeparationPolicyState::kEnforcedByInterceptedAccount, - ProfileSeparationPolicyState::kStrict, - ProfileSeparationPolicyState::kKeepsBrowsingData)); + {ProfileSeparationPolicyState::kEnforcedByExistingProfile, + ProfileSeparationPolicyState::kEnforcedOnMachineLevel, + ProfileSeparationPolicyState::kEnforcedByInterceptedAccount, + ProfileSeparationPolicyState::kStrict, + ProfileSeparationPolicyState::kKeepsBrowsingData})); // Active profile has "primary_account_strict" as a machine level // policy. @@ -301,42 +301,42 @@ prefs::kManagedAccountsSigninRestrictionScopeMachine, true); EXPECT_EQ(signin_util::GetProfileSeparationPolicyState(profile.get()), ProfileSeparationPolicyStateSet( - ProfileSeparationPolicyState::kEnforcedByExistingProfile, - ProfileSeparationPolicyState::kEnforcedOnMachineLevel, - ProfileSeparationPolicyState::kStrict)); + {ProfileSeparationPolicyState::kEnforcedByExistingProfile, + ProfileSeparationPolicyState::kEnforcedOnMachineLevel, + ProfileSeparationPolicyState::kStrict})); EXPECT_EQ(signin_util::GetProfileSeparationPolicyState(profile.get(), "none"), ProfileSeparationPolicyStateSet( - ProfileSeparationPolicyState::kEnforcedByExistingProfile, - ProfileSeparationPolicyState::kEnforcedOnMachineLevel, - ProfileSeparationPolicyState::kStrict)); + {ProfileSeparationPolicyState::kEnforcedByExistingProfile, + ProfileSeparationPolicyState::kEnforcedOnMachineLevel, + ProfileSeparationPolicyState::kStrict})); EXPECT_EQ(signin_util::GetProfileSeparationPolicyState(profile.get(), "primary_account"), ProfileSeparationPolicyStateSet( - ProfileSeparationPolicyState::kEnforcedByExistingProfile, - ProfileSeparationPolicyState::kEnforcedOnMachineLevel, - ProfileSeparationPolicyState::kStrict, - ProfileSeparationPolicyState::kEnforcedByInterceptedAccount)); + {ProfileSeparationPolicyState::kEnforcedByExistingProfile, + ProfileSeparationPolicyState::kEnforcedOnMachineLevel, + ProfileSeparationPolicyState::kStrict, + ProfileSeparationPolicyState::kEnforcedByInterceptedAccount})); EXPECT_EQ(signin_util::GetProfileSeparationPolicyState( profile.get(), "primary_account_strict"), ProfileSeparationPolicyStateSet( - ProfileSeparationPolicyState::kEnforcedByExistingProfile, - ProfileSeparationPolicyState::kEnforcedOnMachineLevel, - ProfileSeparationPolicyState::kStrict, - ProfileSeparationPolicyState::kEnforcedByInterceptedAccount)); + {ProfileSeparationPolicyState::kEnforcedByExistingProfile, + ProfileSeparationPolicyState::kEnforcedOnMachineLevel, + ProfileSeparationPolicyState::kStrict, + ProfileSeparationPolicyState::kEnforcedByInterceptedAccount})); EXPECT_EQ(signin_util::GetProfileSeparationPolicyState( profile.get(), "primary_account_keep_existing_data"), ProfileSeparationPolicyStateSet( - ProfileSeparationPolicyState::kEnforcedByExistingProfile, - ProfileSeparationPolicyState::kEnforcedOnMachineLevel, - ProfileSeparationPolicyState::kStrict, - ProfileSeparationPolicyState::kEnforcedByInterceptedAccount)); + {ProfileSeparationPolicyState::kEnforcedByExistingProfile, + ProfileSeparationPolicyState::kEnforcedOnMachineLevel, + ProfileSeparationPolicyState::kStrict, + ProfileSeparationPolicyState::kEnforcedByInterceptedAccount})); EXPECT_EQ(signin_util::GetProfileSeparationPolicyState( profile.get(), "primary_account_strict_keep_existing_data"), ProfileSeparationPolicyStateSet( - ProfileSeparationPolicyState::kEnforcedByExistingProfile, - ProfileSeparationPolicyState::kEnforcedOnMachineLevel, - ProfileSeparationPolicyState::kEnforcedByInterceptedAccount, - ProfileSeparationPolicyState::kStrict)); + {ProfileSeparationPolicyState::kEnforcedByExistingProfile, + ProfileSeparationPolicyState::kEnforcedOnMachineLevel, + ProfileSeparationPolicyState::kEnforcedByInterceptedAccount, + ProfileSeparationPolicyState::kStrict})); // Active profile has "primary_account_strict_keep_existing_data" // as a machine level policy. @@ -346,46 +346,46 @@ prefs::kManagedAccountsSigninRestrictionScopeMachine, true); EXPECT_EQ(signin_util::GetProfileSeparationPolicyState(profile.get()), ProfileSeparationPolicyStateSet( - ProfileSeparationPolicyState::kEnforcedByExistingProfile, - ProfileSeparationPolicyState::kEnforcedOnMachineLevel, - ProfileSeparationPolicyState::kStrict, - ProfileSeparationPolicyState::kKeepsBrowsingData)); + {ProfileSeparationPolicyState::kEnforcedByExistingProfile, + ProfileSeparationPolicyState::kEnforcedOnMachineLevel, + ProfileSeparationPolicyState::kStrict, + ProfileSeparationPolicyState::kKeepsBrowsingData})); EXPECT_EQ(signin_util::GetProfileSeparationPolicyState(profile.get(), "none"), ProfileSeparationPolicyStateSet( - ProfileSeparationPolicyState::kEnforcedByExistingProfile, - ProfileSeparationPolicyState::kEnforcedOnMachineLevel, - ProfileSeparationPolicyState::kStrict, - ProfileSeparationPolicyState::kKeepsBrowsingData)); + {ProfileSeparationPolicyState::kEnforcedByExistingProfile, + ProfileSeparationPolicyState::kEnforcedOnMachineLevel, + ProfileSeparationPolicyState::kStrict, + ProfileSeparationPolicyState::kKeepsBrowsingData})); EXPECT_EQ(signin_util::GetProfileSeparationPolicyState(profile.get(), "primary_account"), ProfileSeparationPolicyStateSet( - ProfileSeparationPolicyState::kEnforcedByExistingProfile, - ProfileSeparationPolicyState::kEnforcedOnMachineLevel, - ProfileSeparationPolicyState::kStrict, - ProfileSeparationPolicyState::kEnforcedByInterceptedAccount)); + {ProfileSeparationPolicyState::kEnforcedByExistingProfile, + ProfileSeparationPolicyState::kEnforcedOnMachineLevel, + ProfileSeparationPolicyState::kStrict, + ProfileSeparationPolicyState::kEnforcedByInterceptedAccount})); EXPECT_EQ(signin_util::GetProfileSeparationPolicyState( profile.get(), "primary_account_strict"), ProfileSeparationPolicyStateSet( - ProfileSeparationPolicyState::kEnforcedByExistingProfile, - ProfileSeparationPolicyState::kEnforcedOnMachineLevel, - ProfileSeparationPolicyState::kStrict, - ProfileSeparationPolicyState::kEnforcedByInterceptedAccount)); + {ProfileSeparationPolicyState::kEnforcedByExistingProfile, + ProfileSeparationPolicyState::kEnforcedOnMachineLevel, + ProfileSeparationPolicyState::kStrict, + ProfileSeparationPolicyState::kEnforcedByInterceptedAccount})); EXPECT_EQ(signin_util::GetProfileSeparationPolicyState( profile.get(), "primary_account_keep_existing_data"), ProfileSeparationPolicyStateSet( - ProfileSeparationPolicyState::kEnforcedByExistingProfile, - ProfileSeparationPolicyState::kEnforcedOnMachineLevel, - ProfileSeparationPolicyState::kStrict, - ProfileSeparationPolicyState::kEnforcedByInterceptedAccount, - ProfileSeparationPolicyState::kKeepsBrowsingData)); + {ProfileSeparationPolicyState::kEnforcedByExistingProfile, + ProfileSeparationPolicyState::kEnforcedOnMachineLevel, + ProfileSeparationPolicyState::kStrict, + ProfileSeparationPolicyState::kEnforcedByInterceptedAccount, + ProfileSeparationPolicyState::kKeepsBrowsingData})); EXPECT_EQ(signin_util::GetProfileSeparationPolicyState( profile.get(), "primary_account_strict_keep_existing_data"), ProfileSeparationPolicyStateSet( - ProfileSeparationPolicyState::kEnforcedByExistingProfile, - ProfileSeparationPolicyState::kEnforcedOnMachineLevel, - ProfileSeparationPolicyState::kEnforcedByInterceptedAccount, - ProfileSeparationPolicyState::kStrict, - ProfileSeparationPolicyState::kKeepsBrowsingData)); + {ProfileSeparationPolicyState::kEnforcedByExistingProfile, + ProfileSeparationPolicyState::kEnforcedOnMachineLevel, + ProfileSeparationPolicyState::kEnforcedByInterceptedAccount, + ProfileSeparationPolicyState::kStrict, + ProfileSeparationPolicyState::kKeepsBrowsingData})); } TEST_F(SigninUtilTest, ProfileSeparationEnforcedByPolicy) {
diff --git a/chrome/browser/sync/sync_startup_tracker_unittest.cc b/chrome/browser/sync/sync_startup_tracker_unittest.cc index 3208e71b..3c463e7 100644 --- a/chrome/browser/sync/sync_startup_tracker_unittest.cc +++ b/chrome/browser/sync/sync_startup_tracker_unittest.cc
@@ -45,7 +45,7 @@ // Make sure that we get a SyncStartupFailed() callback if sync is not logged // in. sync_service_.SetDisableReasons( - syncer::SyncService::DISABLE_REASON_NOT_SIGNED_IN); + {syncer::SyncService::DISABLE_REASON_NOT_SIGNED_IN}); sync_service_.SetTransportState( syncer::SyncService::TransportState::DISABLED); EXPECT_CALL(callback_, Run(SyncStartupTracker::ServiceStartupState::kError)); @@ -99,7 +99,7 @@ // Now, mark the Sync Service as having an unrecoverable error. sync_service_.SetDisableReasons( - syncer::SyncService::DISABLE_REASON_UNRECOVERABLE_ERROR); + {syncer::SyncService::DISABLE_REASON_UNRECOVERABLE_ERROR}); sync_service_.SetTransportState( syncer::SyncService::TransportState::DISABLED); EXPECT_CALL(callback_, Run(SyncStartupTracker::ServiceStartupState::kError));
diff --git a/chrome/browser/sync/sync_ui_util_unittest.cc b/chrome/browser/sync/sync_ui_util_unittest.cc index f7199155..59c6862 100644 --- a/chrome/browser/sync/sync_ui_util_unittest.cc +++ b/chrome/browser/sync/sync_ui_util_unittest.cc
@@ -90,7 +90,7 @@ service->SetFirstSetupComplete(false); service->SetSetupInProgress(false); service->SetDisableReasons( - syncer::SyncService::DISABLE_REASON_UNRECOVERABLE_ERROR); + {syncer::SyncService::DISABLE_REASON_UNRECOVERABLE_ERROR}); service->SetDetailedSyncStatus(false, syncer::SyncStatus()); return { SyncStatusMessageType::kSyncError, @@ -187,7 +187,7 @@ } case STATUS_CASE_SYNC_DISABLED_BY_POLICY: { service->SetDisableReasons( - syncer::SyncService::DISABLE_REASON_ENTERPRISE_POLICY); + {syncer::SyncService::DISABLE_REASON_ENTERPRISE_POLICY}); service->SetFirstSetupComplete(false); service->SetTransportState(syncer::SyncService::TransportState::DISABLED); service->SetPassphraseRequired(false); @@ -202,7 +202,7 @@ // DISABLE_REASON_USER_CHOICE can only occur if Sync was reset from the // dashboard, and the UI treats it as such. service->SetDisableReasons( - syncer::SyncService::DISABLE_REASON_USER_CHOICE); + {syncer::SyncService::DISABLE_REASON_USER_CHOICE}); service->SetSyncFeatureDisabledViaDashboard(true); service->SetFirstSetupComplete(true); service->SetTransportState(syncer::SyncService::TransportState::ACTIVE); @@ -254,7 +254,7 @@ environment.SetPrimaryAccount(kTestUser, signin::ConsentLevel::kSync); service.SetFirstSetupComplete(true); service.SetDisableReasons( - syncer::SyncService::DISABLE_REASON_UNRECOVERABLE_ERROR); + {syncer::SyncService::DISABLE_REASON_UNRECOVERABLE_ERROR}); // First time action is not set. We should get unrecoverable error. service.SetDetailedSyncStatus(true, syncer::SyncStatus()); @@ -295,7 +295,7 @@ environment.SetPrimaryAccount(kTestUser, signin::ConsentLevel::kSync); service.SetFirstSetupComplete(true); service.SetDisableReasons( - syncer::SyncService::DISABLE_REASON_UNRECOVERABLE_ERROR); + {syncer::SyncService::DISABLE_REASON_UNRECOVERABLE_ERROR}); // Set action to SyncStatusActionType::kUpgradeClient. syncer::SyncStatus status;
diff --git a/chrome/browser/sync/test/integration/ash_lacros_sync_test.cc b/chrome/browser/sync/test/integration/ash_lacros_sync_test.cc index 15ad1cf2..e92cc8c 100644 --- a/chrome/browser/sync/test/integration/ash_lacros_sync_test.cc +++ b/chrome/browser/sync/test/integration/ash_lacros_sync_test.cc
@@ -61,15 +61,15 @@ // WifiConfigurations which are part of the selectable *OS* types. EXPECT_EQ( user_settings->GetRegisteredSelectableTypes(), - syncer::UserSelectableTypeSet(syncer::UserSelectableType::kBookmarks, - syncer::UserSelectableType::kPreferences, - syncer::UserSelectableType::kPasswords, - syncer::UserSelectableType::kAutofill, - syncer::UserSelectableType::kThemes, - syncer::UserSelectableType::kHistory, - syncer::UserSelectableType::kExtensions, - syncer::UserSelectableType::kReadingList, - syncer::UserSelectableType::kTabs)) + syncer::UserSelectableTypeSet({syncer::UserSelectableType::kBookmarks, + syncer::UserSelectableType::kPreferences, + syncer::UserSelectableType::kPasswords, + syncer::UserSelectableType::kAutofill, + syncer::UserSelectableType::kThemes, + syncer::UserSelectableType::kHistory, + syncer::UserSelectableType::kExtensions, + syncer::UserSelectableType::kReadingList, + syncer::UserSelectableType::kTabs})) << "Actual: " << syncer::UserSelectableTypeSetToString( user_settings->GetRegisteredSelectableTypes()); @@ -77,27 +77,48 @@ // All the OS types should be selectable in Ash too. EXPECT_EQ(user_settings->GetRegisteredSelectableOsTypes(), syncer::UserSelectableOsTypeSet( - syncer::UserSelectableOsType::kOsApps, - syncer::UserSelectableOsType::kOsPreferences, - syncer::UserSelectableOsType::kOsWifiConfigurations)) + {syncer::UserSelectableOsType::kOsApps, + syncer::UserSelectableOsType::kOsPreferences, + syncer::UserSelectableOsType::kOsWifiConfigurations})) << "Actual: " << syncer::UserSelectableOsTypeSetToString( user_settings->GetRegisteredSelectableOsTypes()); - syncer::ModelTypeSet expected_active_types( - syncer::BOOKMARKS, syncer::PREFERENCES, syncer::PASSWORDS, - syncer::AUTOFILL_PROFILE, syncer::AUTOFILL, syncer::AUTOFILL_WALLET_DATA, - syncer::AUTOFILL_WALLET_METADATA, syncer::AUTOFILL_WALLET_OFFER, - syncer::THEMES, syncer::EXTENSIONS, syncer::SEARCH_ENGINES, - syncer::SESSIONS, syncer::APPS, syncer::APP_SETTINGS, - syncer::EXTENSION_SETTINGS, syncer::HISTORY_DELETE_DIRECTIVES, - syncer::DICTIONARY, syncer::DEVICE_INFO, syncer::PRIORITY_PREFERENCES, - syncer::APP_LIST, syncer::ARC_PACKAGE, syncer::PRINTERS, - syncer::READING_LIST, syncer::USER_EVENTS, syncer::USER_CONSENTS, - syncer::SEND_TAB_TO_SELF, syncer::SECURITY_EVENTS, - syncer::WIFI_CONFIGURATIONS, syncer::OS_PREFERENCES, - syncer::OS_PRIORITY_PREFERENCES, syncer::SHARING_MESSAGE, - syncer::WORKSPACE_DESK, syncer::PROXY_TABS, syncer::NIGORI); + syncer::ModelTypeSet expected_active_types = { + syncer::BOOKMARKS, + syncer::PREFERENCES, + syncer::PASSWORDS, + syncer::AUTOFILL_PROFILE, + syncer::AUTOFILL, + syncer::AUTOFILL_WALLET_DATA, + syncer::AUTOFILL_WALLET_METADATA, + syncer::AUTOFILL_WALLET_OFFER, + syncer::THEMES, + syncer::EXTENSIONS, + syncer::SEARCH_ENGINES, + syncer::SESSIONS, + syncer::APPS, + syncer::APP_SETTINGS, + syncer::EXTENSION_SETTINGS, + syncer::HISTORY_DELETE_DIRECTIVES, + syncer::DICTIONARY, + syncer::DEVICE_INFO, + syncer::PRIORITY_PREFERENCES, + syncer::APP_LIST, + syncer::ARC_PACKAGE, + syncer::PRINTERS, + syncer::READING_LIST, + syncer::USER_EVENTS, + syncer::USER_CONSENTS, + syncer::SEND_TAB_TO_SELF, + syncer::SECURITY_EVENTS, + syncer::WIFI_CONFIGURATIONS, + syncer::OS_PREFERENCES, + syncer::OS_PRIORITY_PREFERENCES, + syncer::SHARING_MESSAGE, + syncer::WORKSPACE_DESK, + syncer::PROXY_TABS, + syncer::NIGORI}; if (base::FeatureList::IsEnabled(syncer::kSyncEnableHistoryDataType)) { expected_active_types.Put(syncer::HISTORY); } else { @@ -130,9 +151,9 @@ // But all the OS types should be selectable. EXPECT_EQ(user_settings->GetRegisteredSelectableOsTypes(), syncer::UserSelectableOsTypeSet( - syncer::UserSelectableOsType::kOsApps, - syncer::UserSelectableOsType::kOsPreferences, - syncer::UserSelectableOsType::kOsWifiConfigurations)) + {syncer::UserSelectableOsType::kOsApps, + syncer::UserSelectableOsType::kOsPreferences, + syncer::UserSelectableOsType::kOsWifiConfigurations})) << "Actual: " << syncer::UserSelectableOsTypeSetToString( user_settings->GetRegisteredSelectableOsTypes()); @@ -141,10 +162,10 @@ EXPECT_EQ( sync_service->GetActiveDataTypes(), syncer::ModelTypeSet( - syncer::DEVICE_INFO, syncer::APP_LIST, syncer::ARC_PACKAGE, - syncer::PRINTERS, syncer::USER_CONSENTS, syncer::WIFI_CONFIGURATIONS, - syncer::OS_PREFERENCES, syncer::OS_PRIORITY_PREFERENCES, - syncer::WORKSPACE_DESK, syncer::NIGORI)); + {syncer::DEVICE_INFO, syncer::APP_LIST, syncer::ARC_PACKAGE, + syncer::PRINTERS, syncer::USER_CONSENTS, syncer::WIFI_CONFIGURATIONS, + syncer::OS_PREFERENCES, syncer::OS_PRIORITY_PREFERENCES, + syncer::WORKSPACE_DESK, syncer::NIGORI})); } } // namespace
diff --git a/chrome/browser/sync/test/integration/local_sync_test.cc b/chrome/browser/sync/test/integration/local_sync_test.cc index ea17c67..24a1a65 100644 --- a/chrome/browser/sync/test/integration/local_sync_test.cc +++ b/chrome/browser/sync/test/integration/local_sync_test.cc
@@ -95,16 +95,29 @@ // Windows. // TODO(crbug.com/1109640): Consider whether all of these types should really // be enabled in Local Sync mode. - syncer::ModelTypeSet expected_active_data_types = syncer::ModelTypeSet( - syncer::BOOKMARKS, syncer::READING_LIST, syncer::PREFERENCES, - syncer::PASSWORDS, syncer::AUTOFILL_PROFILE, syncer::AUTOFILL, - syncer::AUTOFILL_WALLET_DATA, syncer::AUTOFILL_WALLET_METADATA, - syncer::THEMES, syncer::TYPED_URLS, syncer::EXTENSIONS, - syncer::SEARCH_ENGINES, syncer::SESSIONS, syncer::APPS, - syncer::APP_SETTINGS, syncer::EXTENSION_SETTINGS, - syncer::HISTORY_DELETE_DIRECTIVES, syncer::DEVICE_INFO, - syncer::PRIORITY_PREFERENCES, syncer::WEB_APPS, syncer::PROXY_TABS, - syncer::NIGORI); + syncer::ModelTypeSet expected_active_data_types = { + syncer::BOOKMARKS, + syncer::READING_LIST, + syncer::PREFERENCES, + syncer::PASSWORDS, + syncer::AUTOFILL_PROFILE, + syncer::AUTOFILL, + syncer::AUTOFILL_WALLET_DATA, + syncer::AUTOFILL_WALLET_METADATA, + syncer::THEMES, + syncer::TYPED_URLS, + syncer::EXTENSIONS, + syncer::SEARCH_ENGINES, + syncer::SESSIONS, + syncer::APPS, + syncer::APP_SETTINGS, + syncer::EXTENSION_SETTINGS, + syncer::HISTORY_DELETE_DIRECTIVES, + syncer::DEVICE_INFO, + syncer::PRIORITY_PREFERENCES, + syncer::WEB_APPS, + syncer::PROXY_TABS, + syncer::NIGORI}; if (base::FeatureList::IsEnabled(syncer::kSyncEnableHistoryDataType)) { // If this feature is enabled, HISTORY replaces TYPED_URLS (and HISTORY
diff --git a/chrome/browser/sync/test/integration/migration_test.cc b/chrome/browser/sync/test/integration/migration_test.cc index da1645e..a9466b28 100644 --- a/chrome/browser/sync/test/integration/migration_test.cc +++ b/chrome/browser/sync/test/integration/migration_test.cc
@@ -29,12 +29,14 @@ // Utility functions to make a model type set out of a small number of // model types. +// TODO(crbug/1444105): MakeSet() seems pretty redundant, can be replaced with +// its body. syncer::ModelTypeSet MakeSet(syncer::ModelType type) { - return syncer::ModelTypeSet(type); + return {type}; } syncer::ModelTypeSet MakeSet(syncer::ModelType type1, syncer::ModelType type2) { - return syncer::ModelTypeSet(type1, type2); + return {type1, type2}; } // An ordered list of model types sets to migrate. Used by
diff --git a/chrome/browser/sync/test/integration/single_client_bookmarks_sync_test.cc b/chrome/browser/sync/test/integration/single_client_bookmarks_sync_test.cc index 8dca10a..b4af3ee5 100644 --- a/chrome/browser/sync/test/integration/single_client_bookmarks_sync_test.cc +++ b/chrome/browser/sync/test/integration/single_client_bookmarks_sync_test.cc
@@ -259,8 +259,7 @@ bool IsExitConditionSatisfied(std::ostream* os) override { *os << "Waiting for Bookmarks data type error."; - return service()->HasAnyDatatypeErrorForTest( - syncer::ModelTypeSet(syncer::BOOKMARKS)); + return service()->HasAnyDatatypeErrorForTest({syncer::BOOKMARKS}); } }; @@ -1710,7 +1709,7 @@ // Run a sync cycle to trigger bookmarks reupload on browser startup. This is // required since bookmarks get reuploaded only after the latest changes are // downloaded to avoid uploading outdated data. - GetSyncService(kSingleProfileIndex)->TriggerRefresh(syncer::BOOKMARKS); + GetSyncService(kSingleProfileIndex)->TriggerRefresh({syncer::BOOKMARKS}); // Bookmark favicon will be loaded if there are local changes. ASSERT_TRUE( @@ -2054,8 +2053,7 @@ ASSERT_TRUE(SetupSync()) << "SetupSync() failed."; ASSERT_FALSE(GetClient(kSingleProfileIndex) ->service() - ->HasAnyDatatypeErrorForTest( - syncer::ModelTypeSet(syncer::BOOKMARKS))); + ->HasAnyDatatypeErrorForTest({syncer::BOOKMARKS})); // Add 2 new bookmarks to exceed the limit. const BookmarkNode* bookmark_bar_node = @@ -2079,8 +2077,7 @@ .Wait()); // Bookmarks should be in an error state. Thus excluding it from the // CheckForDataTypeFailures() check. - ExcludeDataTypesFromCheckForDataTypeFailures( - syncer::ModelTypeSet(syncer::BOOKMARKS)); + ExcludeDataTypesFromCheckForDataTypeFailures({syncer::BOOKMARKS}); } IN_PROC_BROWSER_TEST_F( @@ -2111,8 +2108,7 @@ ASSERT_FALSE(GetClient(kSingleProfileIndex) ->service() - ->HasAnyDatatypeErrorForTest( - syncer::ModelTypeSet(syncer::BOOKMARKS))); + ->HasAnyDatatypeErrorForTest({syncer::BOOKMARKS})); ASSERT_TRUE(SetupSync()) << "SetupSync() failed."; // We now have 5 local bookmarks(3 permanent + 2 added), which exceeds our @@ -2122,8 +2118,7 @@ .Wait()); // Bookmarks should be in an error state. Thus excluding it from the // CheckForDataTypeFailures() check. - ExcludeDataTypesFromCheckForDataTypeFailures( - syncer::ModelTypeSet(syncer::BOOKMARKS)); + ExcludeDataTypesFromCheckForDataTypeFailures({syncer::BOOKMARKS}); } IN_PROC_BROWSER_TEST_F( @@ -2158,8 +2153,7 @@ ASSERT_FALSE(GetClient(kSingleProfileIndex) ->service() - ->HasAnyDatatypeErrorForTest( - syncer::ModelTypeSet(syncer::BOOKMARKS))); + ->HasAnyDatatypeErrorForTest({syncer::BOOKMARKS})); ASSERT_TRUE(SetupSync()) << "SetupSync() failed."; // We should now have 6 local bookmarks, (3 permanent + 2 locally added + 1 @@ -2174,8 +2168,7 @@ kTitle1, GURL(kUrl1)))); // Bookmarks should be in an error state. Thus excluding it from the // CheckForDataTypeFailures() check. - ExcludeDataTypesFromCheckForDataTypeFailures( - syncer::ModelTypeSet(syncer::BOOKMARKS)); + ExcludeDataTypesFromCheckForDataTypeFailures({syncer::BOOKMARKS}); } IN_PROC_BROWSER_TEST_F( @@ -2197,8 +2190,7 @@ ASSERT_FALSE(GetClient(kSingleProfileIndex) ->service() - ->HasAnyDatatypeErrorForTest( - syncer::ModelTypeSet(syncer::BOOKMARKS))); + ->HasAnyDatatypeErrorForTest({syncer::BOOKMARKS})); ASSERT_TRUE(SetupSync()) << "SetupSync() failed."; // Create a bookmark on the server under BookmarkBar. @@ -2219,8 +2211,7 @@ kTitle2, GURL(kUrl2)))); // Bookmarks should be in an error state. Thus excluding it from the // CheckForDataTypeFailures() check. - ExcludeDataTypesFromCheckForDataTypeFailures( - syncer::ModelTypeSet(syncer::BOOKMARKS)); + ExcludeDataTypesFromCheckForDataTypeFailures({syncer::BOOKMARKS}); } IN_PROC_BROWSER_TEST_F( @@ -2249,8 +2240,7 @@ ASSERT_FALSE(GetClient(kSingleProfileIndex) ->service() - ->HasAnyDatatypeErrorForTest( - syncer::ModelTypeSet(syncer::BOOKMARKS))); + ->HasAnyDatatypeErrorForTest({syncer::BOOKMARKS})); ASSERT_TRUE(SetupSync()) << "SetupSync() failed."; // Update of size 5 exceeds the limit. @@ -2260,8 +2250,7 @@ EXPECT_TRUE(GetBookmarkBarNode(kSingleProfileIndex)->children().empty()); // Bookmarks should be in an error state. Thus excluding it from the // CheckForDataTypeFailures() check. - ExcludeDataTypesFromCheckForDataTypeFailures( - syncer::ModelTypeSet(syncer::BOOKMARKS)); + ExcludeDataTypesFromCheckForDataTypeFailures({syncer::BOOKMARKS}); } } // namespace
diff --git a/chrome/browser/sync/test/integration/single_client_offer_sync_test.cc b/chrome/browser/sync/test/integration/single_client_offer_sync_test.cc index bd71438c2..34e5e16 100644 --- a/chrome/browser/sync/test/integration/single_client_offer_sync_test.cc +++ b/chrome/browser/sync/test/integration/single_client_offer_sync_test.cc
@@ -71,8 +71,7 @@ bool TriggerGetUpdatesAndWait() { const base::Time now = base::Time::Now(); // Trigger a sync and wait for the new data to arrive. - TriggerSyncForModelTypes( - 0, syncer::ModelTypeSet(syncer::AUTOFILL_WALLET_OFFER)); + TriggerSyncForModelTypes(0, {syncer::AUTOFILL_WALLET_OFFER}); return FullUpdateTypeProgressMarkerChecker(now, GetSyncService(0), syncer::AUTOFILL_WALLET_OFFER) .Wait();
diff --git a/chrome/browser/sync/test/integration/single_client_passwords_sync_test.cc b/chrome/browser/sync/test/integration/single_client_passwords_sync_test.cc index 2d347cf..62ef915 100644 --- a/chrome/browser/sync/test/integration/single_client_passwords_sync_test.cc +++ b/chrome/browser/sync/test/integration/single_client_passwords_sync_test.cc
@@ -313,7 +313,7 @@ // Wait for data types to be ready for sync and trigger a sync cycle. // Otherwise, TriggerRefresh() would be no-op. ASSERT_TRUE(GetClient(0)->AwaitSyncSetupCompletion()); - GetSyncService(0)->TriggerRefresh(syncer::PASSWORDS); + GetSyncService(0)->TriggerRefresh({syncer::PASSWORDS}); // After restart, the last sync cycle snapshot should be empty. Once a sync // request happened (e.g. by a poll), that snapshot is populated. We use the
diff --git a/chrome/browser/sync/test/integration/single_client_secondary_account_sync_test.cc b/chrome/browser/sync/test/integration/single_client_secondary_account_sync_test.cc index 50deb948..06d5703 100644 --- a/chrome/browser/sync/test/integration/single_client_secondary_account_sync_test.cc +++ b/chrome/browser/sync/test/integration/single_client_secondary_account_sync_test.cc
@@ -25,9 +25,9 @@ syncer::ModelTypeSet AllowedTypesInStandaloneTransportMode() { // Only some special whitelisted types (and control types) are allowed in // standalone transport mode. - syncer::ModelTypeSet allowed_types( + syncer::ModelTypeSet allowed_types = { syncer::DEVICE_INFO, syncer::USER_CONSENTS, syncer::SECURITY_EVENTS, - syncer::AUTOFILL_WALLET_DATA, syncer::SHARING_MESSAGE); + syncer::AUTOFILL_WALLET_DATA, syncer::SHARING_MESSAGE}; allowed_types.PutAll(syncer::ControlTypes()); allowed_types.Put(syncer::SEND_TAB_TO_SELF); return allowed_types;
diff --git a/chrome/browser/sync/test/integration/single_client_sessions_sync_test.cc b/chrome/browser/sync/test/integration/single_client_sessions_sync_test.cc index 6c5b9407..37a157b8 100644 --- a/chrome/browser/sync/test/integration/single_client_sessions_sync_test.cc +++ b/chrome/browser/sync/test/integration/single_client_sessions_sync_test.cc
@@ -794,7 +794,7 @@ /*last_modified_time=*/0)); // Mimic a browser restart by forcing a refresh to get updates. - GetSyncService(0)->TriggerRefresh(syncer::SESSIONS); + GetSyncService(0)->TriggerRefresh({syncer::SESSIONS}); EXPECT_TRUE(UpdatedProgressMarkerChecker(GetSyncService(0)).Wait()); // Foreign data should be empty.
diff --git a/chrome/browser/sync/test/integration/single_client_standalone_transport_sync_test.cc b/chrome/browser/sync/test/integration/single_client_standalone_transport_sync_test.cc index 0ac5b03f..69c7bef 100644 --- a/chrome/browser/sync/test/integration/single_client_standalone_transport_sync_test.cc +++ b/chrome/browser/sync/test/integration/single_client_standalone_transport_sync_test.cc
@@ -32,10 +32,10 @@ "Add new types below if they run in transport mode"); // Only some special allowlisted types (and control types) are allowed in // standalone transport mode. - syncer::ModelTypeSet allowed_types( - syncer::DEVICE_INFO, syncer::USER_CONSENTS, syncer::SECURITY_EVENTS, - syncer::AUTOFILL_WALLET_DATA, syncer::CONTACT_INFO, - syncer::SHARING_MESSAGE); + syncer::ModelTypeSet allowed_types = { + syncer::DEVICE_INFO, syncer::USER_CONSENTS, + syncer::SECURITY_EVENTS, syncer::AUTOFILL_WALLET_DATA, + syncer::CONTACT_INFO, syncer::SHARING_MESSAGE}; allowed_types.PutAll(syncer::ControlTypes()); allowed_types.Put(syncer::SEND_TAB_TO_SELF); #if BUILDFLAG(IS_CHROMEOS_ASH)
diff --git a/chrome/browser/sync/test/integration/single_client_sync_invalidations_test.cc b/chrome/browser/sync/test/integration/single_client_sync_invalidations_test.cc index 28d2d79..d9d1b7d 100644 --- a/chrome/browser/sync/test/integration/single_client_sync_invalidations_test.cc +++ b/chrome/browser/sync/test/integration/single_client_sync_invalidations_test.cc
@@ -95,7 +95,7 @@ return data_types == expected_data_types; } -MATCHER_P(InterestedDataTypesContain, expected_data_types, "") { +MATCHER_P(InterestedDataTypesContain, expected_data_type, "") { syncer::ModelTypeSet data_types; for (const int field_number : arg.specifics() .device_info() @@ -108,7 +108,7 @@ } data_types.Put(data_type); } - return data_types.HasAll(expected_data_types); + return data_types.Has(expected_data_type); } MATCHER(HasInstanceIdToken, "") {
diff --git a/chrome/browser/sync/test/integration/single_client_wallet_sync_test.cc b/chrome/browser/sync/test/integration/single_client_wallet_sync_test.cc index 23150a7..b8674531 100644 --- a/chrome/browser/sync/test/integration/single_client_wallet_sync_test.cc +++ b/chrome/browser/sync/test/integration/single_client_wallet_sync_test.cc
@@ -237,8 +237,7 @@ bool TriggerGetUpdatesAndWait() { const base::Time now = base::Time::Now(); // Trigger a sync and wait for the new data to arrive. - TriggerSyncForModelTypes( - 0, syncer::ModelTypeSet(syncer::AUTOFILL_WALLET_DATA)); + TriggerSyncForModelTypes(0, {syncer::AUTOFILL_WALLET_DATA}); return FullUpdateTypeProgressMarkerChecker(now, GetSyncService(0), syncer::AUTOFILL_WALLET_DATA) .Wait();
diff --git a/chrome/browser/sync/test/integration/sync_errors_test.cc b/chrome/browser/sync/test/integration/sync_errors_test.cc index 5374aa1c..90971d39 100644 --- a/chrome/browser/sync/test/integration/sync_errors_test.cc +++ b/chrome/browser/sync/test/integration/sync_errors_test.cc
@@ -433,7 +433,7 @@ // PREFERENCES should now be throttled. EXPECT_EQ(GetThrottledDataTypes(GetSyncService(0)), - syncer::ModelTypeSet{syncer::PREFERENCES}); + syncer::ModelTypeSet({syncer::PREFERENCES})); // Unthrottle PREFERENCES to verify that sync can resume. GetFakeServer()->SetThrottledTypes(syncer::ModelTypeSet());
diff --git a/chrome/browser/ui/browser_command_controller.cc b/chrome/browser/ui/browser_command_controller.cc index 916d3005..759c1038c5 100644 --- a/chrome/browser/ui/browser_command_controller.cc +++ b/chrome/browser/ui/browser_command_controller.cc
@@ -1192,7 +1192,8 @@ IDC_SHOW_HISTORY, (!guest_session && !profile()->IsSystemProfile())); command_updater_.UpdateCommandEnabled(IDC_SHOW_DOWNLOADS, true); command_updater_.UpdateCommandEnabled(IDC_FIND_AND_EDIT_MENU, true); - command_updater_.UpdateCommandEnabled(IDC_AUTOFILL_MENU, !guest_session); + command_updater_.UpdateCommandEnabled(IDC_PASSWORDS_AND_AUTOFILL_MENU, + !guest_session); command_updater_.UpdateCommandEnabled(IDC_SHOW_PASSWORD_MANAGER, !guest_session); command_updater_.UpdateCommandEnabled(IDC_SHOW_PAYMENT_METHODS,
diff --git a/chrome/browser/ui/cocoa/dock_icon.mm b/chrome/browser/ui/cocoa/dock_icon.mm index efe238e7..2855a009 100644 --- a/chrome/browser/ui/cocoa/dock_icon.mm +++ b/chrome/browser/ui/cocoa/dock_icon.mm
@@ -6,8 +6,8 @@ #include <stdint.h> +#include "base/apple/bundle_locations.h" #include "base/check_op.h" -#include "base/mac/bundle_locations.h" #include "base/mac/scoped_nsobject.h" #include "content/public/browser/browser_thread.h" #include "ui/gfx/scoped_ns_graphics_context_save_gstate_mac.h" @@ -63,7 +63,7 @@ - (void)drawRect:(NSRect)dirtyRect { // Not -[NSApplication applicationIconImage]; that fails to return a pasted // custom icon. - NSString* appPath = [base::mac::MainBundle() bundlePath]; + NSString* appPath = [base::apple::MainBundle() bundlePath]; NSImage* appIcon = [[NSWorkspace sharedWorkspace] iconForFile:appPath]; [appIcon drawInRect:[self bounds] fromRect:NSZeroRect
diff --git a/chrome/browser/ui/cocoa/first_run_dialog_cocoa.mm b/chrome/browser/ui/cocoa/first_run_dialog_cocoa.mm index d4cc11e6..41eea8f3 100644 --- a/chrome/browser/ui/cocoa/first_run_dialog_cocoa.mm +++ b/chrome/browser/ui/cocoa/first_run_dialog_cocoa.mm
@@ -4,10 +4,10 @@ #import "chrome/browser/ui/cocoa/first_run_dialog_cocoa.h" +#include "base/apple/bundle_locations.h" #include "base/command_line.h" #include "base/compiler_specific.h" #include "base/functional/bind.h" -#include "base/mac/bundle_locations.h" #import "base/mac/scoped_nsobject.h" #include "base/memory/ref_counted.h" #include "base/run_loop.h"
diff --git a/chrome/browser/ui/cocoa/task_manager_mac.mm b/chrome/browser/ui/cocoa/task_manager_mac.mm index 751d045..055bcf1 100644 --- a/chrome/browser/ui/cocoa/task_manager_mac.mm +++ b/chrome/browser/ui/cocoa/task_manager_mac.mm
@@ -9,8 +9,8 @@ #include <algorithm> #include <vector> +#include "base/apple/bundle_locations.h" #include "base/feature_list.h" -#include "base/mac/bundle_locations.h" #include "base/strings/sys_string_conversions.h" #include "build/buildflag.h" #include "chrome/browser/browser_process.h"
diff --git a/chrome/browser/ui/cocoa/test/cocoa_test_helper.mm b/chrome/browser/ui/cocoa/test/cocoa_test_helper.mm index 6d31317..32f1b6dd 100644 --- a/chrome/browser/ui/cocoa/test/cocoa_test_helper.mm +++ b/chrome/browser/ui/cocoa/test/cocoa_test_helper.mm
@@ -4,7 +4,7 @@ #import "chrome/browser/ui/cocoa/test/cocoa_test_helper.h" -#include "base/mac/bundle_locations.h" +#include "base/apple/bundle_locations.h" #include "base/path_service.h" #include "chrome/common/chrome_constants.h" @@ -23,5 +23,5 @@ base::FilePath path; base::PathService::Get(base::DIR_EXE, &path); path = path.Append(chrome::kFrameworkName); - base::mac::SetOverrideFrameworkBundlePath(path); + base::apple::SetOverrideFrameworkBundlePath(path); }
diff --git a/chrome/browser/ui/passwords/bubble_controllers/items_bubble_controller_unittest.cc b/chrome/browser/ui/passwords/bubble_controllers/items_bubble_controller_unittest.cc index c61fa45..ce0b0f7 100644 --- a/chrome/browser/ui/passwords/bubble_controllers/items_bubble_controller_unittest.cc +++ b/chrome/browser/ui/passwords/bubble_controllers/items_bubble_controller_unittest.cc
@@ -222,8 +222,7 @@ sync_service()->GetUserSettings()->SetSelectedTypes( /*sync_everything=*/false, - /*types=*/syncer::UserSelectableTypeSet( - syncer::UserSelectableType::kPasswords)); + /*types=*/{syncer::UserSelectableType::kPasswords}); EXPECT_EQ( controller()->GetPasswordSyncState(), password_manager::SyncState::kAccountPasswordsActiveNormalEncryption);
diff --git a/chrome/browser/ui/passwords/bubble_controllers/save_update_bubble_controller_unittest.cc b/chrome/browser/ui/passwords/bubble_controllers/save_update_bubble_controller_unittest.cc index 2ba7deb..175ebed 100644 --- a/chrome/browser/ui/passwords/bubble_controllers/save_update_bubble_controller_unittest.cc +++ b/chrome/browser/ui/passwords/bubble_controllers/save_update_bubble_controller_unittest.cc
@@ -72,8 +72,7 @@ void SetupAccountPasswordStore(syncer::TestSyncService* sync_service) { sync_service->GetUserSettings()->SetSelectedTypes( /*sync_everything=*/false, - /*types=*/syncer::UserSelectableTypeSet( - syncer::UserSelectableType::kPasswords)); + /*types=*/{syncer::UserSelectableType::kPasswords}); sync_service->SetHasSyncConsent(false); }
diff --git a/chrome/browser/ui/passwords/manage_passwords_test.cc b/chrome/browser/ui/passwords/manage_passwords_test.cc index df6ec171..fe12b2b 100644 --- a/chrome/browser/ui/passwords/manage_passwords_test.cc +++ b/chrome/browser/ui/passwords/manage_passwords_test.cc
@@ -213,12 +213,11 @@ sync_service->SetDisableReasons({}); sync_service->GetUserSettings()->SetSelectedTypes( /*sync_everything=*/false, - /*types=*/syncer::UserSelectableTypeSet( - syncer::UserSelectableType::kPasswords)); + /*types=*/{syncer::UserSelectableType::kPasswords}); } else { sync_service->SetHasSyncConsent(false); sync_service->SetDisableReasons( - syncer::SyncService::DISABLE_REASON_USER_CHOICE); + {syncer::SyncService::DISABLE_REASON_USER_CHOICE}); sync_service->GetUserSettings()->SetSelectedTypes( /*sync_everything=*/false, /*types=*/syncer::UserSelectableTypeSet());
diff --git a/chrome/browser/ui/signin/profile_customization_synced_theme_waiter_unittest.cc b/chrome/browser/ui/signin/profile_customization_synced_theme_waiter_unittest.cc index 103050a..beac2bc 100644 --- a/chrome/browser/ui/signin/profile_customization_synced_theme_waiter_unittest.cc +++ b/chrome/browser/ui/signin/profile_customization_synced_theme_waiter_unittest.cc
@@ -194,7 +194,7 @@ Run(ProfileCustomizationSyncedThemeWaiter::Outcome::kSyncCannotStart)); test_sync_service()->SetDisableReasons( - syncer::SyncService::DISABLE_REASON_ENTERPRISE_POLICY); + {syncer::SyncService::DISABLE_REASON_ENTERPRISE_POLICY}); WaitForSyncedTheme(callback.Get()); } @@ -209,7 +209,7 @@ WaitForSyncedTheme(callback.Get()); test_sync_service()->SetDisableReasons( - syncer::SyncService::DISABLE_REASON_ENTERPRISE_POLICY); + {syncer::SyncService::DISABLE_REASON_ENTERPRISE_POLICY}); test_sync_service()->FireStateChanged(); }
diff --git a/chrome/browser/ui/signin_intercept_first_run_experience_dialog_browsertest.cc b/chrome/browser/ui/signin_intercept_first_run_experience_dialog_browsertest.cc index 370f36c2..409a773c 100644 --- a/chrome/browser/ui/signin_intercept_first_run_experience_dialog_browsertest.cc +++ b/chrome/browser/ui/signin_intercept_first_run_experience_dialog_browsertest.cc
@@ -600,7 +600,7 @@ SyncDisabled) { SignIn(kEnterpriseEmail); sync_service()->SetDisableReasons( - syncer::SyncService::DISABLE_REASON_ENTERPRISE_POLICY); + {syncer::SyncService::DISABLE_REASON_ENTERPRISE_POLICY}); ExpectPrimaryAccountWithExactConsentLevel(signin::ConsentLevel::kSignin); content::TestNavigationObserver profile_customization_observer( kProfileCustomizationUrl);
diff --git a/chrome/browser/ui/toolbar/app_menu_model.cc b/chrome/browser/ui/toolbar/app_menu_model.cc index e997bec1..538d314b 100644 --- a/chrome/browser/ui/toolbar/app_menu_model.cc +++ b/chrome/browser/ui/toolbar/app_menu_model.cc
@@ -354,9 +354,9 @@ } //////////////////////////////////////////////////////////////////////////////// -// AutofillSubMenuModel +// PasswordsAndAutofillSubMenuModel -AutofillSubMenuModel::AutofillSubMenuModel( +PasswordsAndAutofillSubMenuModel::PasswordsAndAutofillSubMenuModel( ui::SimpleMenuModel::Delegate* delegate) : SimpleMenuModel(delegate) { AddItemWithStringIdAndIcon( @@ -373,7 +373,7 @@ ui::kColorMenuIcon, kDefaultIconSize)); } -AutofillSubMenuModel::~AutofillSubMenuModel() = default; +PasswordsAndAutofillSubMenuModel::~PasswordsAndAutofillSubMenuModel() = default; //////////////////////////////////////////////////////////////////////////////// // FindAndEditSubMenuModel @@ -1051,8 +1051,10 @@ features::IsChromeRefresh2023() && !base::FeatureList::IsEnabled( password_manager::features::kPasswordManagerRedesign)) { - sub_menus_.push_back(std::make_unique<AutofillSubMenuModel>(this)); - AddSubMenuWithStringId(IDC_AUTOFILL_MENU, IDS_PASSWORDS_AND_AUTOFILL_MENU, + sub_menus_.push_back( + std::make_unique<PasswordsAndAutofillSubMenuModel>(this)); + AddSubMenuWithStringId(IDC_PASSWORDS_AND_AUTOFILL_MENU, + IDS_PASSWORDS_AND_AUTOFILL_MENU, sub_menus_.back().get()); } @@ -1290,7 +1292,7 @@ set_icon(IDC_TRANSLATE_PAGE, kTranslateChromeRefreshIcon); set_icon(IDC_ROUTE_MEDIA, kCastMenuIcon); set_icon(IDC_FIND_AND_EDIT_MENU, kSearchMenuIcon); - set_icon(IDC_AUTOFILL_MENU, kKeyChromeRefreshIcon); + set_icon(IDC_PASSWORDS_AND_AUTOFILL_MENU, kKeyChromeRefreshIcon); set_icon(IDC_MORE_TOOLS_MENU, kMoreToolsMenuIcon); set_icon(IDC_OPTIONS, kSettingsMenuIcon); #if BUILDFLAG(GOOGLE_CHROME_BRANDING)
diff --git a/chrome/browser/ui/toolbar/app_menu_model.h b/chrome/browser/ui/toolbar/app_menu_model.h index 4a423f0..33fd495 100644 --- a/chrome/browser/ui/toolbar/app_menu_model.h +++ b/chrome/browser/ui/toolbar/app_menu_model.h
@@ -139,14 +139,17 @@ void Build(Browser* browser); }; -class AutofillSubMenuModel : public ui::SimpleMenuModel { +class PasswordsAndAutofillSubMenuModel : public ui::SimpleMenuModel { public: - explicit AutofillSubMenuModel(ui::SimpleMenuModel::Delegate* delegate); + explicit PasswordsAndAutofillSubMenuModel( + ui::SimpleMenuModel::Delegate* delegate); - AutofillSubMenuModel(const AutofillSubMenuModel&) = delete; - AutofillSubMenuModel& operator=(const AutofillSubMenuModel&) = delete; + PasswordsAndAutofillSubMenuModel(const PasswordsAndAutofillSubMenuModel&) = + delete; + PasswordsAndAutofillSubMenuModel& operator=( + const PasswordsAndAutofillSubMenuModel&) = delete; - ~AutofillSubMenuModel() override; + ~PasswordsAndAutofillSubMenuModel() override; }; class FindAndEditSubMenuModel : public ui::SimpleMenuModel {
diff --git a/chrome/browser/ui/views/download/bubble/download_bubble_security_view.cc b/chrome/browser/ui/views/download/bubble/download_bubble_security_view.cc index 97b2152..7d907a0 100644 --- a/chrome/browser/ui/views/download/bubble/download_bubble_security_view.cc +++ b/chrome/browser/ui/views/download/bubble/download_bubble_security_view.cc
@@ -230,9 +230,12 @@ // First open primary dialog, and then execute the command. If a deletion // happens leading to closure of the bubble, it will be called after primary // dialog is opened. - navigation_handler_->OpenPrimaryDialog(); - bubble_controller_->ProcessDownloadButtonPress(model_.get(), command, - /*is_main_view=*/false); + if (navigation_handler_ && bubble_controller_) { + navigation_handler_->OpenPrimaryDialog(); + bubble_controller_->ProcessDownloadButtonPress(model_.get(), command, + /*is_main_view=*/false); + } + base::UmaHistogramEnumeration( kSubpageActionHistogram, is_secondary_button ? DownloadBubbleSubpageAction::kPressedSecondaryButton @@ -339,11 +342,11 @@ } DownloadBubbleSecurityView::DownloadBubbleSecurityView( - DownloadBubbleUIController* bubble_controller, - DownloadBubbleNavigationHandler* navigation_handler, + base::WeakPtr<DownloadBubbleUIController> bubble_controller, + base::WeakPtr<DownloadBubbleNavigationHandler> navigation_handler, views::BubbleDialogDelegate* bubble_delegate) - : bubble_controller_(bubble_controller), - navigation_handler_(navigation_handler), + : bubble_controller_(std::move(bubble_controller)), + navigation_handler_(std::move(navigation_handler)), bubble_delegate_(bubble_delegate) { SetLayoutManager(std::make_unique<views::FlexLayout>()) ->SetOrientation(views::LayoutOrientation::kVertical);
diff --git a/chrome/browser/ui/views/download/bubble/download_bubble_security_view.h b/chrome/browser/ui/views/download/bubble/download_bubble_security_view.h index a995f28..156fdfb 100644 --- a/chrome/browser/ui/views/download/bubble/download_bubble_security_view.h +++ b/chrome/browser/ui/views/download/bubble/download_bubble_security_view.h
@@ -31,8 +31,8 @@ public: METADATA_HEADER(DownloadBubbleSecurityView); DownloadBubbleSecurityView( - DownloadBubbleUIController* bubble_controller, - DownloadBubbleNavigationHandler* navigation_handler, + base::WeakPtr<DownloadBubbleUIController> bubble_controller, + base::WeakPtr<DownloadBubbleNavigationHandler> navigation_handler, views::BubbleDialogDelegate* bubble_delegate); DownloadBubbleSecurityView(const DownloadBubbleSecurityView&) = delete; DownloadBubbleSecurityView& operator=(const DownloadBubbleSecurityView&) = @@ -74,8 +74,8 @@ raw_ptr<DownloadBubbleRowView> download_row_view_; DownloadUIModel::DownloadUIModelPtr model_; - raw_ptr<DownloadBubbleUIController> bubble_controller_ = nullptr; - raw_ptr<DownloadBubbleNavigationHandler> navigation_handler_ = nullptr; + base::WeakPtr<DownloadBubbleUIController> bubble_controller_ = nullptr; + base::WeakPtr<DownloadBubbleNavigationHandler> navigation_handler_ = nullptr; raw_ptr<views::BubbleDialogDelegate, DanglingUntriaged> bubble_delegate_ = nullptr; // The secondary button is the one that may be protected by the checkbox.
diff --git a/chrome/browser/ui/views/download/bubble/download_bubble_security_view_unittest.cc b/chrome/browser/ui/views/download/bubble/download_bubble_security_view_unittest.cc index c527b23..d72e2ec 100644 --- a/chrome/browser/ui/views/download/bubble/download_bubble_security_view_unittest.cc +++ b/chrome/browser/ui/views/download/bubble/download_bubble_security_view_unittest.cc
@@ -46,6 +46,12 @@ void OpenSecurityDialog(DownloadBubbleRowView*) override {} void CloseDialog(views::Widget::ClosedReason) override {} void ResizeDialog() override {} + base::WeakPtr<DownloadBubbleNavigationHandler> GetWeakPtr() override { + return weak_factory_.GetWeakPtr(); + } + + private: + base::WeakPtrFactory<MockDownloadBubbleNavigationHandler> weak_factory_{this}; }; } // namespace @@ -76,14 +82,14 @@ anchor_widget_->GetContentsView(), views::BubbleBorder::TOP_RIGHT); bubble_delegate_ = bubble_delegate.get(); bubble_navigator_ = std::make_unique<MockDownloadBubbleNavigationHandler>(); - security_view_ = bubble_delegate_->SetContentsView( - std::make_unique<DownloadBubbleSecurityView>(bubble_controller_.get(), - bubble_navigator_.get(), - bubble_delegate_)); views::BubbleDialogDelegate::CreateBubble(std::move(bubble_delegate)); bubble_delegate_->GetWidget()->Show(); bubble_controller_ = std::make_unique<MockDownloadBubbleUIController>(browser_.get()); + security_view_ = bubble_delegate_->SetContentsView( + std::make_unique<DownloadBubbleSecurityView>( + bubble_controller_->GetWeakPtr(), bubble_navigator_->GetWeakPtr(), + bubble_delegate_)); row_list_view_ = std::make_unique<DownloadBubbleRowListView>( /*is_partial_view=*/true, browser_.get()); @@ -189,7 +195,8 @@ // Back action logged. { auto security_view = std::make_unique<DownloadBubbleSecurityView>( - bubble_controller_.get(), bubble_navigator_.get(), bubble_delegate_); + bubble_controller_->GetWeakPtr(), bubble_navigator_->GetWeakPtr(), + bubble_delegate_); security_view->UpdateSecurityView(row_view_.get()); security_view->BackButtonPressed(); @@ -205,7 +212,8 @@ // Close action logged { auto security_view = std::make_unique<DownloadBubbleSecurityView>( - bubble_controller_.get(), bubble_navigator_.get(), bubble_delegate_); + bubble_controller_->GetWeakPtr(), bubble_navigator_->GetWeakPtr(), + bubble_delegate_); security_view->UpdateSecurityView(row_view_.get()); security_view->CloseBubble(); @@ -220,7 +228,8 @@ // Dismiss action logged { auto security_view = std::make_unique<DownloadBubbleSecurityView>( - bubble_controller_.get(), bubble_navigator_.get(), bubble_delegate_); + bubble_controller_->GetWeakPtr(), bubble_navigator_->GetWeakPtr(), + bubble_delegate_); security_view->UpdateSecurityView(row_view_.get()); security_view.reset(); @@ -233,7 +242,8 @@ // Dismiss action logged after update { auto security_view = std::make_unique<DownloadBubbleSecurityView>( - bubble_controller_.get(), bubble_navigator_.get(), bubble_delegate_); + bubble_controller_->GetWeakPtr(), bubble_navigator_->GetWeakPtr(), + bubble_delegate_); security_view->UpdateSecurityView(row_view_.get()); security_view->BackButtonPressed();
diff --git a/chrome/browser/ui/views/download/bubble/download_toolbar_button_view.cc b/chrome/browser/ui/views/download/bubble/download_toolbar_button_view.cc index 9084c36e..17da9b6 100644 --- a/chrome/browser/ui/views/download/bubble/download_toolbar_button_view.cc +++ b/chrome/browser/ui/views/download/bubble/download_toolbar_button_view.cc
@@ -453,6 +453,11 @@ bubble_delegate_->SizeToContents(); } +base::WeakPtr<DownloadBubbleNavigationHandler> +DownloadToolbarButtonView::GetWeakPtr() { + return weak_factory_.GetWeakPtr(); +} + void DownloadToolbarButtonView::OnBubbleDelegateDeleted() { bubble_delegate_ = nullptr; primary_view_ = nullptr; @@ -483,11 +488,12 @@ switcher_view->SetLayoutManager(std::make_unique<views::FlexLayout>()) ->SetOrientation(views::LayoutOrientation::kVertical); primary_view_ = switcher_view->AddChildView(std::move(bubble_contents_view)); - // raw ptr for this and member fields are safe as Toolbar Button view owns the - // Bubble. + // raw ptr for this bubble_delegate is safe as it owns the + // DownloadBubbleSecurityView. security_view_ = switcher_view->AddChildView(std::make_unique<DownloadBubbleSecurityView>( - bubble_controller_.get(), this, bubble_delegate.get())); + bubble_controller_->GetWeakPtr(), GetWeakPtr(), + bubble_delegate.get())); security_view_->SetVisible(false); bubble_delegate->set_margins(GetPrimaryViewMargin()); bubble_delegate->SetEnableArrowKeyTraversal(true);
diff --git a/chrome/browser/ui/views/download/bubble/download_toolbar_button_view.h b/chrome/browser/ui/views/download/bubble/download_toolbar_button_view.h index b29c04928..0508fe7f 100644 --- a/chrome/browser/ui/views/download/bubble/download_toolbar_button_view.h +++ b/chrome/browser/ui/views/download/bubble/download_toolbar_button_view.h
@@ -33,6 +33,7 @@ virtual void OpenSecurityDialog(DownloadBubbleRowView* download_row_view) = 0; virtual void CloseDialog(views::Widget::ClosedReason reason) = 0; virtual void ResizeDialog() = 0; + virtual base::WeakPtr<DownloadBubbleNavigationHandler> GetWeakPtr() = 0; }; // Download icon shown in the trusted area of the toolbar. Its lifetime is tied @@ -74,6 +75,7 @@ void OpenSecurityDialog(DownloadBubbleRowView* download_row_view) override; void CloseDialog(views::Widget::ClosedReason reason) override; void ResizeDialog() override; + base::WeakPtr<DownloadBubbleNavigationHandler> GetWeakPtr() override; // Deactivates the automatic closing of the partial bubble. void DeactivateAutoClose();
diff --git a/chrome/browser/ui/views/global_media_controls/media_item_ui_helper.cc b/chrome/browser/ui/views/global_media_controls/media_item_ui_helper.cc index c0ab1b89..59cb848 100644 --- a/chrome/browser/ui/views/global_media_controls/media_item_ui_helper.cc +++ b/chrome/browser/ui/views/global_media_controls/media_item_ui_helper.cc
@@ -63,6 +63,10 @@ const std::string& item_id, base::WeakPtr<media_message_center::MediaNotificationItem> item, content::BrowserContext* context) { + if (!media_router::MediaRouterEnabled(context)) { + return absl::nullopt; + } + // Return absl::nullopt if the item is not a local media session. if (!item || item->SourceType() != media_message_center::SourceType::kLocalMediaSession) {
diff --git a/chrome/browser/ui/views/profiles/enterprise_profile_welcome_ui_browsertest.cc b/chrome/browser/ui/views/profiles/enterprise_profile_welcome_ui_browsertest.cc index 319ece92..3997a35 100644 --- a/chrome/browser/ui/views/profiles/enterprise_profile_welcome_ui_browsertest.cc +++ b/chrome/browser/ui/views/profiles/enterprise_profile_welcome_ui_browsertest.cc
@@ -50,36 +50,28 @@ // Permutations of supported parameters. const EnterpriseWelcomeTestParam kWindowTestParams[] = { - // Naming note: "Fre" refers to the TangibleSync style variants of the UI, - // which is now the default. - {.pixel_test_param = {.test_suffix = "EnterpriseWelcomeFre"}}, - {.pixel_test_param = {.test_suffix = "EnterpriseWelcomeFreDarkTheme", - .use_dark_theme = true}}, - {.pixel_test_param = {.test_suffix = "EnterpriseWelcomeFreRtl", + {.pixel_test_param = {.test_suffix = "Regular"}}, + {.pixel_test_param = {.test_suffix = "DarkTheme", .use_dark_theme = true}}, + {.pixel_test_param = {.test_suffix = "Rtl", .use_right_to_left_language = true}}, - {.pixel_test_param = {.test_suffix = "EnterpriseWelcomeFreSmallWindow", + {.pixel_test_param = {.test_suffix = "SmallWindow", .use_small_window = true}}, - {.pixel_test_param = {.test_suffix = "EnterpriseWelcomeFreCR2023", + {.pixel_test_param = {.test_suffix = "CR2023", .use_chrome_refresh_2023_style = true}}, }; const EnterpriseWelcomeTestParam kDialogTestParams[] = { - // Naming note: "Fre" refers to the TangibleSync style variants of the UI, - // which is now the default. - {.pixel_test_param = {.test_suffix = "EnterpriseWelcomeFre"}}, - {.pixel_test_param = {.test_suffix = - "EnterpriseWelcomeFreWithLinkDataCheckbox"}, + {.pixel_test_param = {.test_suffix = "Regular"}}, + {.pixel_test_param = {.test_suffix = "WithLinkDataCheckbox"}, .show_link_data_checkbox = true}, - {.pixel_test_param = - {.test_suffix = "EnterpriseWelcomeFreWithProfileCreationRequired"}, + {.pixel_test_param = {.test_suffix = "WithProfileCreationRequired"}, .profile_creation_required_by_policy = true}, - {.pixel_test_param = {.test_suffix = "EnterpriseWelcomeFreDarkTheme", - .use_dark_theme = true}, + {.pixel_test_param = {.test_suffix = "DarkTheme", .use_dark_theme = true}, .show_link_data_checkbox = true}, - {.pixel_test_param = {.test_suffix = "EnterpriseWelcomeFreRtl", + {.pixel_test_param = {.test_suffix = "Rtl", .use_right_to_left_language = true}, .show_link_data_checkbox = true}, - {.pixel_test_param = {.test_suffix = "EnterpriseWelcomeFreCR2023", + {.pixel_test_param = {.test_suffix = "CR2023", .use_chrome_refresh_2023_style = true}}, };
diff --git a/chrome/browser/ui/views/profiles/profile_customization_bubble_sync_controller_unittest.cc b/chrome/browser/ui/views/profiles/profile_customization_bubble_sync_controller_unittest.cc index 5665492b..f40592b 100644 --- a/chrome/browser/ui/views/profiles/profile_customization_bubble_sync_controller_unittest.cc +++ b/chrome/browser/ui/views/profiles/profile_customization_bubble_sync_controller_unittest.cc
@@ -149,7 +149,7 @@ EXPECT_CALL(show_bubble, Run(Outcome::kShowBubble)); test_sync_service_.SetDisableReasons( - syncer::SyncService::DISABLE_REASON_ENTERPRISE_POLICY); + {syncer::SyncService::DISABLE_REASON_ENTERPRISE_POLICY}); ApplyColorAndShowBubbleWhenNoValueSynced(show_bubble.Get()); }
diff --git a/chrome/browser/ui/views/profiles/profile_picker_ui_browsertest.cc b/chrome/browser/ui/views/profiles/profile_picker_ui_browsertest.cc index 31af76a8..37193e5 100644 --- a/chrome/browser/ui/views/profiles/profile_picker_ui_browsertest.cc +++ b/chrome/browser/ui/views/profiles/profile_picker_ui_browsertest.cc
@@ -41,15 +41,15 @@ // Permutations of supported parameters. const ProfilePickerTestParam kTestParams[] = { - {.pixel_test_param = {.test_suffix = "TS"}}, - {.pixel_test_param = {.test_suffix = "TSMultipleProfiles"}, + {.pixel_test_param = {.test_suffix = "Regular"}}, + {.pixel_test_param = {.test_suffix = "MultipleProfiles"}, .use_multiple_profiles = true}, - {.pixel_test_param = {.test_suffix = "DarkRtlSmallTSMultipleProfiles", + {.pixel_test_param = {.test_suffix = "DarkRtlSmallMultipleProfiles", .use_dark_theme = true, .use_right_to_left_language = true, .use_small_window = true}, .use_multiple_profiles = true}, - {.pixel_test_param = {.test_suffix = "TSCR2023", + {.pixel_test_param = {.test_suffix = "CR2023", .use_chrome_refresh_2023_style = true}}, };
diff --git a/chrome/browser/ui/views/profiles/profile_picker_view_browsertest.cc b/chrome/browser/ui/views/profiles/profile_picker_view_browsertest.cc index a5dd4ad..8fa6be5 100644 --- a/chrome/browser/ui/views/profiles/profile_picker_view_browsertest.cc +++ b/chrome/browser/ui/views/profiles/profile_picker_view_browsertest.cc
@@ -2732,7 +2732,7 @@ // Unblock the sync service and simulate the server-side // being disabled. sync_service()->SetDisableReasons( - syncer::SyncService::DISABLE_REASON_ENTERPRISE_POLICY); + {syncer::SyncService::DISABLE_REASON_ENTERPRISE_POLICY}); sync_service()->SetTransportState( syncer::SyncService::TransportState::ACTIVE); sync_service()->FireStateChanged();
diff --git a/chrome/browser/ui/views/profiles/profile_type_choice_ui_browsertest.cc b/chrome/browser/ui/views/profiles/profile_type_choice_ui_browsertest.cc index 7d97061..1b4226f 100644 --- a/chrome/browser/ui/views/profiles/profile_type_choice_ui_browsertest.cc +++ b/chrome/browser/ui/views/profiles/profile_type_choice_ui_browsertest.cc
@@ -35,8 +35,8 @@ // Permutations of supported parameters. const PixelTestParam kTestParams[] = { - {.test_suffix = "TS"}, - {.test_suffix = "DarkRtlSmallTS", + {.test_suffix = "Regular"}, + {.test_suffix = "DarkRtlSmall", .use_dark_theme = true, .use_right_to_left_language = true, .use_small_window = true},
diff --git a/chrome/browser/ui/views/profiles/sync_confirmation_ui_browsertest.cc b/chrome/browser/ui/views/profiles/sync_confirmation_ui_browsertest.cc index 4b497cc..028d6fa 100644 --- a/chrome/browser/ui/views/profiles/sync_confirmation_ui_browsertest.cc +++ b/chrome/browser/ui/views/profiles/sync_confirmation_ui_browsertest.cc
@@ -51,34 +51,32 @@ // Permutations of supported parameters. const SyncConfirmationTestParam kWindowTestParams[] = { - {.pixel_test_param = {.test_suffix = "TangibleSync"}}, - {.pixel_test_param = {.test_suffix = "TangibleSyncDarkTheme", - .use_dark_theme = true}}, - {.pixel_test_param = {.test_suffix = "TangibleSyncRtl", + {.pixel_test_param = {.test_suffix = "Regular"}}, + {.pixel_test_param = {.test_suffix = "DarkTheme", .use_dark_theme = true}}, + {.pixel_test_param = {.test_suffix = "Rtl", .use_right_to_left_language = true}}, - {.pixel_test_param = {.test_suffix = "TangibleSyncSmallWindow", + {.pixel_test_param = {.test_suffix = "SmallWindow", .use_small_window = true}}, - {.pixel_test_param = {.test_suffix = "TangibleSyncManagedAccount"}, + {.pixel_test_param = {.test_suffix = "ManagedAccount"}, .account_management_status = AccountManagementStatus::kManaged}, - {.pixel_test_param = {.test_suffix = "TangibleSyncCR2023", + {.pixel_test_param = {.test_suffix = "CR2023", .use_chrome_refresh_2023_style = true}}, }; const SyncConfirmationTestParam kDialogTestParams[] = { - {.pixel_test_param = {.test_suffix = "TangibleSync"}, + {.pixel_test_param = {.test_suffix = "Regular"}, .sync_style = SyncConfirmationStyle::kDefaultModal}, - {.pixel_test_param = {.test_suffix = "TangibleSyncSigninInterceptStyle"}, + {.pixel_test_param = {.test_suffix = "SigninInterceptStyle"}, .sync_style = SyncConfirmationStyle::kSigninInterceptModal}, - {.pixel_test_param = {.test_suffix = "TangibleSyncDarkTheme", - .use_dark_theme = true}, + {.pixel_test_param = {.test_suffix = "DarkTheme", .use_dark_theme = true}, .sync_style = SyncConfirmationStyle::kDefaultModal}, - {.pixel_test_param = {.test_suffix = "TangibleSyncRtl", + {.pixel_test_param = {.test_suffix = "Rtl", .use_right_to_left_language = true}, .sync_style = SyncConfirmationStyle::kDefaultModal}, - {.pixel_test_param = {.test_suffix = "TangibleSyncManagedAccount"}, + {.pixel_test_param = {.test_suffix = "ManagedAccount"}, .account_management_status = AccountManagementStatus::kManaged, .sync_style = SyncConfirmationStyle::kDefaultModal}, - {.pixel_test_param = {.test_suffix = "TangibleSyncCR2023", + {.pixel_test_param = {.test_suffix = "CR2023", .use_chrome_refresh_2023_style = true}, .sync_style = SyncConfirmationStyle::kDefaultModal}, };
diff --git a/chrome/browser/ui/webui/ash/sync/os_sync_handler_unittest.cc b/chrome/browser/ui/webui/ash/sync/os_sync_handler_unittest.cc index dc5efa62..199a43f 100644 --- a/chrome/browser/ui/webui/ash/sync/os_sync_handler_unittest.cc +++ b/chrome/browser/ui/webui/ash/sync/os_sync_handler_unittest.cc
@@ -302,7 +302,7 @@ TEST_F(OsSyncHandlerTest, ShowSetupSyncForAllTypesIndividually) { for (UserSelectableOsType type : UserSelectableOsTypeSet::All()) { - UserSelectableOsTypeSet types(type); + const UserSelectableOsTypeSet types = {type}; user_settings_->SetSelectedOsTypes(/*sync_all_os_types=*/false, types); handler_->HandleDidNavigateToOsSyncPage(base::Value::List());
diff --git a/chrome/browser/ui/webui/browser_command/browser_command_handler_unittest.cc b/chrome/browser/ui/webui/browser_command/browser_command_handler_unittest.cc index a2a0efa..8cbef83 100644 --- a/chrome/browser/ui/webui/browser_command/browser_command_handler_unittest.cc +++ b/chrome/browser/ui/webui/browser_command/browser_command_handler_unittest.cc
@@ -81,8 +81,9 @@ ui::ElementContext GetUiElementContext() override { return kTestContext1; } CommandUpdater* GetCommandUpdater() override { - if (command_updater_) + if (command_updater_) { return command_updater_.get(); + } return BrowserCommandHandler::GetCommandUpdater(); } @@ -171,13 +172,15 @@ : TestTutorialService(tutorial_registry, help_bubble_factory_registry) {} ~MockTutorialService() override = default; - MOCK_METHOD4(StartTutorial, - void(user_education::TutorialIdentifier, - ui::ElementContext, - base::OnceClosure, - base::OnceClosure)); - MOCK_METHOD2(LogStartedFromWhatsNewPage, - void(user_education::TutorialIdentifier, bool)); + MOCK_METHOD(void, + StartTutorial, + (user_education::TutorialIdentifier, + ui::ElementContext, + base::OnceClosure, + base::OnceClosure)); + MOCK_METHOD(void, + LogStartedFromWhatsNewPage, + (user_education::TutorialIdentifier, bool)); MOCK_CONST_METHOD0(IsRunningTutorial, bool()); }; @@ -186,9 +189,9 @@ explicit MockCommandHandler(Profile* profile) : TestCommandHandler(profile) {} ~MockCommandHandler() override = default; - MOCK_METHOD2(NavigateToURL, void(const GURL&, WindowOpenDisposition)); + MOCK_METHOD(void, NavigateToURL, (const GURL&, WindowOpenDisposition)); - MOCK_METHOD0(OpenFeedbackForm, void()); + MOCK_METHOD(void, OpenFeedbackForm, ()); }; class MockCommandUpdater : public CommandUpdaterImpl {
diff --git a/chrome/browser/ui/webui/password_manager/sync_handler_unittest.cc b/chrome/browser/ui/webui/password_manager/sync_handler_unittest.cc index 5997f25..8693b9d 100644 --- a/chrome/browser/ui/webui/password_manager/sync_handler_unittest.cc +++ b/chrome/browser/ui/webui/password_manager/sync_handler_unittest.cc
@@ -146,9 +146,11 @@ ON_CALL(*sync_service(), GetTransportState()) .WillByDefault(Return(syncer::SyncService::TransportState::ACTIVE)); ON_CALL(*sync_service(), GetActiveDataTypes()) - .WillByDefault(testing::Return(syncer::ModelTypeSet(syncer::PASSWORDS))); + .WillByDefault( + testing::Return(syncer::ModelTypeSet({syncer::PASSWORDS}))); ON_CALL(*sync_service()->GetMockUserSettings(), GetEncryptedDataTypes()) - .WillByDefault(testing::Return(syncer::ModelTypeSet(syncer::PASSWORDS))); + .WillByDefault( + testing::Return(syncer::ModelTypeSet({syncer::PASSWORDS}))); ON_CALL(*sync_service()->GetMockUserSettings(), GetPassphraseType()) .WillByDefault(Return(syncer::PassphraseType::kKeystorePassphrase)); ON_CALL(*sync_service()->GetMockUserSettings(), IsPassphraseRequired())
diff --git a/chrome/browser/ui/webui/print_preview/print_preview_handler.cc b/chrome/browser/ui/webui/print_preview/print_preview_handler.cc index 30d22a9f..86b70424 100644 --- a/chrome/browser/ui/webui/print_preview/print_preview_handler.cc +++ b/chrome/browser/ui/webui/print_preview/print_preview_handler.cc
@@ -70,6 +70,10 @@ #include "third_party/blink/public/common/associated_interfaces/associated_interface_provider.h" #include "third_party/icu/source/i18n/unicode/ulocdata.h" +#if BUILDFLAG(ENABLE_PRINT_CONTENT_ANALYSIS) +#include "chrome/browser/enterprise/connectors/analysis/print_content_analysis_utils.h" +#endif + #if BUILDFLAG(IS_CHROMEOS) #include "chromeos/crosapi/mojom/local_printer.mojom.h" #endif @@ -751,8 +755,49 @@ } ReportUserActionHistogram(user_action); +#if BUILDFLAG(ENABLE_PRINT_CONTENT_ANALYSIS) + auto on_verdict = + base::BindOnce(&PrintPreviewHandler::OnVerdictByEnterprisePolicy, + weak_factory_.GetWeakPtr(), user_action, + std::move(settings), data, callback_id); + + auto hide_preview = base::BindOnce(&PrintPreviewUI::OnHidePreviewDialog, + print_preview_ui()->GetWeakPointer()); + + enterprise_connectors::PrintIfAllowedByPolicy( + data, GetInitiator(), std::move(on_verdict), std::move(hide_preview)); + +#else + FinishHandlePrint(user_action, std::move(settings), data, callback_id); +#endif // BUILDFLAG(ENABLE_PRINT_CONTENT_ANALYSIS) +} + +#if BUILDFLAG(ENABLE_PRINT_CONTENT_ANALYSIS) +void PrintPreviewHandler::OnVerdictByEnterprisePolicy( + UserActionBuckets user_action, + base::Value::Dict settings, + scoped_refptr<base::RefCountedMemory> data, + const std::string& callback_id, + bool allowed) { + if (allowed) { + FinishHandlePrint(user_action, std::move(settings), data, callback_id); + } else { + OnPrintResult(callback_id, base::Value("NOT_ALLOWED")); + } +} +#endif // BUILDFLAG(ENABLE_PRINT_CONTENT_ANALYSIS) + +void PrintPreviewHandler::FinishHandlePrint( + UserActionBuckets user_action, + base::Value::Dict settings, + scoped_refptr<base::RefCountedMemory> data, + const std::string& callback_id) { PrinterHandler* handler = GetPrinterHandler(GetPrinterTypeForUserAction(user_action)); + if (!handler) { + RejectJavascriptCallback(base::Value(callback_id), base::Value()); + return; + } handler->StartPrint(print_preview_ui()->initiator_title(), std::move(settings), data, base::BindOnce(&PrintPreviewHandler::OnPrintResult,
diff --git a/chrome/browser/ui/webui/print_preview/print_preview_handler.h b/chrome/browser/ui/webui/print_preview/print_preview_handler.h index ec48deb5..0af86668 100644 --- a/chrome/browser/ui/webui/print_preview/print_preview_handler.h +++ b/chrome/browser/ui/webui/print_preview/print_preview_handler.h
@@ -12,12 +12,16 @@ #include "base/containers/flat_map.h" #include "base/containers/flat_set.h" #include "base/files/file_path.h" +#include "base/functional/callback_forward.h" #include "base/gtest_prod_util.h" #include "base/memory/raw_ptr.h" +#include "base/memory/ref_counted_memory.h" +#include "base/memory/scoped_refptr.h" #include "base/memory/weak_ptr.h" #include "base/values.h" #include "build/build_config.h" #include "build/chromeos_buildflags.h" +#include "chrome/browser/ui/webui/print_preview/print_preview_metrics.h" #include "components/prefs/pref_service.h" #include "components/printing/common/print.mojom.h" #include "content/public/browser/web_ui_message_handler.h" @@ -117,6 +121,13 @@ // Gets the initiator for the print preview dialog. virtual content::WebContents* GetInitiator(); + // Initiates print after any content analysis checks have been passed + // successfully. + virtual void FinishHandlePrint(UserActionBuckets user_action, + base::Value::Dict settings, + scoped_refptr<base::RefCountedMemory> data, + const std::string& callback_id); + private: friend class PrintPreviewPdfGeneratedBrowserTest; FRIEND_TEST_ALL_PREFIXES(PrintPreviewPdfGeneratedBrowserTest, @@ -133,7 +144,8 @@ friend class PrintPreviewHandlerFailingTest; FRIEND_TEST_ALL_PREFIXES(PrintPreviewHandlerFailingTest, GetPrinterCapabilities); - + FRIEND_TEST_ALL_PREFIXES(ContentAnalysisPrintPreviewHandlerTest, + LocalScanBeforePrinting); content::WebContents* preview_web_contents(); PrintPreviewUI* print_preview_ui(); @@ -255,6 +267,17 @@ void OnPrintResult(const std::string& callback_id, const base::Value& error); +#if BUILDFLAG(ENABLE_PRINT_CONTENT_ANALYSIS) + // Called when enterprise policy returns a verdict. + // Calls FinishHandlePrint if it's allowed else calls OnPrintResult to report + // print not allowed. + void OnVerdictByEnterprisePolicy(UserActionBuckets user_action, + base::Value::Dict settings, + scoped_refptr<base::RefCountedMemory> data, + const std::string& callback_id, + bool allowed); +#endif // BUILDFLAG(ENABLE_PRINT_CONTENT_ANALYSIS) + // Whether we have already logged a failed print preview. bool reported_failed_preview_ = false;
diff --git a/chrome/browser/ui/webui/print_preview/print_preview_handler_unittest.cc b/chrome/browser/ui/webui/print_preview/print_preview_handler_unittest.cc index 8e11276..ce07fb3 100644 --- a/chrome/browser/ui/webui/print_preview/print_preview_handler_unittest.cc +++ b/chrome/browser/ui/webui/print_preview/print_preview_handler_unittest.cc
@@ -19,6 +19,7 @@ #include "base/strings/utf_string_conversions.h" #include "base/test/icu_test_util.h" #include "base/test/metrics/histogram_tester.h" +#include "base/test/scoped_feature_list.h" #include "base/test/values_test_util.h" #include "base/values.h" #include "build/build_config.h" @@ -42,12 +43,24 @@ #include "content/public/test/navigation_simulator.h" #include "content/public/test/test_renderer_host.h" #include "content/public/test/test_web_ui.h" +#include "printing/buildflags/buildflags.h" #include "printing/mojom/print.mojom.h" +#include "printing/printing_features.h" #include "testing/gtest/include/gtest/gtest.h" #include "third_party/abseil-cpp/absl/types/optional.h" -#if BUILDFLAG(IS_CHROMEOS) +#if BUILDFLAG(ENABLE_PRINT_CONTENT_ANALYSIS) +#include "chrome/browser/enterprise/connectors/analysis/fake_content_analysis_delegate.h" +#include "chrome/browser/enterprise/connectors/common.h" +#include "chrome/browser/policy/dm_token_utils.h" +#include "chrome/browser/safe_browsing/cloud_content_scanning/deep_scanning_test_utils.h" +#endif // BUILDFLAG(ENABLE_PRINT_CONTENT_ANALYSIS) + +#if BUILDFLAG(IS_CHROMEOS) || BUILDFLAG(ENABLE_PRINT_CONTENT_ANALYSIS) #include "chrome/test/base/testing_profile_manager.h" +#endif + +#if BUILDFLAG(IS_CHROMEOS) #include "chromeos/crosapi/mojom/local_printer.mojom.h" #endif @@ -72,6 +85,11 @@ const char kEmptyPrinterName[] = "EmptyPrinter"; const char kTestData[] = "abc"; +#if BUILDFLAG(ENABLE_PRINT_CONTENT_ANALYSIS) +constexpr char kFakeDmToken[] = "fake-dm-token"; +constexpr char kCallbackId[] = "test-callback-id-1"; +#endif // BUILDFLAG(ENABLE_PRINT_CONTENT_ANALYSIS) + // Array of all mojom::PrinterTypes. constexpr mojom::PrinterType kAllTypes[] = {mojom::PrinterType::kExtension, mojom::PrinterType::kPdf, @@ -393,6 +411,40 @@ const raw_ptr<content::WebContents> initiator_; }; +#if BUILDFLAG(ENABLE_PRINT_CONTENT_ANALYSIS) +class TestPrintPreviewHandlerForContentAnalysis + : public TestPrintPreviewHandler { + public: + TestPrintPreviewHandlerForContentAnalysis( + std::unique_ptr<PrinterHandler> printer_handler, + content::WebContents* web_contents) + : TestPrintPreviewHandler(std::move(printer_handler), web_contents) {} + + ~TestPrintPreviewHandlerForContentAnalysis() override = default; + + bool print_called_after_scan() const { return print_called_after_scan_; } + bool finish_handle_print_if_allowed_called() const { + return finish_handle_print_if_allowed_called_; + } + + protected: + void FinishHandlePrint(UserActionBuckets user_action, + base::Value::Dict settings, + scoped_refptr<base::RefCountedMemory> data, + const std::string& callback_id) override { + ASSERT_EQ(base::StringPiece(data->front_as<const char>(), data->size()), + kTestData); + print_called_after_scan_ = true; + PrintPreviewHandler::FinishHandlePrint(user_action, std::move(settings), + data, callback_id); + } + + private: + bool print_called_after_scan_ = false; + bool finish_handle_print_if_allowed_called_ = false; +}; +#endif // BUILDFLAG(ENABLE_PRINT_CONTENT_ANALYSIS) + } // namespace class PrintPreviewHandlerTest : public testing::Test { @@ -410,16 +462,16 @@ void AddToDenyList(const mojom::PrinterType& printer_type) { local_printer_.add_to_deny_list(printer_type); } +#endif void SetProfileForInitialSettings(TestingProfile* profile) { preview_web_contents_ = content::WebContents::Create( content::WebContents::CreateParams(profile)); web_ui_->set_web_contents(preview_web_contents_.get()); } -#endif void SetUp() override { -#if BUILDFLAG(IS_CHROMEOS) +#if BUILDFLAG(IS_CHROMEOS) || BUILDFLAG(ENABLE_PRINT_CONTENT_ANALYSIS) ASSERT_TRUE(testing_profile_manager_.SetUp()); #endif #if BUILDFLAG(IS_CHROMEOS_ASH) @@ -447,8 +499,7 @@ auto printer_handler = CreatePrinterHandler(printers_); printer_handler_ = printer_handler.get(); - auto preview_handler = std::make_unique<TestPrintPreviewHandler>( - std::move(printer_handler), initiator); + auto preview_handler = CreateHandler(std::move(printer_handler), initiator); handler_ = preview_handler.get(); handler_->set_web_ui(web_ui()); #if BUILDFLAG(IS_CHROMEOS_ASH) @@ -483,6 +534,13 @@ return std::make_unique<TestPrinterHandler>(printers); } + virtual std::unique_ptr<TestPrintPreviewHandler> CreateHandler( + std ::unique_ptr<TestPrinterHandler> printer_handler, + content::WebContents* web_contents) { + return std::make_unique<TestPrintPreviewHandler>(std::move(printer_handler), + web_contents); + } + void Initialize() { InitializeWithLocale("en"); } void InitializeWithLocale(const std::string& locale) { @@ -703,9 +761,10 @@ } content::TestWebUI* web_ui() { return web_ui_.get(); } TestPrintPreviewHandler* handler() { return handler_; } + TestingProfile* profile() { return &profile_; } TestPrinterHandler* printer_handler() { return printer_handler_; } std::vector<PrinterInfo>& printers() { return printers_; } -#if BUILDFLAG(IS_CHROMEOS) +#if BUILDFLAG(IS_CHROMEOS) || BUILDFLAG(ENABLE_PRINT_CONTENT_ANALYSIS) TestingProfileManager* testing_profile_manager() { return &testing_profile_manager_; } @@ -713,7 +772,7 @@ private: content::BrowserTaskEnvironment task_environment_; -#if BUILDFLAG(IS_CHROMEOS) +#if BUILDFLAG(IS_CHROMEOS) || BUILDFLAG(ENABLE_PRINT_CONTENT_ANALYSIS) TestingProfileManager testing_profile_manager_{ TestingBrowserProcess::GetGlobal()}; #endif @@ -1485,4 +1544,104 @@ } } +#if BUILDFLAG(ENABLE_PRINT_CONTENT_ANALYSIS) +class ContentAnalysisPrintPreviewHandlerTest + : public PrintPreviewHandlerTest, + public testing::WithParamInterface<bool> { + public: + ContentAnalysisPrintPreviewHandlerTest() { + feature_list_.InitAndEnableFeature(features::kEnablePrintScanAfterPreview); + } + + void SetUp() override { + enterprise_connectors::ContentAnalysisDelegate::SetFactoryForTesting( + base::BindRepeating( + &enterprise_connectors::FakeContentAnalysisDelegate::Create, + run_loop_.QuitClosure(), + base::BindRepeating( + &ContentAnalysisPrintPreviewHandlerTest::ScanningResponse, + base::Unretained(this)), + kFakeDmToken)); + + enterprise_connectors::ContentAnalysisDelegate::DisableUIForTesting(); + PrintPreviewHandlerTest::SetUp(); + TestingProfile* main_profile = + PrintPreviewHandlerTest::testing_profile_manager() + ->CreateTestingProfile("Main Profile", + /*is_main_profile=*/true); + PrintPreviewHandlerTest::SetProfileForInitialSettings(main_profile); + safe_browsing::SetAnalysisConnector( + profile()->GetPrefs(), enterprise_connectors::AnalysisConnector::PRINT, + R"({ + "service_provider": "local_system_agent", + "enable": [ {"url_list": ["*"], "tags": ["dlp"]} ], + "block_until_verdict": 1 + })"); + } + + std::unique_ptr<TestPrintPreviewHandler> CreateHandler( + std ::unique_ptr<TestPrinterHandler> printer_handler, + content::WebContents* web_contents) override { + return std::make_unique<TestPrintPreviewHandlerForContentAnalysis>( + std::move(printer_handler), web_contents); + } + + bool scanning_allows_print() const { return GetParam(); } + + enterprise_connectors::ContentAnalysisResponse ScanningResponse( + const std::string& content, + const base::FilePath& path) { + enterprise_connectors::ContentAnalysisResponse response; + + auto* result = response.add_results(); + result->set_tag("dlp"); + result->set_status( + enterprise_connectors::ContentAnalysisResponse::Result::SUCCESS); + + if (!scanning_allows_print()) { + auto* rule = result->add_triggered_rules(); + rule->set_rule_name("blocking_rule_name"); + rule->set_action(enterprise_connectors::TriggeredRule::BLOCK); + } + + return response; + } + + void WaitForScan() { run_loop_.Run(); } + + private: + base::test::ScopedFeatureList feature_list_; + base::RunLoop run_loop_; +}; + +TEST_P(ContentAnalysisPrintPreviewHandlerTest, LocalScanBeforePrinting) { + Initialize(); + + base::Value::List print_args; + print_args.Append(kCallbackId); + base::Value print_ticket(test::GetPrintTicket(kAllTypes[0])); + std::string json; + base::JSONWriter::Write(print_ticket, &json); + print_args.Append(json); + + handler()->HandlePrint(print_args); + WaitForScan(); + + auto* print_preview_handler = + static_cast<TestPrintPreviewHandlerForContentAnalysis*>(handler()); + + // Check if printing was allowed or not depending on the parameter. + ASSERT_EQ(print_preview_handler->print_called_after_scan(), + scanning_allows_print()); + + // Verify that printing went through or not based on the parameter. + const content::TestWebUI::CallData& data = *web_ui()->call_data().back(); + CheckWebUIResponse(data, kCallbackId, scanning_allows_print()); +} + +INSTANTIATE_TEST_SUITE_P(All, + ContentAnalysisPrintPreviewHandlerTest, + /*scanning_allows_print=*/testing::Bool()); + +#endif // BUILDFLAG(ENABLE_PRINT_CONTENT_ANALYSIS) } // namespace printing
diff --git a/chrome/browser/ui/webui/print_preview/print_preview_ui.cc b/chrome/browser/ui/webui/print_preview/print_preview_ui.cc index e8a5af6..f0cab77 100644 --- a/chrome/browser/ui/webui/print_preview/print_preview_ui.cc +++ b/chrome/browser/ui/webui/print_preview/print_preview_ui.cc
@@ -478,6 +478,10 @@ id_.reset(); } +base::WeakPtr<PrintPreviewUI> PrintPreviewUI::GetWeakPointer() { + return weak_ptr_factory_.GetWeakPtr(); +} + void PrintPreviewUI::GetPrintPreviewDataForIndex( int index, scoped_refptr<base::RefCountedMemory>* data) const {
diff --git a/chrome/browser/ui/webui/print_preview/print_preview_ui.h b/chrome/browser/ui/webui/print_preview/print_preview_ui.h index 4ec4981..d76a7718 100644 --- a/chrome/browser/ui/webui/print_preview/print_preview_ui.h +++ b/chrome/browser/ui/webui/print_preview/print_preview_ui.h
@@ -206,6 +206,8 @@ // OnJavascriptDisallowed(). void ClearPreviewUIId(); + base::WeakPtr<PrintPreviewUI> GetWeakPointer(); + protected: // Alternate constructor for tests PrintPreviewUI(content::WebUI* web_ui,
diff --git a/chrome/browser/ui/webui/settings/people_handler_unittest.cc b/chrome/browser/ui/webui/settings/people_handler_unittest.cc index b7cf7fa..96f5807 100644 --- a/chrome/browser/ui/webui/settings/people_handler_unittest.cc +++ b/chrome/browser/ui/webui/settings/people_handler_unittest.cc
@@ -384,7 +384,8 @@ handler_->DisallowJavascript(); ON_CALL(*mock_sync_service_, GetDisableReasons()) - .WillByDefault(Return(syncer::SyncService::DISABLE_REASON_NOT_SIGNED_IN)); + .WillByDefault(Return(syncer::SyncService::DisableReasonSet( + {syncer::SyncService::DISABLE_REASON_NOT_SIGNED_IN}))); ON_CALL(*mock_sync_service_->GetMockUserSettings(), IsInitialSyncFeatureSetupComplete()) .WillByDefault(Return(false)); @@ -518,7 +519,8 @@ // Clearing sync from the dashboard results in DISABLE_REASON_USER_CHOICE // being set. ON_CALL(*mock_sync_service_, GetDisableReasons()) - .WillByDefault(Return(syncer::SyncService::DISABLE_REASON_USER_CHOICE)); + .WillByDefault(Return(syncer::SyncService::DisableReasonSet( + {syncer::SyncService::DISABLE_REASON_USER_CHOICE}))); ON_CALL(*mock_sync_service_, IsSyncFeatureDisabledViaDashboard()) .WillByDefault(Return(true)); ON_CALL(*mock_sync_service_, GetTransportState()) @@ -552,7 +554,8 @@ // being set. However, the sync engine has restarted in standalone transport // mode. ON_CALL(*mock_sync_service_, GetDisableReasons()) - .WillByDefault(Return(syncer::SyncService::DISABLE_REASON_USER_CHOICE)); + .WillByDefault(Return(syncer::SyncService::DisableReasonSet( + {syncer::SyncService::DISABLE_REASON_USER_CHOICE}))); ON_CALL(*mock_sync_service_, IsSyncFeatureDisabledViaDashboard()) .WillByDefault(Return(true)); ON_CALL(*mock_sync_service_, GetTransportState()) @@ -615,8 +618,8 @@ SigninUser(); CreatePeopleHandler(); ON_CALL(*mock_sync_service_, GetDisableReasons()) - .WillByDefault( - Return(syncer::SyncService::DISABLE_REASON_UNRECOVERABLE_ERROR)); + .WillByDefault(Return(syncer::SyncService::DisableReasonSet( + {syncer::SyncService::DISABLE_REASON_UNRECOVERABLE_ERROR}))); ON_CALL(*mock_sync_service_->GetMockUserSettings(), IsInitialSyncFeatureSetupComplete()) .WillByDefault(Return(false)); @@ -630,7 +633,8 @@ SigninUser(); CreatePeopleHandler(); ON_CALL(*mock_sync_service_, GetDisableReasons()) - .WillByDefault(Return(syncer::SyncService::DISABLE_REASON_NOT_SIGNED_IN)); + .WillByDefault(Return(syncer::SyncService::DisableReasonSet( + {syncer::SyncService::DISABLE_REASON_NOT_SIGNED_IN}))); ON_CALL(*mock_sync_service_->GetMockUserSettings(), IsInitialSyncFeatureSetupComplete()) .WillByDefault(Return(false)); @@ -930,7 +934,7 @@ ON_CALL(*mock_sync_service_->GetMockUserSettings(), IsSyncEverythingEnabled()) .WillByDefault(Return(false)); - syncer::UserSelectableTypeSet types(type); + const syncer::UserSelectableTypeSet types = {type}; ON_CALL(*mock_sync_service_->GetMockUserSettings(), GetSelectedTypes()) .WillByDefault(Return(types)); @@ -1132,7 +1136,8 @@ // data" link), which results in the sync-requested and first-setup-complete // bits being cleared. ON_CALL(*mock_sync_service_, GetDisableReasons()) - .WillByDefault(Return(syncer::SyncService::DISABLE_REASON_USER_CHOICE)); + .WillByDefault(Return(syncer::SyncService::DisableReasonSet( + {syncer::SyncService::DISABLE_REASON_USER_CHOICE}))); ON_CALL(*mock_sync_service_, IsSyncFeatureDisabledViaDashboard()) .WillByDefault(Return(true)); ON_CALL(*mock_sync_service_->GetMockUserSettings(), @@ -1187,7 +1192,8 @@ // data" link), which results in the sync-requested and first-setup-complete // bits being cleared. ON_CALL(*mock_sync_service_, GetDisableReasons()) - .WillByDefault(Return(syncer::SyncService::DISABLE_REASON_USER_CHOICE)); + .WillByDefault(Return(syncer::SyncService::DisableReasonSet( + {syncer::SyncService::DISABLE_REASON_USER_CHOICE}))); ON_CALL(*mock_sync_service_, IsSyncFeatureDisabledViaDashboard()) .WillByDefault(Return(true)); ON_CALL(*mock_sync_service_->GetMockUserSettings(),
diff --git a/chrome/browser/ui/webui/signin/turn_sync_on_helper_unittest.cc b/chrome/browser/ui/webui/signin/turn_sync_on_helper_unittest.cc index b9cb3a32..44ca0541 100644 --- a/chrome/browser/ui/webui/signin/turn_sync_on_helper_unittest.cc +++ b/chrome/browser/ui/webui/signin/turn_sync_on_helper_unittest.cc
@@ -623,7 +623,7 @@ syncer::MockSyncService* mock_sync_service = GetMockSyncService(profile); ON_CALL(*mock_sync_service, GetDisableReasons()) .WillByDefault(Return(syncer::SyncService::DisableReasonSet( - syncer::SyncService::DISABLE_REASON_ENTERPRISE_POLICY))); + {syncer::SyncService::DISABLE_REASON_ENTERPRISE_POLICY}))); } void SetExpectationsForSyncAborted() {
diff --git a/chrome/browser/updater/browser_updater_client_mac.mm b/chrome/browser/updater/browser_updater_client_mac.mm index b692548c..57f35934 100644 --- a/chrome/browser/updater/browser_updater_client_mac.mm +++ b/chrome/browser/updater/browser_updater_client_mac.mm
@@ -6,7 +6,7 @@ #include <string> -#include "base/mac/bundle_locations.h" +#include "base/apple/bundle_locations.h" #include "base/mac/foundation_util.h" #include "base/strings/strcat.h" #include "chrome/browser/google/google_brand.h" @@ -19,7 +19,7 @@ std::string GetTag() { std::string contents; base::ReadFileToString( - base::mac::OuterBundlePath().Append(".want_full_installer"), &contents); + base::apple::OuterBundlePath().Append(".want_full_installer"), &contents); return base::StrCat( {chrome::GetChannelName(chrome::WithExtendedStable(true)), contents == version_info::GetVersionNumber() ? "-full" : ""}); @@ -37,6 +37,6 @@ google_brand::GetBrand(&req.brand_code); req.version = base::Version(version_info::GetVersionNumber()); req.ap = GetTag(); - req.existence_checker_path = base::mac::OuterBundlePath(); + req.existence_checker_path = base::apple::OuterBundlePath(); return req; }
diff --git a/chrome/browser/updater/browser_updater_client_util_mac.mm b/chrome/browser/updater/browser_updater_client_util_mac.mm index fb7c4aa..139cb509 100644 --- a/chrome/browser/updater/browser_updater_client_util_mac.mm +++ b/chrome/browser/updater/browser_updater_client_util_mac.mm
@@ -12,6 +12,7 @@ #include <sys/stat.h> #include <unistd.h> +#include "base/apple/bundle_locations.h" #include "base/command_line.h" #include "base/files/file_enumerator.h" #include "base/files/file_path.h" @@ -20,7 +21,6 @@ #include "base/functional/callback.h" #include "base/logging.h" #include "base/mac/authorization_util.h" -#include "base/mac/bundle_locations.h" #include "base/mac/foundation_util.h" #include "base/mac/scoped_authorizationref.h" #include "base/memory/scoped_refptr.h" @@ -54,7 +54,7 @@ } bool BundleOwnedByUser(uid_t user_uid) { - const base::FilePath path = base::mac::OuterBundlePath(); + const base::FilePath path = base::apple::OuterBundlePath(); base::stat_wrapper_t stat_info = {}; if (base::File::Lstat(path.value().c_str(), &stat_info) != 0) { VPLOG(2) << "Failed to get information on path " << path.value(); @@ -169,7 +169,7 @@ // BRANDING.app/Contents/Frameworks/BRANDING.framework/Versions/V/ // Helpers/Updater.app/Contents/MacOS/Updater const base::FilePath updater_executable_path = - base::mac::FrameworkBundlePath() + base::apple::FrameworkBundlePath() .Append(FILE_PATH_LITERAL("Helpers")) .Append(GetUpdaterExecutablePath()); @@ -199,7 +199,7 @@ } // namespace std::string CurrentlyInstalledVersion() { - base::FilePath outer_bundle = base::mac::OuterBundlePath(); + base::FilePath outer_bundle = base::apple::OuterBundlePath(); base::FilePath plist_path = outer_bundle.Append("Contents").Append("Info.plist"); NSDictionary* info_plist = [NSDictionary
diff --git a/chrome/browser/updater/browser_updater_helper_client_mac.mm b/chrome/browser/updater/browser_updater_helper_client_mac.mm index bde9c33..e9fbbb9 100644 --- a/chrome/browser/updater/browser_updater_helper_client_mac.mm +++ b/chrome/browser/updater/browser_updater_helper_client_mac.mm
@@ -6,10 +6,10 @@ #import <Foundation/Foundation.h> +#include "base/apple/bundle_locations.h" #include "base/functional/bind.h" #include "base/functional/callback.h" #include "base/logging.h" -#include "base/mac/bundle_locations.h" #include "base/mac/foundation_util.h" #include "base/mac/scoped_nsobject.h" #include "base/memory/scoped_refptr.h" @@ -70,7 +70,7 @@ [[xpc_connection_ remoteObjectProxyWithErrorHandler:errorHandler] setupSystemUpdaterWithBrowserPath:base::mac::FilePathToNSString( - base::mac::OuterBundlePath()) + base::apple::OuterBundlePath()) reply:reply]; }
diff --git a/chrome/browser/upgrade_detector/directory_monitor.cc b/chrome/browser/upgrade_detector/directory_monitor.cc index 251b452..df98934 100644 --- a/chrome/browser/upgrade_detector/directory_monitor.cc +++ b/chrome/browser/upgrade_detector/directory_monitor.cc
@@ -22,14 +22,14 @@ #include "chrome/browser/upgrade_detector/installed_version_monitor.h" #if BUILDFLAG(IS_MAC) -#include "base/mac/bundle_locations.h" +#include "base/apple/bundle_locations.h" #endif namespace { base::FilePath GetDefaultMonitorLocation() { #if BUILDFLAG(IS_MAC) - return base::mac::OuterBundlePath(); + return base::apple::OuterBundlePath(); #else return base::PathService::CheckedGet(base::DIR_EXE); #endif
diff --git a/chrome/browser/web_applications/os_integration/web_app_shortcut_mac.mm b/chrome/browser/web_applications/os_integration/web_app_shortcut_mac.mm index bdb27ef..cb1fbca 100644 --- a/chrome/browser/web_applications/os_integration/web_app_shortcut_mac.mm +++ b/chrome/browser/web_applications/os_integration/web_app_shortcut_mac.mm
@@ -13,6 +13,7 @@ #include <string> #include <utility> +#include "base/apple/bundle_locations.h" #include "base/base_switches.h" #include "base/check_is_test.h" #include "base/command_line.h" @@ -25,7 +26,6 @@ #include "base/functional/callback.h" #include "base/functional/callback_helpers.h" #include "base/logging.h" -#include "base/mac/bundle_locations.h" #include "base/mac/foundation_util.h" #import "base/mac/launch_application.h" #include "base/mac/mac_util.h" @@ -382,15 +382,15 @@ app_mode::kLaunchedByChromeProcessId, base::NumberToString(base::GetCurrentProcId())); command_line.AppendSwitchPath(app_mode::kLaunchedByChromeBundlePath, - base::mac::MainBundlePath()); + base::apple::MainBundlePath()); // When running unbundled (e.g, when running browser_tests), the path - // returned by base::mac::FrameworkBundlePath will not include the version. + // returned by base::apple::FrameworkBundlePath will not include the version. // Manually append it. // https://crbug.com/1286681 const base::FilePath framework_bundle_path = - base::mac::AmIBundled() ? base::mac::FrameworkBundlePath() - : base::mac::FrameworkBundlePath() + base::mac::AmIBundled() ? base::apple::FrameworkBundlePath() + : base::apple::FrameworkBundlePath() .Append("Versions") .Append(version_info::GetVersionNumber()); command_line.AppendSwitchPath(app_mode::kLaunchedByChromeFrameworkBundlePath, @@ -1129,7 +1129,8 @@ return false; } - const base::FilePath framework_bundle_path = base::mac::FrameworkBundlePath(); + const base::FilePath framework_bundle_path = + base::apple::FrameworkBundlePath(); const base::FilePath executable_path = framework_bundle_path.Append("Helpers").Append("app_mode_loader");
diff --git a/chrome/build/mac-arm.pgo.txt b/chrome/build/mac-arm.pgo.txt index 5a4abfd..2cefa8ad 100644 --- a/chrome/build/mac-arm.pgo.txt +++ b/chrome/build/mac-arm.pgo.txt
@@ -1 +1 @@ -chrome-mac-arm-main-1683907023-a0d824eeab5b4e755c0e0ed6672ab52783626651.profdata +chrome-mac-arm-main-1683914360-1e5c2bc64b4f166fa786bcb8e4933d21e810159b.profdata
diff --git a/chrome/build/win32.pgo.txt b/chrome/build/win32.pgo.txt index 41d068c..29fe9b102 100644 --- a/chrome/build/win32.pgo.txt +++ b/chrome/build/win32.pgo.txt
@@ -1 +1 @@ -chrome-win32-main-1683892723-b416ad1cb12179f88068b9a4c3382da72708ea46.profdata +chrome-win32-main-1683903455-59a6336338ddc55af0cbd1a108d49fcbaa95dd82.profdata
diff --git a/chrome/build/win64.pgo.txt b/chrome/build/win64.pgo.txt index d53f14f..94572c2 100644 --- a/chrome/build/win64.pgo.txt +++ b/chrome/build/win64.pgo.txt
@@ -1 +1 @@ -chrome-win64-main-1683892723-dce52e39bac402aff6d3afd909483f2e4b8a1af4.profdata +chrome-win64-main-1683914360-1c1f9764dbe340c4b1a45fb624c6d9c4cffd3794.profdata
diff --git a/chrome/common/channel_info_mac.mm b/chrome/common/channel_info_mac.mm index 906139f..ddbcdf9b 100644 --- a/chrome/common/channel_info_mac.mm +++ b/chrome/common/channel_info_mac.mm
@@ -8,8 +8,8 @@ #include <tuple> +#include "base/apple/bundle_locations.h" #include "base/check.h" -#include "base/mac/bundle_locations.h" #include "base/no_destructor.h" #include "base/strings/sys_string_conversions.h" #include "build/branding_buildflags.h" @@ -68,7 +68,7 @@ ChannelState DetermineChannelState() { // Use the main Chrome application bundle and not the framework bundle. // Keystone keys don't live in the framework. - NSBundle* bundle = base::mac::OuterBundle(); + NSBundle* bundle = base::apple::OuterBundle(); if (![bundle objectForInfoDictionaryKey:@"KSProductID"]) { // This build is not Keystone-enabled; it can't have a channel. @@ -103,7 +103,7 @@ static const bool capable = [] { // Use the main Chrome application bundle and not the framework bundle. // Keystone keys don't live in the framework. - NSBundle* bundle = base::mac::OuterBundle(); + NSBundle* bundle = base::apple::OuterBundle(); if (![bundle objectForInfoDictionaryKey:@"KSProductID"]) { // This build is not Keystone-enabled, and without a channel assume it is // side-by-side capable.
diff --git a/chrome/common/chrome_paths.cc b/chrome/common/chrome_paths.cc index b6a56e6..beefbf50 100644 --- a/chrome/common/chrome_paths.cc +++ b/chrome/common/chrome_paths.cc
@@ -29,7 +29,7 @@ #endif #if BUILDFLAG(IS_MAC) -#include "base/mac/bundle_locations.h" +#include "base/apple/bundle_locations.h" #include "base/mac/foundation_util.h" #endif @@ -236,7 +236,7 @@ #endif case chrome::DIR_RESOURCES: #if BUILDFLAG(IS_MAC) - cur = base::mac::FrameworkBundlePath(); + cur = base::apple::FrameworkBundlePath(); cur = cur.Append(FILE_PATH_LITERAL("Resources")); #else if (!base::PathService::Get(base::DIR_ASSETS, &cur)) @@ -337,7 +337,7 @@ case chrome::FILE_RESOURCES_PACK: // Falls through. case chrome::FILE_DEV_UI_RESOURCES_PACK: #if BUILDFLAG(IS_MAC) - cur = base::mac::FrameworkBundlePath(); + cur = base::apple::FrameworkBundlePath(); cur = cur.Append(FILE_PATH_LITERAL("Resources")) .Append(FILE_PATH_LITERAL("resources.pak")); #elif BUILDFLAG(IS_ANDROID) @@ -475,7 +475,7 @@ return false; #else #if BUILDFLAG(IS_MAC) - cur = base::mac::FrameworkBundlePath(); + cur = base::apple::FrameworkBundlePath(); cur = cur.Append(FILE_PATH_LITERAL("Default Apps")); #else if (!base::PathService::Get(base::DIR_MODULE, &cur))
diff --git a/chrome/common/chrome_paths_mac.mm b/chrome/common/chrome_paths_mac.mm index d8ee646..bbf53800 100644 --- a/chrome/common/chrome_paths_mac.mm +++ b/chrome/common/chrome_paths_mac.mm
@@ -84,7 +84,7 @@ // in the main app's bundle because it will be set differently on the canary // channel, and the autoupdate system dictates that there can be no // differences between channels within the versioned directory. This would - // normally use base::mac::FrameworkBundle(), but that references the + // normally use base::apple::FrameworkBundle(), but that references the // framework bundle within the versioned directory. Ordinarily, the profile // should not be accessed from non-browser processes, but those processes do // attempt to get the profile directory, so direct them to look in the outer
diff --git a/chrome/common/media/cdm_host_file_path.cc b/chrome/common/media/cdm_host_file_path.cc index 5bcf246..e89a23c 100644 --- a/chrome/common/media/cdm_host_file_path.cc +++ b/chrome/common/media/cdm_host_file_path.cc
@@ -16,7 +16,7 @@ #include "chrome/common/chrome_version.h" #if BUILDFLAG(IS_MAC) -#include "base/mac/bundle_locations.h" +#include "base/apple/bundle_locations.h" #endif #if BUILDFLAG(GOOGLE_CHROME_BRANDING) @@ -75,7 +75,7 @@ #elif BUILDFLAG(IS_MAC) - base::FilePath framework_dir = base::mac::FrameworkBundlePath(); + base::FilePath framework_dir = base::apple::FrameworkBundlePath(); base::FilePath chrome_framework_path = framework_dir.Append(chrome::kFrameworkExecutableName); // The signature file lives inside
diff --git a/chrome/services/mac_notifications/mac_notification_service_ns_unittest.mm b/chrome/services/mac_notifications/mac_notification_service_ns_unittest.mm index d51d6a7..1bb005a 100644 --- a/chrome/services/mac_notifications/mac_notification_service_ns_unittest.mm +++ b/chrome/services/mac_notifications/mac_notification_service_ns_unittest.mm
@@ -9,8 +9,8 @@ #include <utility> #include <vector> +#include "base/apple/bundle_locations.h" #include "base/barrier_closure.h" -#include "base/mac/bundle_locations.h" #include "base/run_loop.h" #include "base/strings/sys_string_conversions.h" #include "base/test/bind.h"
diff --git a/chrome/services/mac_notifications/mac_notification_service_un_unittest.mm b/chrome/services/mac_notifications/mac_notification_service_un_unittest.mm index a3c3d0f..a143fea 100644 --- a/chrome/services/mac_notifications/mac_notification_service_un_unittest.mm +++ b/chrome/services/mac_notifications/mac_notification_service_un_unittest.mm
@@ -8,7 +8,7 @@ #include <utility> #include <vector> -#include "base/mac/bundle_locations.h" +#include "base/apple/bundle_locations.h" #include "base/run_loop.h" #include "base/strings/sys_string_conversions.h" #include "base/test/bind.h" @@ -488,7 +488,7 @@ if (@available(macOS 10.14, *)) { base::HistogramTester histogram_tester; id mainBundleMock = - [OCMockObject partialMockForObject:base::mac::MainBundle()]; + [OCMockObject partialMockForObject:base::apple::MainBundle()]; // Mock the alert style to "alert" and verify we log the correct metrics. [[[mainBundleMock stub] @@ -513,7 +513,7 @@ if (@available(macOS 10.14, *)) { base::HistogramTester histogram_tester; id mainBundleMock = - [OCMockObject partialMockForObject:base::mac::MainBundle()]; + [OCMockObject partialMockForObject:base::apple::MainBundle()]; // Mock the alert style to "banner" and verify we log the correct metrics. [[[mainBundleMock stub]
diff --git a/chrome/services/mac_notifications/public/cpp/mac_notification_metrics.mm b/chrome/services/mac_notifications/public/cpp/mac_notification_metrics.mm index 5116e36d..24d21e0 100644 --- a/chrome/services/mac_notifications/public/cpp/mac_notification_metrics.mm +++ b/chrome/services/mac_notifications/public/cpp/mac_notification_metrics.mm
@@ -6,7 +6,7 @@ #import <Foundation/Foundation.h> -#include "base/mac/bundle_locations.h" +#include "base/apple/bundle_locations.h" #include "base/metrics/histogram_functions.h" #include "base/strings/strcat.h" @@ -17,7 +17,7 @@ namespace mac_notifications { bool IsAppBundleAlertStyle() { - NSDictionary* infoDictionary = [base::mac::MainBundle() infoDictionary]; + NSDictionary* infoDictionary = [base::apple::MainBundle() infoDictionary]; NSString* alertStyle = infoDictionary[@"NSUserNotificationAlertStyle"]; return [alertStyle isEqualToString:@"alert"]; }
diff --git a/chrome/services/sharing/nearby/quick_start_decoder/quick_start_decoder.cc b/chrome/services/sharing/nearby/quick_start_decoder/quick_start_decoder.cc index fb7d9fe..ddeb32fd 100644 --- a/chrome/services/sharing/nearby/quick_start_decoder/quick_start_decoder.cc +++ b/chrome/services/sharing/nearby/quick_start_decoder/quick_start_decoder.cc
@@ -66,6 +66,10 @@ // verification constexpr char kIsFirstUserVerificationKey[] = "is_first_user_verification"; +// Key in UserVerificationRequested indicating if user verification was +// requested +constexpr char kAwaitingUserVerificationKey[] = "awaiting_user_verification"; + std::pair<int, absl::optional<cbor::Value>> CborDecodeGetAssertionResponse( base::span<const uint8_t> response) { cbor::Reader::DecoderError error; @@ -239,6 +243,35 @@ DoDecodeWifiCredentialsResponse(data, std::move(callback)); } +void QuickStartDecoder::DecodeUserVerificationRequested( + const std::vector<uint8_t>& data, + DecodeUserVerificationRequestedCallback callback) { + std::unique_ptr<ash::quick_start::QuickStartMessage> message = + QuickStartMessage::ReadMessage(data, + QuickStartMessageType::kQuickStartPayload); + if (!message) { + LOG(ERROR) + << "Failed to read UserVerificationRequested as QuickStartMessage"; + std::move(callback).Run(nullptr, + mojom::QuickStartDecoderError::kUnableToReadAsJSON); + return; + } + + absl::optional<bool> is_awaiting_user_verification = + message->GetPayload()->FindBool(kAwaitingUserVerificationKey); + if (!is_awaiting_user_verification.has_value()) { + LOG(ERROR) << "UserVerificationRequested message does not include " + "await_user_verification."; + std::move(callback).Run( + nullptr, mojom::QuickStartDecoderError::kMessageDoesNotMatchSchema); + return; + } + + std::move(callback).Run(mojom::UserVerificationRequested::New( + is_awaiting_user_verification.value()), + absl::nullopt); +} + void QuickStartDecoder::DecodeUserVerificationResult( const std::vector<uint8_t>& data, DecodeUserVerificationResultCallback callback) {
diff --git a/chrome/services/sharing/nearby/quick_start_decoder/quick_start_decoder.h b/chrome/services/sharing/nearby/quick_start_decoder/quick_start_decoder.h index fcfe5bdbb..e1a3d460 100644 --- a/chrome/services/sharing/nearby/quick_start_decoder/quick_start_decoder.h +++ b/chrome/services/sharing/nearby/quick_start_decoder/quick_start_decoder.h
@@ -49,6 +49,10 @@ void DecodeUserVerificationResult( const std::vector<uint8_t>& data, DecodeUserVerificationResultCallback callback) override; + + void DecodeUserVerificationRequested( + const std::vector<uint8_t>& data, + DecodeUserVerificationRequestedCallback callback) override; // mojom::QuickStartDecoder: private:
diff --git a/chrome/services/sharing/nearby/quick_start_decoder/quick_start_decoder_unittest.cc b/chrome/services/sharing/nearby/quick_start_decoder/quick_start_decoder_unittest.cc index 4f1842c..f586988 100644 --- a/chrome/services/sharing/nearby/quick_start_decoder/quick_start_decoder_unittest.cc +++ b/chrome/services/sharing/nearby/quick_start_decoder/quick_start_decoder_unittest.cc
@@ -64,6 +64,10 @@ // verification constexpr char kIsFirstUserVerificationKey[] = "is_first_user_verification"; +// Key in UserVerificationRequested indicating if user verification was +// requestedait +constexpr char kAwaitingUserVerificationKey[] = "awaiting_user_verification"; + constexpr int kUserVerifiedStatusCode = 0; const std::vector<uint8_t> kValidCredentialId = {0x01, 0x02, 0x03}; @@ -710,4 +714,39 @@ mojom::QuickStartDecoderError::kMessageDoesNotMatchSchema); } +TEST_F(QuickStartDecoderTest, DecodeUserVerificationRequestSucceeds) { + QuickStartMessage message(QuickStartMessageType::kQuickStartPayload); + message.GetPayload()->Set(kAwaitingUserVerificationKey, true); + + base::test::TestFuture< + ::ash::quick_start::mojom::UserVerificationRequestedPtr, + absl::optional<::ash::quick_start::mojom::QuickStartDecoderError>> + future; + + decoder()->DecodeUserVerificationRequested(ConvertMessageToBytes(&message), + future.GetCallback()); + + EXPECT_TRUE(future.IsReady()); + ASSERT_FALSE(future.Get<0>().is_null()); + EXPECT_TRUE(future.Get<0>().get()->is_awaiting_user_verification); + EXPECT_EQ(future.Get<1>(), absl::nullopt); +} + +TEST_F(QuickStartDecoderTest, DecodeUserVerificationRequestFailsIfKeyMissing) { + QuickStartMessage message(QuickStartMessageType::kQuickStartPayload); + + base::test::TestFuture< + ::ash::quick_start::mojom::UserVerificationRequestedPtr, + absl::optional<::ash::quick_start::mojom::QuickStartDecoderError>> + future; + + decoder()->DecodeUserVerificationRequested(ConvertMessageToBytes(&message), + future.GetCallback()); + + EXPECT_TRUE(future.IsReady()); + EXPECT_TRUE(future.Get<0>().is_null()); + EXPECT_EQ(future.Get<1>(), + mojom::QuickStartDecoderError::kMessageDoesNotMatchSchema); +} + } // namespace ash::quick_start
diff --git a/chrome/test/base/chrome_test_launcher.cc b/chrome/test/base/chrome_test_launcher.cc index e78c7d6c..6c6a81f 100644 --- a/chrome/test/base/chrome_test_launcher.cc +++ b/chrome/test/base/chrome_test_launcher.cc
@@ -45,7 +45,7 @@ #include "ui/base/test/ui_controls.h" #if BUILDFLAG(IS_MAC) -#include "base/mac/bundle_locations.h" +#include "base/apple/bundle_locations.h" #include "chrome/browser/chrome_browser_application_mac.h" #endif // BUILDFLAG(IS_MAC) @@ -254,7 +254,7 @@ base::FilePath path; CHECK(base::PathService::Get(base::DIR_EXE, &path)); path = path.Append(chrome::kFrameworkName); - base::mac::SetOverrideFrameworkBundlePath(path); + base::apple::SetOverrideFrameworkBundlePath(path); #endif #if BUILDFLAG(IS_WIN)
diff --git a/chrome/test/base/chrome_test_suite.cc b/chrome/test/base/chrome_test_suite.cc index 4556fd4..6fdac11 100644 --- a/chrome/test/base/chrome_test_suite.cc +++ b/chrome/test/base/chrome_test_suite.cc
@@ -40,7 +40,7 @@ #endif // BUILDFLAG(IS_CHROMEOS_LACROS) #if BUILDFLAG(IS_MAC) -#include "base/mac/bundle_locations.h" +#include "base/apple/bundle_locations.h" #include "base/mac/scoped_nsautorelease_pool.h" #include "chrome/browser/chrome_browser_application_mac.h" #endif @@ -107,7 +107,7 @@ base::FilePath path; base::PathService::Get(base::DIR_EXE, &path); path = path.Append(chrome::kFrameworkName); - base::mac::SetOverrideFrameworkBundlePath(path); + base::apple::SetOverrideFrameworkBundlePath(path); #endif #if BUILDFLAG(IS_CHROMEOS_LACROS) @@ -132,7 +132,7 @@ void ChromeTestSuite::Shutdown() { #if BUILDFLAG(IS_MAC) - base::mac::SetOverrideFrameworkBundlePath({}); + base::apple::SetOverrideFrameworkBundlePath({}); #endif content::ContentTestSuiteBase::Shutdown();
diff --git a/chrome/test/chromedriver/session_commands_unittest.cc b/chrome/test/chromedriver/session_commands_unittest.cc index 40b6135..1c4add2 100644 --- a/chrome/test/chromedriver/session_commands_unittest.cc +++ b/chrome/test/chromedriver/session_commands_unittest.cc
@@ -476,11 +476,8 @@ base::Value::List args; args.Append("headless"); caps.SetByDottedPath("goog:chromeOptions.args", base::Value(std::move(args))); - - base::Value::Dict prefs; - prefs.SetByDottedPath("download.default_directory", - base::Value("/examples/python/downloads")); - caps.SetByDottedPath("goog:chromeOptions.prefs", prefs.Clone()); + caps.SetByDottedPath("goog:chromeOptions.prefs.download.default_directory", + "/examples/python/downloads"); Status status = capabilities.Parse(caps); BrowserInfo binfo; @@ -501,11 +498,8 @@ base::Value::List args; args.Append("headless"); caps.SetByDottedPath("goog:chromeOptions.args", base::Value(std::move(args))); - - base::Value* prefs = - caps.SetByDottedPath("goog:chromeOptions.prefs", base::Value::Dict()); - base::Value::Dict* download = prefs->GetDict().EnsureDict("download"); - download->Set("default_directory", "/examples/python/downloads"); + caps.SetByDottedPath("goog:chromeOptions.prefs.download.default_directory", + "/examples/python/downloads"); Status status = capabilities.Parse(caps); BrowserInfo binfo; @@ -542,10 +536,8 @@ TEST(SessionCommandsTest, ConfigureHeadlessSession_notHeadless) { Capabilities capabilities; base::Value::Dict caps; - base::Value* prefs = - caps.SetByDottedPath("goog:chromeOptions.prefs", base::Value::Dict()); - base::Value::Dict* download = prefs->GetDict().EnsureDict("download"); - download->Set("default_directory", "/examples/python/downloads"); + caps.SetByDottedPath("goog:chromeOptions.prefs.download.default_directory", + "/examples/python/downloads"); Status status = capabilities.Parse(caps); BrowserInfo binfo;
diff --git a/chrome/test/data/android/environment_integrity.html b/chrome/test/data/android/environment_integrity.html new file mode 100644 index 0000000..095f9fc --- /dev/null +++ b/chrome/test/data/android/environment_integrity.html
@@ -0,0 +1,26 @@ +<!DOCTYPE html> +<html> + <head> + <title>getEnvironmentIntegrity</title> + <script> + function doGetEnvironmentIntegrity(contentBinding) { + if (navigator.getEnvironmentIntegrity === undefined) { + window.document.title = 'Fail: navigator.getEnvironmentIntegrity === undefined'; + return; + } + + navigator.getEnvironmentIntegrity(contentBinding).then(token => { + if (token.encode() === '') { + window.document.title = 'Success'; + } else { + window.document.title = 'Fail: token.encode() returned an incorrect value'; + } + }).catch(e => { + window.document.title = 'Fail: ' + e; + }); + } + </script> + </head> + <body> + </body> +</html>
diff --git a/chrome/test/data/webui/chromeos/personalization_app/wallpaper_collections_element_test.ts b/chrome/test/data/webui/chromeos/personalization_app/wallpaper_collections_element_test.ts index 744f60f..aeccf595 100644 --- a/chrome/test/data/webui/chromeos/personalization_app/wallpaper_collections_element_test.ts +++ b/chrome/test/data/webui/chromeos/personalization_app/wallpaper_collections_element_test.ts
@@ -5,9 +5,9 @@ import 'chrome://personalization/strings.m.js'; import 'chrome://webui-test/mojo_webui_test_support.js'; -import {emptyState, GooglePhotosEnablementState, kDefaultImageSymbol, PersonalizationRouter, WallpaperActionName, WallpaperCollections, WallpaperGridItem} from 'chrome://personalization/js/personalization_app.js'; +import {emptyState, GooglePhotosEnablementState, kDefaultImageSymbol, PersonalizationRouter, WallpaperActionName, WallpaperCollections, WallpaperGridItem, WallpaperImage} from 'chrome://personalization/js/personalization_app.js'; import {loadTimeData} from 'chrome://resources/js/load_time_data.js'; -import {assertDeepEquals, assertEquals, assertTrue} from 'chrome://webui-test/chai_assert.js'; +import {assertDeepEquals, assertEquals, assertGE, assertTrue} from 'chrome://webui-test/chai_assert.js'; import {waitAfterNextRender} from 'chrome://webui-test/polymer_test_util.js'; import {TestMock} from 'chrome://webui-test/test_mock.js'; @@ -261,4 +261,123 @@ Array.from(onlineTiles).map(item => item.infoText), 'correct info text set for both online collections'); }); + + for (const isTimeOfDayWallpaperEnabled of [false, true]) { + test(`tile order time of day ${isTimeOfDayWallpaperEnabled}`, async () => { + loadTimeData.overrideValues({isTimeOfDayWallpaperEnabled}); + const timeOfDayCollectionId = + loadTimeData.getString('timeOfDayWallpaperCollectionId'); + + // A simplified representation of WallpaperCollectionElement tile for + // testing. + interface Tile { + id: string; + type: string; + } + function getTiles(): Tile[] { + // Access a private field for testing because iron-list hides elements + // that are out of the viewport. Pick just id and type fields for + // simpler testing. + return (wallpaperCollectionsElement as any) + .tiles_.map(({id, type}: Tile) => ({id, type})); + } + + personalizationStore.data = emptyState(); + // Local images are still loading. + personalizationStore.data.wallpaper.loading.local.images = true; + + wallpaperCollectionsElement = initElement(WallpaperCollections); + await waitAfterNextRender(wallpaperCollectionsElement); + + let tiles = getTiles(); + assertGE(tiles.length, 6, 'minimum 3 wide by 2 high'); + for (const tile of tiles) { + assertEquals('loading', tile.type, 'all elements are loading tile'); + } + + // Local tile loads. + personalizationStore.data.wallpaper.local.images = [kDefaultImageSymbol]; + personalizationStore.data.wallpaper.local.data = { + [kDefaultImageSymbol]: { + url: createSvgDataUrl(kDefaultImageSymbol.toString()), + }, + }; + personalizationStore.data.wallpaper.loading.local.images = false; + personalizationStore.data.wallpaper.loading.local + .data = {[kDefaultImageSymbol]: false}; + // Google photos tile loads. + personalizationStore.data.wallpaper.googlePhotos.enabled = + GooglePhotosEnablementState.kEnabled; + personalizationStore.data.wallpaper.loading.googlePhotos.enabled = false; + personalizationStore.notifyObservers(); + await waitAfterNextRender(wallpaperCollectionsElement); + + tiles = getTiles(); + let expectedTiles: Tile[] = []; + if (isTimeOfDayWallpaperEnabled) { + expectedTiles.push({id: timeOfDayCollectionId, type: 'loading'}); + } + expectedTiles.push( + {id: 'local_', type: 'image_local'}, + {id: 'google_photos_', type: 'image_google_photos'}); + // All loading tiles with sequential backdrop temporary ids. + expectedTiles.push(...Array.from( + {length: tiles.length - expectedTiles.length}, + (_, i) => ({id: `backdrop_collection_${i}`, type: 'loading'}))); + + assertDeepEquals( + expectedTiles, tiles, + 'first special tiles should match and all loading after that'); + + personalizationStore.data.wallpaper.backdrop.collections = + wallpaperProvider.collections; + + if (!isTimeOfDayWallpaperEnabled) { + personalizationStore.data.wallpaper.backdrop.collections = + personalizationStore.data.wallpaper.backdrop.collections!.filter( + collection => collection.id !== + loadTimeData.getString('timeOfDayWallpaperCollectionId')); + } + + personalizationStore.data.wallpaper.backdrop.images = + personalizationStore.data.wallpaper.backdrop.collections!.reduce( + (result, next) => { + result[next.id] = wallpaperProvider.images; + return result; + }, + {} as Record<string, WallpaperImage[]|null>); + personalizationStore.data.wallpaper.loading.collections = false; + personalizationStore.data.wallpaper.loading.images = + personalizationStore.data.wallpaper.backdrop.collections!.reduce( + (result, next) => { + result[next.id] = false; + return result; + }, + {} as Record<string, boolean>); + personalizationStore.notifyObservers(); + await waitAfterNextRender(wallpaperCollectionsElement); + + tiles = getTiles(); + expectedTiles = []; + if (isTimeOfDayWallpaperEnabled) { + expectedTiles.push({ + id: loadTimeData.getString('timeOfDayWallpaperCollectionId'), + type: 'image_online', + }); + } + expectedTiles.push( + {id: 'local_', type: 'image_local'}, + {id: 'google_photos_', type: 'image_google_photos'}); + // Loading tiles truncated to match correct number of collections, and + // switched to correct id and type image_online. + expectedTiles.push( + ...personalizationStore.data.wallpaper.backdrop.collections! + .filter( + collection => collection.id !== + loadTimeData.getString('timeOfDayWallpaperCollectionId')) + .map(collection => ({id: collection.id, type: 'image_online'}))); + + assertDeepEquals(expectedTiles, tiles, 'tiles expected to match'); + }); + } });
diff --git a/chrome/test/enterprise/e2e/policy/password_manager_enabled/password_manager_enabled.py b/chrome/test/enterprise/e2e/policy/password_manager_enabled/password_manager_enabled.py index 7fdf2e2..8b0308c4 100644 --- a/chrome/test/enterprise/e2e/policy/password_manager_enabled/password_manager_enabled.py +++ b/chrome/test/enterprise/e2e/policy/password_manager_enabled/password_manager_enabled.py
@@ -4,11 +4,13 @@ import os from chrome_ent_test.infra.core import before_all +from chrome_ent_test.infra.core import category from chrome_ent_test.infra.core import environment from chrome_ent_test.infra.core import test from infra import ChromeEnterpriseTestCase +@category("chrome_only") @environment(file="../policy_test.asset.textpb") class PasswordManagerEnabledTest(ChromeEnterpriseTestCase): """Test the PasswordManagerEnabled policy.
diff --git a/chrome/test/variations/conftest.py b/chrome/test/variations/conftest.py index a215e9e..5fc4684 100644 --- a/chrome/test/variations/conftest.py +++ b/chrome/test/variations/conftest.py
@@ -2,120 +2,10 @@ # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. -import logging -import os -import shutil - -import pytest - -from chrome.test.variations import test_utils -from contextlib import contextmanager -from selenium import webdriver -from selenium.common.exceptions import WebDriverException -from selenium.webdriver import ChromeOptions -from selenium.webdriver.chrome.service import Service -from typing import Optional pytest_plugins = [ + 'chrome.test.variations.fixtures.driver', 'chrome.test.variations.fixtures.http', 'chrome.test.variations.fixtures.seed_locator', 'chrome.test.variations.fixtures.skia_gold', ] - -def pytest_addoption(parser): - # By default, running on the hosted platform. - parser.addoption('--target-platform', - default=test_utils.get_hosted_platform(), - dest='target_platform', - choices=['linux', 'win', 'mac', 'android', 'cros', - 'lacros'], - help='If present, run for the target platform, ' - 'defaults to the host platform.') - - parser.addoption('--channel', - default='dev', - choices=['dev', 'canary', 'beta', 'stable', 'extended'], - help='The channel of Chrome to download.') - - # parser.addoption('--dcheck', - # action='store_true', - # help='Whether to download DCHECK build. ' - # 'Note this is only available in dev or canary.') - - parser.addoption('--chromedriver', - help='The path to the existing chromedriver. ' - 'This will ignore --channel and skip downloading.') - -# pylint: disable=redefined-outer-name -@pytest.fixture(scope="session") -def chromedriver_path(pytestconfig) -> str: - """Returns a path to the chromedriver.""" - if cd_path := pytestconfig.getoption('chromedriver'): - cd_path = os.path.abspath(cd_path) - assert os.path.isfile(cd_path), ( - f'Given chromedriver doesn\'t exist. ({cd_path})') - return cd_path - - platform = pytestconfig.getoption('target_platform') - channel = pytestconfig.getoption('channel') - # dcheck = pytestconfig.getoption('dcheck') - - # https://developer.chrome.com/docs/versionhistory/reference/#platform-identifiers - downloaded_dir = None - if platform == "linux": - ver = test_utils.find_version('linux', channel) - downloaded_dir = test_utils.download_chrome_linux(version=str(ver)) - elif platform == "mac": - ver = test_utils.find_version('mac_arm64', channel) - downloaded_dir = test_utils.download_chrome_mac(version=str(ver)) - elif platform == "win": - ver = test_utils.find_version('win64', channel) - downloaded_dir = test_utils.download_chrome_win(version=str(ver)) - else: - raise RuntimeError(f'Given platform ({platform}) is not supported.') - - return os.path.join(downloaded_dir, 'chromedriver') - -@pytest.fixture -def driver_factory(pytestconfig, - chromedriver_path: str, - tmp_path_factory: pytest.TempPathFactory): - """Returns a factory that creates a webdriver.""" - @contextmanager - def factory(seed_file: Optional[str] = None, - chrome_options: Optional[ChromeOptions] = None): - # Crashpad is a separate process and its dump locations is set via env - # variable. - crash_dump_dir = tmp_path_factory.mktemp('crash', True) - os.environ['BREAKPAD_DUMP_LOCATION'] = str(crash_dump_dir) - - chrome_options = chrome_options or ChromeOptions() - chrome_options.add_argument('disable-field-trial-config') - - if seed_file: - assert os.path.exists(seed_file) - chrome_options.add_argument(f'variations-test-seed-path={seed_file}') - chrome_options.add_argument( - f'fake-variations-channel={pytestconfig.getoption("channel")}') - chrome_options.add_experimental_option('excludeSwitches', - ['disable-background-networking']) - driver = None - try: - logging.info('Launching Chrome w/ caps: %s', - chrome_options.to_capabilities()) - driver = webdriver.Chrome(service=Service(chromedriver_path), - options=chrome_options) - yield driver - except WebDriverException as e: - # Report this to be part of test result. - if os.listdir(crash_dump_dir): - logging.error('Chrome crashed and exited abnormally.\n%s', e) - else: - logging.error('Uncaught WebDriver exception thrown.\n%s', e) - raise - finally: - if driver: - driver.quit() - shutil.rmtree(crash_dump_dir, ignore_errors=True) - - return factory
diff --git a/chrome/test/variations/fixtures/__init__.py b/chrome/test/variations/fixtures/__init__.py index 2510daf..2484312 100644 --- a/chrome/test/variations/fixtures/__init__.py +++ b/chrome/test/variations/fixtures/__init__.py
@@ -2,6 +2,7 @@ # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. +from chrome.test.variations.fixtures.driver import DriverFactory from chrome.test.variations.fixtures.seed_locator import SeedLocator from chrome.test.variations.fixtures.seed_locator import SeedName from chrome.test.variations.fixtures.skia_gold import VariationsSkiaGoldUtil
diff --git a/chrome/test/variations/fixtures/driver.py b/chrome/test/variations/fixtures/driver.py new file mode 100644 index 0000000..0ebbcbb --- /dev/null +++ b/chrome/test/variations/fixtures/driver.py
@@ -0,0 +1,142 @@ +# Copyright 2023 The Chromium Authors +# Use of this source code is governed by a BSD-style license that can be +# found in the LICENSE file. + +import logging +import os +import shutil + +import attr +import pytest + +from chrome.test.variations import test_utils +from contextlib import contextmanager +from selenium import webdriver +from selenium.common.exceptions import WebDriverException +from selenium.webdriver import ChromeOptions +from selenium.webdriver.chrome.service import Service +from typing import Optional + + +def pytest_addoption(parser): + # By default, running on the hosted platform. + parser.addoption('--target-platform', + default=test_utils.get_hosted_platform(), + dest='target_platform', + choices=['linux', 'win', 'mac', 'android', 'cros', + 'lacros'], + help='If present, run for the target platform, ' + 'defaults to the host platform.') + + parser.addoption('--channel', + default='dev', + choices=['dev', 'canary', 'beta', 'stable', 'extended'], + help='The channel of Chrome to download.') + + parser.addoption('--chromedriver', + help='The path to the existing chromedriver. ' + 'This will ignore --channel and skip downloading.') + + +class DriverFactory: + """The factory to create webdriver for the pre-defined environment""" + + @contextmanager + def create_driver(self, + seed_file: Optional[str] = None, + options: Optional[ChromeOptions] = None + ) -> webdriver.Remote: + """Creates a webdriver.""" + raise NotImplemented + + +@attr.attrs() +class DesktopDriverFactory(DriverFactory): + """Driver factory for desktop platforms.""" + channel: Optional[str] = attr.attrib() + crash_dump_dir: Optional[str] = attr.attrib() + chromedriver_path: str = attr.attrib() + + @contextmanager + def create_driver( + self, + seed_file: Optional[str] = None, + options: Optional[ChromeOptions] = None + ) -> webdriver.Remote: + os.environ['BREAKPAD_DUMP_LOCATION'] = self.crash_dump_dir + + options = options or ChromeOptions() + options.add_argument('disable-field-trial-config') + + if seed_file: + assert os.path.exists(seed_file) + options.add_argument(f'variations-test-seed-path={seed_file}') + options.add_argument( + f'fake-variations-channel={self.channel}') + options.add_experimental_option('excludeSwitches', + ['disable-background-networking']) + driver = None + try: + logging.info('Launching Chrome w/ caps: %s', + options.to_capabilities()) + driver = webdriver.Chrome(service=Service(self.chromedriver_path), + options=options) + yield driver + except WebDriverException as e: + # Report this to be part of test result. + if os.listdir(self.crash_dump_dir): + logging.error('Chrome crashed and exited abnormally.\n%s', e) + else: + logging.error('Uncaught WebDriver exception thrown.\n%s', e) + raise + finally: + if driver: + driver.quit() + shutil.rmtree(self.crash_dump_dir, ignore_errors=True) + + +# pylint: disable=redefined-outer-name +@pytest.fixture(scope="session") +def chromedriver_path(pytestconfig) -> str: + """Returns a path to the chromedriver.""" + if cd_path := pytestconfig.getoption('chromedriver'): + cd_path = os.path.abspath(cd_path) + assert os.path.isfile(cd_path), ( + f'Given chromedriver doesn\'t exist. ({cd_path})') + return cd_path + + platform = pytestconfig.getoption('target_platform') + channel = pytestconfig.getoption('channel') + + # https://developer.chrome.com/docs/versionhistory/reference/#platform-identifiers + downloaded_dir = None + if platform == "linux": + ver = test_utils.find_version('linux', channel) + downloaded_dir = test_utils.download_chrome_linux(version=str(ver)) + elif platform == "mac": + ver = test_utils.find_version('mac_arm64', channel) + downloaded_dir = test_utils.download_chrome_mac(version=str(ver)) + elif platform == "win": + ver = test_utils.find_version('win64', channel) + downloaded_dir = test_utils.download_chrome_win(version=str(ver)) + else: + return None + + return str(os.path.join(downloaded_dir, 'chromedriver')) + + +@pytest.fixture +def driver_factory( + pytestconfig, + chromedriver_path: str, + tmp_path_factory: pytest.TempPathFactory + ) -> DriverFactory: + """Returns a factory that creates a webdriver.""" + target_platform = pytestconfig.getoption('target_platform') + if target_platform in ('linux', 'win', 'mac'): + return DesktopDriverFactory( + channel=pytestconfig.getoption('channel'), + crash_dump_dir=str(tmp_path_factory.mktemp('crash')), + chromedriver_path=chromedriver_path) + + assert False, f'Not supported platform {target_platform}.'
diff --git a/chrome/test/variations/smoke_test.py b/chrome/test/variations/smoke_test.py index ec80912..fabd5372 100644 --- a/chrome/test/variations/smoke_test.py +++ b/chrome/test/variations/smoke_test.py
@@ -15,27 +15,27 @@ from selenium.webdriver.common.by import By from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.support.wait import WebDriverWait -from typing import Callable -DriverFactory = Callable[[str, ChromeOptions], webdriver.Remote] -def test_load_simple_url(driver_factory: DriverFactory, +def test_load_simple_url(driver_factory: fixtures.DriverFactory, local_http_server: HTTPServer, seed_locator: fixtures.SeedLocator): url = (f'http://localhost:{local_http_server.server_port}') - with driver_factory(seed_file=seed_locator.get_seed()) as driver: + with driver_factory.create_driver( + seed_file=seed_locator.get_seed()) as driver: driver.set_window_size(800, 600) driver.get(url) WebDriverWait(driver, 5).until( EC.presence_of_element_located((By.TAG_NAME, 'body'))) -def test_basic_rendering(driver_factory: DriverFactory, +def test_basic_rendering(driver_factory: fixtures.DriverFactory, local_http_server: HTTPServer, seed_locator: fixtures.SeedLocator, skia_gold_util: fixtures.VariationsSkiaGoldUtil): url = (f'http://localhost:{local_http_server.server_port}') - with driver_factory(seed_file=seed_locator.get_seed()) as driver: + with driver_factory.create_driver( + seed_file=seed_locator.get_seed()) as driver: driver.set_window_size(800, 600) driver.get(url) body = WebDriverWait(driver, 5).until( @@ -47,12 +47,12 @@ assert status == 0, error_msg -def test_load_crash_seed(driver_factory: DriverFactory, +def test_load_crash_seed(driver_factory: fixtures.DriverFactory, local_http_server: HTTPServer, seed_locator: fixtures.SeedLocator): url = (f'http://localhost:{local_http_server.server_port}') # Launch Chrome normally. - with driver_factory() as driver: + with driver_factory.create_driver() as driver: driver.get("chrome://version") version = WebDriverWait(driver, 5).until( EC.presence_of_element_located((By.ID, 'version'))) @@ -60,6 +60,6 @@ # Launch again with bad seed, expecting a crash. with pytest.raises(WebDriverException): - with driver_factory( + with driver_factory.create_driver( seed_file=seed_locator.get_seed(fixtures.SeedName.CRASH)) as driver: driver.get(url)
diff --git a/chrome/updater/mac/setup/keystone.mm b/chrome/updater/mac/setup/keystone.mm index ff66e75f..acb4b6c1 100644 --- a/chrome/updater/mac/setup/keystone.mm +++ b/chrome/updater/mac/setup/keystone.mm
@@ -7,13 +7,13 @@ #include <string> #include <vector> +#include "base/apple/bundle_locations.h" #include "base/command_line.h" #include "base/files/file.h" #include "base/files/file_path.h" #include "base/files/file_util.h" #include "base/functional/callback.h" #include "base/logging.h" -#include "base/mac/bundle_locations.h" #include "base/mac/foundation_util.h" #include "base/process/launch.h" #include "base/process/process.h" @@ -114,7 +114,7 @@ // The Keystone Bundle is in // GoogleUpdater.app/Contents/Helpers/GoogleSoftwareUpdate.bundle. base::FilePath keystone_bundle_path = - base::mac::OuterBundlePath() + base::apple::OuterBundlePath() .Append(FILE_PATH_LITERAL("Contents")) .Append(FILE_PATH_LITERAL("Helpers")) .Append(FILE_PATH_LITERAL(KEYSTONE_NAME ".bundle"));
diff --git a/chrome/updater/mac/setup/setup.mm b/chrome/updater/mac/setup/setup.mm index ce58fdec..bf39785 100644 --- a/chrome/updater/mac/setup/setup.mm +++ b/chrome/updater/mac/setup/setup.mm
@@ -9,13 +9,13 @@ #include <sys/stat.h> #include <unistd.h> +#include "base/apple/bundle_locations.h" #include "base/at_exit.h" #include "base/command_line.h" #include "base/debug/dump_without_crashing.h" #include "base/files/file_path.h" #include "base/files/file_util.h" #include "base/logging.h" -#include "base/mac/bundle_locations.h" #include "base/mac/foundation_util.h" #include "base/path_service.h" #include "base/process/launch.h" @@ -86,7 +86,7 @@ } } - if (!CopyDir(base::mac::OuterBundlePath(), *versioned_install_dir, + if (!CopyDir(base::apple::OuterBundlePath(), *versioned_install_dir, scope == UpdaterScope::kSystem)) { LOG(ERROR) << "Copying app to '" << versioned_install_dir->value().c_str() << "' failed";
diff --git a/chrome/updater/test/integration_tests_win.cc b/chrome/updater/test/integration_tests_win.cc index 4c84b8a..48f9f94 100644 --- a/chrome/updater/test/integration_tests_win.cc +++ b/chrome/updater/test/integration_tests_win.cc
@@ -293,7 +293,7 @@ EXPECT_EQ(task_info.trigger_types, TaskScheduler::TriggerType::TRIGGER_TYPE_HOURLY | (IsSystemInstall(scope) - ? TaskScheduler::TriggerType::TRIGGER_TYPE_POST_REBOOT + ? TaskScheduler::TriggerType::TRIGGER_TYPE_LOGON : 0)); } else { task_scheduler->ForEachTaskWithPrefix(
diff --git a/chrome/updater/win/setup/setup_util.cc b/chrome/updater/win/setup/setup_util.cc index a5ac51f..a57f09e7 100644 --- a/chrome/updater/win/setup/setup_util.cc +++ b/chrome/updater/win/setup/setup_util.cc
@@ -521,7 +521,7 @@ task_name.c_str(), GetTaskDisplayName(scope_).c_str(), run_command_, TaskScheduler::TriggerType::TRIGGER_TYPE_HOURLY | (IsSystemInstall(scope_) - ? TaskScheduler::TriggerType::TRIGGER_TYPE_POST_REBOOT + ? TaskScheduler::TriggerType::TRIGGER_TYPE_LOGON : 0), true)) { return false;
diff --git a/chrome/updater/win/task_scheduler.cc b/chrome/updater/win/task_scheduler.cc index ff725e3..c53de0be 100644 --- a/chrome/updater/win/task_scheduler.cc +++ b/chrome/updater/win/task_scheduler.cc
@@ -44,7 +44,6 @@ // Text for times used in the V2 API of the Task Scheduler. const wchar_t kOneHourText[] = L"PT1H"; const wchar_t kFiveHoursText[] = L"PT5H"; -const wchar_t kFifteenMinutesText[] = L"PT15M"; const wchar_t kOneDayText[] = L"P1D"; const size_t kNumDeleteTaskRetry = 3; @@ -539,7 +538,7 @@ } for (const TriggerType trigger_type : - {TRIGGER_TYPE_POST_REBOOT, TRIGGER_TYPE_NOW, TRIGGER_TYPE_HOURLY, + {TRIGGER_TYPE_LOGON, TRIGGER_TYPE_NOW, TRIGGER_TYPE_HOURLY, TRIGGER_TYPE_EVERY_FIVE_HOURS}) { if (!(trigger_types & trigger_type)) { continue; @@ -548,7 +547,7 @@ TASK_TRIGGER_TYPE2 task_trigger_type = TASK_TRIGGER_EVENT; base::win::ScopedBstr repetition_interval; switch (trigger_type) { - case TRIGGER_TYPE_POST_REBOOT: + case TRIGGER_TYPE_LOGON: task_trigger_type = TASK_TRIGGER_LOGON; break; case TRIGGER_TYPE_NOW: @@ -630,7 +629,7 @@ } } - if (trigger_type == TRIGGER_TYPE_POST_REBOOT) { + if (trigger_type == TRIGGER_TYPE_LOGON) { Microsoft::WRL::ComPtr<ILogonTrigger> logon_trigger; hr = trigger.As(&logon_trigger); if (FAILED(hr)) { @@ -638,13 +637,6 @@ << hr; return false; } - - hr = logon_trigger->put_Delay( - base::win::ScopedBstr(kFifteenMinutesText).Get()); - if (FAILED(hr)) { - PLOG(ERROR) << "Can't put 'Delay'. " << std::hex << hr; - return false; - } } } @@ -686,13 +678,9 @@ return false; } - VLOG(2) << "Registering Task with XML: " << [&task]() -> std::wstring { - base::win::ScopedBstr task_xml; - if (SUCCEEDED(task->get_XmlText(task_xml.Receive()))) { - return task_xml.Get(); - } - return L""; - }(); + base::win::ScopedBstr task_xml; + task->get_XmlText(task_xml.Receive()); + VLOG(2) << "Registering Task with XML: " << task_xml.Get(); Microsoft::WRL::ComPtr<IRegisteredTask> registered_task; base::win::ScopedVariant user(user_name.Get()); @@ -706,8 +694,9 @@ is_system ? TASK_LOGON_SERVICE_ACCOUNT : TASK_LOGON_INTERACTIVE_TOKEN, base::win::ScopedVariant::kEmptyVariant, ®istered_task); if (FAILED(hr)) { - LOG(ERROR) << "RegisterTaskDefinition failed. " << std::hex << hr << ": " - << logging::SystemErrorCodeToString(hr); + LOG(ERROR) << "RegisterTaskDefinition failed: " << std::hex << hr << ": " + << logging::SystemErrorCodeToString(hr) + << ": Task XML: " << task_xml.Get(); return false; } @@ -1212,7 +1201,7 @@ switch (task_trigger_type) { case TASK_TRIGGER_LOGON: - *trigger_types |= TRIGGER_TYPE_POST_REBOOT; + *trigger_types |= TRIGGER_TYPE_LOGON; break; case TASK_TRIGGER_REGISTRATION: *trigger_types |= TRIGGER_TYPE_NOW;
diff --git a/chrome/updater/win/task_scheduler.h b/chrome/updater/win/task_scheduler.h index c9702331..55201c4 100644 --- a/chrome/updater/win/task_scheduler.h +++ b/chrome/updater/win/task_scheduler.h
@@ -33,9 +33,9 @@ // The types of trigger to register for this task. Multiple triggers types can // be combined using the bitwise OR operator. enum TriggerType { - TRIGGER_TYPE_POST_REBOOT = 1 << 0, // Only run once post-reboot. - TRIGGER_TYPE_NOW = 1 << 1, // Run right now (mainly for tests). - TRIGGER_TYPE_HOURLY = 1 << 2, // Run every hour. + TRIGGER_TYPE_LOGON = 1 << 0, // Run when any user logs on. + TRIGGER_TYPE_NOW = 1 << 1, // Run right now (mainly for tests). + TRIGGER_TYPE_HOURLY = 1 << 2, // Run every hour. TRIGGER_TYPE_EVERY_FIVE_HOURS = 1 << 3, TRIGGER_TYPE_MAX = 1 << 4, };
diff --git a/chrome/updater/win/task_scheduler_unittest.cc b/chrome/updater/win/task_scheduler_unittest.cc index 48670205..1644131 100644 --- a/chrome/updater/win/task_scheduler_unittest.cc +++ b/chrome/updater/win/task_scheduler_unittest.cc
@@ -458,11 +458,11 @@ TEST_F(TaskSchedulerTests, GetTaskInfoTriggerTypes) { for (const TaskScheduler::TriggerType expected_trigger_type : { - TaskScheduler::TRIGGER_TYPE_POST_REBOOT, + TaskScheduler::TRIGGER_TYPE_LOGON, TaskScheduler::TRIGGER_TYPE_HOURLY, TaskScheduler::TRIGGER_TYPE_EVERY_FIVE_HOURS, }) { - if (expected_trigger_type == TaskScheduler::TRIGGER_TYPE_POST_REBOOT && + if (expected_trigger_type == TaskScheduler::TRIGGER_TYPE_LOGON && !::IsUserAnAdmin()) { continue; } @@ -470,9 +470,10 @@ RunGetTaskInfoTriggerTypesTest(expected_trigger_type); } - RunGetTaskInfoTriggerTypesTest(TaskScheduler::TRIGGER_TYPE_POST_REBOOT | - TaskScheduler::TRIGGER_TYPE_HOURLY | - TaskScheduler::TRIGGER_TYPE_EVERY_FIVE_HOURS); + RunGetTaskInfoTriggerTypesTest( + (::IsUserAnAdmin() ? TaskScheduler::TRIGGER_TYPE_LOGON : 0) | + TaskScheduler::TRIGGER_TYPE_HOURLY | + TaskScheduler::TRIGGER_TYPE_EVERY_FIVE_HOURS); } TEST(TaskSchedulerTest, NoSubfolders) {
diff --git a/chrome/version.gni b/chrome/version.gni index 9bbb846..938b664 100644 --- a/chrome/version.gni +++ b/chrome/version.gni
@@ -48,6 +48,8 @@ "webview_beta_version_code = \"@WEBVIEW_BETA_VERSION_CODE@\" " + "webview_dev_version_code = \"@WEBVIEW_DEV_VERSION_CODE@\" " + # Generate hybrid configurations for target_cpu's that can run in hybrid configurations. + # i.e. "riscv64" does not show up in this list, as it's a 64-bit-only target_cpu. if (target_cpu == "arm64" || target_cpu == "x64") { _version_dictionary_template += "monochrome_32_version_code = \"@MONOCHROME_32_VERSION_CODE@\" " @@ -182,7 +184,7 @@ "AndroidWebviewDev: $webview_dev_version_code", ] - if (target_cpu == "arm64" || target_cpu == "x64") { + if (android_64bit_target_cpu && defined(android_app_secondary_abi)) { lines_to_write += [ "Monochrome32: $monochrome_32_version_code", "Monochrome3264: $monochrome_32_64_version_code", @@ -239,24 +241,33 @@ # 64-bit constants are not generated by version.py on non-64-bit target_cpu. if (android_64bit_target_cpu) { - if (_use_stable_package_name_for_trichrome) { - if (is_high_end_android) { - true_true_true_true = trichrome_64_32_high_beta_version_code + # hybrid constants are not generated by version.py on non-64-bit-only target_cpu. + if (defined(android_app_secondary_abi)) { + if (_use_stable_package_name_for_trichrome) { + if (is_high_end_android) { + true_true_true_true = trichrome_64_32_high_beta_version_code + } else { + true_true_true_true = trichrome_64_32_beta_version_code + } + true_true_true_false = trichrome_64_beta_version_code + true_false_false_true = trichrome_32_beta_version_code + true_false_true_true = trichrome_32_64_beta_version_code } else { - true_true_true_true = trichrome_64_32_beta_version_code + if (is_high_end_android) { + true_true_true_true = trichrome_64_32_high_version_code + } else { + true_true_true_true = trichrome_64_32_version_code + } + true_true_true_false = trichrome_64_version_code + true_false_false_true = trichrome_32_version_code + true_false_true_true = trichrome_32_64_version_code } - true_true_true_false = trichrome_64_beta_version_code - true_false_false_true = trichrome_32_beta_version_code - true_false_true_true = trichrome_32_64_beta_version_code } else { - if (is_high_end_android) { - true_true_true_true = trichrome_64_32_high_version_code + if (_use_stable_package_name_for_trichrome) { + true_true_true_false = trichrome_beta_version_code } else { - true_true_true_true = trichrome_64_32_version_code + true_true_true_false = trichrome_version_code } - true_true_true_false = trichrome_64_version_code - true_false_false_true = trichrome_32_version_code - true_false_true_true = trichrome_32_64_version_code } } else { # !android_64bit_target_cpu @@ -271,10 +282,14 @@ # Key: {android_64bit_target_cpu}_{is_64_bit_browser}_{include_64_bit_webview}_{include_32_bit_webview} MONOCHROME_VERSION_MAP = { if (android_64bit_target_cpu) { - true_true_true_true = monochrome_64_32_version_code - true_false_true_true = monochrome_32_64_version_code - true_true_true_false = monochrome_64_version_code - true_false_false_true = monochrome_32_version_code + if (defined(android_app_secondary_abi)) { + true_true_true_true = monochrome_64_32_version_code + true_false_true_true = monochrome_32_64_version_code + true_true_true_false = monochrome_64_version_code + true_false_false_true = monochrome_32_version_code + } else { + true_true_true_false = monochrome_version_code + } } else { false_false_false_true = monochrome_version_code } @@ -284,18 +299,28 @@ WEBVIEW_VERSION_MAP = { # 64-bit constants are not generated by version.py on non-64-bit target_cpu. if (android_64bit_target_cpu) { - if (android_channel == "dev") { - true_false_true = webview_32_dev_version_code - true_true_false = webview_64_dev_version_code - true_true_true = webview_dev_version_code - } else if (android_channel == "beta") { - true_false_true = webview_32_beta_version_code - true_true_false = webview_64_beta_version_code - true_true_true = webview_beta_version_code + if (defined(android_app_secondary_abi)) { + if (android_channel == "dev") { + true_false_true = webview_32_dev_version_code + true_true_false = webview_64_dev_version_code + true_true_true = webview_dev_version_code + } else if (android_channel == "beta") { + true_false_true = webview_32_beta_version_code + true_true_false = webview_64_beta_version_code + true_true_true = webview_beta_version_code + } else { + true_false_true = webview_32_stable_version_code + true_true_false = webview_64_stable_version_code + true_true_true = webview_stable_version_code + } } else { - true_false_true = webview_32_stable_version_code - true_true_false = webview_64_stable_version_code - true_true_true = webview_stable_version_code + if (android_channel == "dev") { + true_true_false = webview_dev_version_code + } else if (android_channel == "beta") { + true_true_false = webview_beta_version_code + } else { + true_true_false = webview_stable_version_code + } } } else { # !android_64bit_target_cpu
diff --git a/chromeos/CHROMEOS_LKGM b/chromeos/CHROMEOS_LKGM index 6a25a5b..7c74869 100644 --- a/chromeos/CHROMEOS_LKGM +++ b/chromeos/CHROMEOS_LKGM
@@ -1 +1 @@ -15459.0.0 \ No newline at end of file +15460.0.0 \ No newline at end of file
diff --git a/chromeos/ash/components/quick_start/fake_quick_start_decoder.cc b/chromeos/ash/components/quick_start/fake_quick_start_decoder.cc index 6da5ca67..300a469 100644 --- a/chromeos/ash/components/quick_start/fake_quick_start_decoder.cc +++ b/chromeos/ash/components/quick_start/fake_quick_start_decoder.cc
@@ -33,6 +33,17 @@ std::move(callback).Run(std::move(credentials_), error_); } +void FakeQuickStartDecoder::DecodeUserVerificationRequested( + const std::vector<uint8_t>& data, + DecodeUserVerificationRequestedCallback callback) { + if (error_ != absl::nullopt) { + std::move(callback).Run(nullptr, error_); + } else { + std::move(callback).Run(std::move(user_verification_request_), + absl::nullopt); + } +} + void FakeQuickStartDecoder::DecodeUserVerificationResult( const std::vector<uint8_t>& data, DecodeUserVerificationResultCallback callback) { @@ -60,6 +71,12 @@ std::move(callback).Run(/*ack_received=*/notify_source_of_update_response_); } +void FakeQuickStartDecoder::SetUserVerificationRequested( + bool is_awaiting_user_verification) { + user_verification_request_ = + mojom::UserVerificationRequested::New(is_awaiting_user_verification); +} + void FakeQuickStartDecoder::SetExpectedData( std::vector<uint8_t> expected_data) { expected_data_ = expected_data;
diff --git a/chromeos/ash/components/quick_start/fake_quick_start_decoder.h b/chromeos/ash/components/quick_start/fake_quick_start_decoder.h index a86ff57a..3fa8f236 100644 --- a/chromeos/ash/components/quick_start/fake_quick_start_decoder.h +++ b/chromeos/ash/components/quick_start/fake_quick_start_decoder.h
@@ -36,6 +36,9 @@ void DecodeNotifySourceOfUpdateResponse( const std::vector<uint8_t>& data, DecodeNotifySourceOfUpdateResponseCallback callback) override; + void DecodeUserVerificationRequested( + const std::vector<uint8_t>& data, + DecodeUserVerificationRequestedCallback callback) override; void DecodeUserVerificationResult( const std::vector<uint8_t>& data, DecodeUserVerificationResultCallback callback) override; @@ -53,6 +56,8 @@ void SetUserVerificationResponse(mojom::UserVerificationResult result, bool is_first_user_verification); + void SetUserVerificationRequested(bool is_awaiting_user_verification); + void SetDecoderError(mojom::QuickStartDecoderError error); void SetWifiCredentialsResponse( @@ -73,6 +78,7 @@ mojo::ReceiverSet<ash::quick_start::mojom::QuickStartDecoder> receiver_set_; absl::optional<bool> notify_source_of_update_response_; mojom::WifiCredentialsPtr credentials_; + mojom::UserVerificationRequestedPtr user_verification_request_; mojom::UserVerificationResponsePtr user_verification_response_; absl::optional<mojom::QuickStartDecoderError> error_; };
diff --git a/chromeos/ash/services/nearby/public/cpp/mock_quick_start_decoder.h b/chromeos/ash/services/nearby/public/cpp/mock_quick_start_decoder.h index 220316b4..ab597ef 100644 --- a/chromeos/ash/services/nearby/public/cpp/mock_quick_start_decoder.h +++ b/chromeos/ash/services/nearby/public/cpp/mock_quick_start_decoder.h
@@ -60,6 +60,12 @@ DecodeUserVerificationResultCallback callback), (override)); + MOCK_METHOD(void, + DecodeUserVerificationRequested, + (const std::vector<uint8_t>& data, + DecodeUserVerificationRequestedCallback callback), + (override)); + private: mojo::ReceiverSet<ash::quick_start::mojom::QuickStartDecoder> receiver_set_; mojo::SharedRemote<ash::quick_start::mojom::QuickStartDecoder> shared_remote_;
diff --git a/chromeos/ash/services/nearby/public/mojom/quick_start_decoder.mojom b/chromeos/ash/services/nearby/public/mojom/quick_start_decoder.mojom index 67228d2..81e9126 100644 --- a/chromeos/ash/services/nearby/public/mojom/quick_start_decoder.mojom +++ b/chromeos/ash/services/nearby/public/mojom/quick_start_decoder.mojom
@@ -41,6 +41,11 @@ DecodeGetAssertionResponse(array<uint8> data) => ( GetAssertionResponse response); + // Decode UserVerificationRequested message, indicating we are waiting + // for the user to pass a verification prompt. + DecodeUserVerificationRequested(array<uint8> data) => ( + UserVerificationRequested? response, QuickStartDecoderError? error); + // Decode the UserVerificationResult sent from the target device. DecodeUserVerificationResult(array<uint8> data) => ( UserVerificationResponse? response, QuickStartDecoderError? error);
diff --git a/chromeos/ash/services/nearby/public/mojom/quick_start_decoder_types.mojom b/chromeos/ash/services/nearby/public/mojom/quick_start_decoder_types.mojom index cc5d8ed..c989b4a 100644 --- a/chromeos/ash/services/nearby/public/mojom/quick_start_decoder_types.mojom +++ b/chromeos/ash/services/nearby/public/mojom/quick_start_decoder_types.mojom
@@ -30,6 +30,10 @@ bool is_first_user_verification; }; +struct UserVerificationRequested { + bool is_awaiting_user_verification; +}; + enum QuickStartDecoderError { kEmptyMessage = 0, kUnableToReadAsJSON = 1,
diff --git a/components/BUILD.gn b/components/BUILD.gn index a29c2106..6f142654 100644 --- a/components/BUILD.gn +++ b/components/BUILD.gn
@@ -665,7 +665,10 @@ "//components/safe_browsing/core/common:unit_tests", ] } else if (safe_browsing_mode == 2) { - deps += [ "//components/safe_browsing/android:unit_tests_mobile" ] + deps += [ + "//components/safe_browsing/android:native_java_unittests_java", + "//components/safe_browsing/android:unit_tests_mobile", + ] } if (safe_browsing_mode == 1) {
diff --git a/components/autofill/ios/browser/autofill_agent_unittests.mm b/components/autofill/ios/browser/autofill_agent_unittests.mm index 0461a58..ad2a5d3 100644 --- a/components/autofill/ios/browser/autofill_agent_unittests.mm +++ b/components/autofill/ios/browser/autofill_agent_unittests.mm
@@ -4,7 +4,7 @@ #import "components/autofill/ios/browser/autofill_agent.h" -#include "base/mac/bundle_locations.h" +#include "base/apple/bundle_locations.h" #include "base/memory/weak_ptr.h" #include "base/strings/utf_string_conversions.h" #import "base/test/ios/wait_util.h"
diff --git a/components/browser_ui/widget/android/java/src/org/chromium/components/browser_ui/widget/dragreorder/DragStateDelegate.java b/components/browser_ui/widget/android/java/src/org/chromium/components/browser_ui/widget/dragreorder/DragStateDelegate.java index 67b06d7..1ce83e3 100644 --- a/components/browser_ui/widget/android/java/src/org/chromium/components/browser_ui/widget/dragreorder/DragStateDelegate.java +++ b/components/browser_ui/widget/android/java/src/org/chromium/components/browser_ui/widget/dragreorder/DragStateDelegate.java
@@ -4,8 +4,6 @@ package org.chromium.components.browser_ui.widget.dragreorder; -import androidx.annotation.VisibleForTesting; - /** * Responsible for keeping track of the drag state (whether drag is enabled, and if so, whether drag * is active). @@ -23,7 +21,4 @@ * dragged). Activating drag is only valid if drag is currently enabled. */ boolean getDragActive(); - - @VisibleForTesting - void setA11yStateForTesting(boolean a11yEnabled); }
diff --git a/components/component_updater/component_installer.cc b/components/component_updater/component_installer.cc index f93c720..a695c95 100644 --- a/components/component_updater/component_installer.cc +++ b/components/component_updater/component_installer.cc
@@ -40,7 +40,7 @@ #include "third_party/abseil-cpp/absl/types/optional.h" #if BUILDFLAG(IS_APPLE) -#include "base/mac/backup_util.h" +#include "base/apple/backup_util.h" #endif namespace component_updater { @@ -173,7 +173,7 @@ #if BUILDFLAG(IS_APPLE) // Since components can be large and can be re-downloaded when needed, they // are excluded from backups. - base::mac::SetBackupExclusion(local_install_path); + base::apple::SetBackupExclusion(local_install_path); #endif const Result result =
diff --git a/components/content_settings/core/browser/content_settings_origin_identifier_value_map.cc b/components/content_settings/core/browser/content_settings_origin_identifier_value_map.cc index 336a853..ebff3d79 100644 --- a/components/content_settings/core/browser/content_settings_origin_identifier_value_map.cc +++ b/components/content_settings/core/browser/content_settings_origin_identifier_value_map.cc
@@ -7,6 +7,7 @@ #include <memory> #include <tuple> +#include "base/auto_reset.h" #include "base/check_op.h" #include "base/compiler_specific.h" #include "base/synchronization/lock.h" @@ -26,10 +27,12 @@ RuleIteratorImpl( const OriginIdentifierValueMap::Rules::const_iterator& current_rule, const OriginIdentifierValueMap::Rules::const_iterator& rule_end, - std::unique_ptr<base::AutoLock> auto_lock) + std::unique_ptr<base::AutoLock> auto_lock, + base::AutoReset<bool> iterating) : current_rule_(current_rule), rule_end_(rule_end), - auto_lock_(std::move(auto_lock)) {} + auto_lock_(std::move(auto_lock)), + iterating_(std::move(iterating)) {} ~RuleIteratorImpl() override = default; bool HasNext() const override { return (current_rule_ != rule_end_); } @@ -48,6 +51,7 @@ OriginIdentifierValueMap::Rules::const_iterator current_rule_; OriginIdentifierValueMap::Rules::const_iterator rule_end_; std::unique_ptr<base::AutoLock> auto_lock_; + base::AutoReset<bool> iterating_; }; } // namespace @@ -71,20 +75,22 @@ OriginIdentifierValueMap::ValueEntry::~ValueEntry() = default; std::unique_ptr<RuleIterator> OriginIdentifierValueMap::GetRuleIterator( - ContentSettingsType content_type, - base::Lock* lock) const { + ContentSettingsType content_type) const NO_THREAD_SAFETY_ANALYSIS { // We access |entries_| here, so we need to lock |auto_lock| first. The lock // must be passed to the |RuleIteratorImpl| in a locked state, so that nobody // can access |entries_| after |find()| but before the |RuleIteratorImpl| is // created. - std::unique_ptr<base::AutoLock> auto_lock; - if (lock) - auto_lock = std::make_unique<base::AutoLock>(*lock); + std::unique_ptr<base::AutoLock> auto_lock = + std::make_unique<base::AutoLock>(lock_); auto it = entries_.find(content_type); - if (it == entries_.end()) + if (it == entries_.end()) { return nullptr; + } + CHECK(!iterating_); + base::AutoReset<bool> iterating(&iterating_, true); return std::make_unique<RuleIteratorImpl>( - it->second.begin(), it->second.end(), std::move(auto_lock)); + it->second.begin(), it->second.end(), std::move(auto_lock), + std::move(iterating)); } size_t OriginIdentifierValueMap::size() const { @@ -124,6 +130,7 @@ ContentSettingsType content_type, base::Value value, const RuleMetaData& metadata) { + CHECK(!iterating_); DCHECK(primary_pattern.IsValid()); DCHECK(secondary_pattern.IsValid()); // TODO(raymes): Remove this after we track down the cause of @@ -139,6 +146,7 @@ const ContentSettingsPattern& primary_pattern, const ContentSettingsPattern& secondary_pattern, ContentSettingsType content_type) { + CHECK(!iterating_); PatternPair patterns(primary_pattern, secondary_pattern); auto it = entries_.find(content_type); if (it == entries_.end()) @@ -149,10 +157,12 @@ } void OriginIdentifierValueMap::DeleteValues(ContentSettingsType content_type) { + CHECK(!iterating_); entries_.erase(content_type); } void OriginIdentifierValueMap::clear() { + CHECK(!iterating_); // Delete all owned value objects. entries_.clear(); }
diff --git a/components/content_settings/core/browser/content_settings_origin_identifier_value_map.h b/components/content_settings/core/browser/content_settings_origin_identifier_value_map.h index 9b9e2fc..70d90fc4 100644 --- a/components/content_settings/core/browser/content_settings_origin_identifier_value_map.h +++ b/components/content_settings/core/browser/content_settings_origin_identifier_value_map.h
@@ -10,6 +10,8 @@ #include <map> #include <memory> +#include "base/synchronization/lock.h" +#include "base/thread_annotations.h" #include "base/time/time.h" #include "components/content_settings/core/common/content_settings.h" #include "components/content_settings/core/common/content_settings_constraints.h" @@ -26,6 +28,16 @@ class RuleIterator; +// Stores and provides access to Content Settings Rules. +// +// This class is multi-threaded, with some users calling |GetRuleIterator| off +// of the UI thread. +// +// Interacting with this class generally requires holding |GetLock|, and +// modifying rules while iterating over them is not permitted. Notably, due to +// complexity around ensuring the lock is held while iterating, +// |GetRuleIterator| should only be called while the lock is not held, as the +// Iterator itself will hold the lock until it's destroyed. class OriginIdentifierValueMap { public: struct PatternPair { @@ -46,31 +58,42 @@ typedef std::map<PatternPair, ValueEntry> Rules; typedef std::map<ContentSettingsType, Rules> EntryMap; - EntryMap::iterator begin() { return entries_.begin(); } + base::Lock& GetLock() const LOCK_RETURNED(lock_) { return lock_; } - EntryMap::iterator end() { return entries_.end(); } + EntryMap::iterator begin() EXCLUSIVE_LOCKS_REQUIRED(lock_) { + return entries_.begin(); + } - EntryMap::const_iterator begin() const { return entries_.begin(); } + EntryMap::iterator end() EXCLUSIVE_LOCKS_REQUIRED(lock_) { + return entries_.end(); + } - EntryMap::const_iterator end() const { return entries_.end(); } + EntryMap::const_iterator begin() const EXCLUSIVE_LOCKS_REQUIRED(lock_) { + return entries_.begin(); + } - EntryMap::iterator find(ContentSettingsType content_type) { + EntryMap::const_iterator end() const EXCLUSIVE_LOCKS_REQUIRED(lock_) { + return entries_.end(); + } + + EntryMap::iterator find(ContentSettingsType content_type) + EXCLUSIVE_LOCKS_REQUIRED(lock_) { return entries_.find(content_type); } - bool empty() const { return size() == 0u; } + bool empty() const EXCLUSIVE_LOCKS_REQUIRED(lock_) { return size() == 0u; } - size_t size() const; + size_t size() const EXCLUSIVE_LOCKS_REQUIRED(lock_); // Returns an iterator for reading the rules for |content_type| and // |resource_identifier|. It is not allowed to call functions of // |OriginIdentifierValueMap| (also |GetRuleIterator|) before the iterator - // has been destroyed. If |lock| is non-NULL, the returned |RuleIterator| - // locks it and releases it when it is destroyed. - // Returns nullptr to indicate the RuleIterator is empty. + // has been destroyed. + // + // |lock_| will be acquired and held until the returned RuleIterator is + // destroyed. std::unique_ptr<RuleIterator> GetRuleIterator( - ContentSettingsType content_type, - base::Lock* lock) const; + ContentSettingsType content_type) const LOCKS_EXCLUDED(lock_); OriginIdentifierValueMap(); @@ -84,7 +107,8 @@ // no value is stored for the passed parameter |NULL| is returned. const base::Value* GetValue(const GURL& primary_url, const GURL& secondary_url, - ContentSettingsType content_type) const; + ContentSettingsType content_type) const + EXCLUSIVE_LOCKS_REQUIRED(lock_); // Sets the |value| for the given |primary_pattern|, |secondary_pattern|, // |content_type| tuple. The caller can also store a @@ -95,22 +119,26 @@ const ContentSettingsPattern& secondary_pattern, ContentSettingsType content_type, base::Value value, - const RuleMetaData& metadata); + const RuleMetaData& metadata) EXCLUSIVE_LOCKS_REQUIRED(lock_); // Deletes the map entry for the given |primary_pattern|, // |secondary_pattern|, |content_type| tuple. void DeleteValue(const ContentSettingsPattern& primary_pattern, const ContentSettingsPattern& secondary_pattern, - ContentSettingsType content_type); + ContentSettingsType content_type) + EXCLUSIVE_LOCKS_REQUIRED(lock_); // Deletes all map entries for the given |content_type|. - void DeleteValues(ContentSettingsType content_type); + void DeleteValues(ContentSettingsType content_type) + EXCLUSIVE_LOCKS_REQUIRED(lock_); // Clears all map entries. - void clear(); + void clear() EXCLUSIVE_LOCKS_REQUIRED(lock_); private: - EntryMap entries_; + mutable bool iterating_ = false; + mutable base::Lock lock_; + EntryMap entries_ GUARDED_BY(lock_); }; } // namespace content_settings
diff --git a/components/content_settings/core/browser/content_settings_policy_provider.cc b/components/content_settings/core/browser/content_settings_policy_provider.cc index 2a742f9..b704d81 100644 --- a/components/content_settings/core/browser/content_settings_policy_provider.cc +++ b/components/content_settings/core/browser/content_settings_policy_provider.cc
@@ -275,11 +275,10 @@ std::unique_ptr<RuleIterator> PolicyProvider::GetRuleIterator( ContentSettingsType content_type, bool incognito) const { - return value_map_.GetRuleIterator(content_type, &lock_); + return value_map_.GetRuleIterator(content_type); } -void PolicyProvider::GetContentSettingsFromPreferences( - OriginIdentifierValueMap* value_map) { +void PolicyProvider::GetContentSettingsFromPreferences() { for (const auto& entry : kPrefsForManagedContentSettingsMap) { // Skip unset policies. if (!prefs_->HasPrefPath(entry.pref_name)) { @@ -338,14 +337,13 @@ } // Don't set a timestamp for policy settings. - value_map->SetValue(pattern_pair.first, secondary_pattern, + value_map_.SetValue(pattern_pair.first, secondary_pattern, entry.content_type, base::Value(entry.setting), {}); } } } -void PolicyProvider::GetAutoSelectCertificateSettingsFromPreferences( - OriginIdentifierValueMap* value_map) { +void PolicyProvider::GetAutoSelectCertificateSettingsFromPreferences() { constexpr const char* pref_name = prefs::kManagedAutoSelectCertificateForUrls; if (!prefs_->HasPrefPath(pref_name)) { VLOG(2) << "Skipping unset preference: " << pref_name; @@ -428,7 +426,7 @@ continue; } - value_map->SetValue(pattern, ContentSettingsPattern::Wildcard(), + value_map_.SetValue(pattern, ContentSettingsPattern::Wildcard(), ContentSettingsType::AUTO_SELECT_CERTIFICATE, base::Value(setting.Clone()), {}); } @@ -456,8 +454,8 @@ // MUST be managed. DCHECK(!prefs_->HasPrefPath(entry.pref_name) || prefs_->IsManagedPreference(entry.pref_name)); - base::AutoLock auto_lock(lock_); int setting = prefs_->GetInteger(entry.pref_name); + base::AutoLock lock(value_map_.GetLock()); if (setting == CONTENT_SETTING_DEFAULT) { value_map_.DeleteValue(ContentSettingsPattern::Wildcard(), ContentSettingsPattern::Wildcard(), @@ -471,11 +469,11 @@ } void PolicyProvider::ReadManagedContentSettings(bool overwrite) { - base::AutoLock auto_lock(lock_); + base::AutoLock lock(value_map_.GetLock()); if (overwrite) value_map_.clear(); - GetContentSettingsFromPreferences(&value_map_); - GetAutoSelectCertificateSettingsFromPreferences(&value_map_); + GetContentSettingsFromPreferences(); + GetAutoSelectCertificateSettingsFromPreferences(); } // Since the PolicyProvider is a read only content settings provider, all
diff --git a/components/content_settings/core/browser/content_settings_policy_provider.h b/components/content_settings/core/browser/content_settings_policy_provider.h index b317caf7f..0a93a25 100644 --- a/components/content_settings/core/browser/content_settings_policy_provider.h +++ b/components/content_settings/core/browser/content_settings_policy_provider.h
@@ -64,10 +64,11 @@ void ReadManagedContentSettings(bool overwrite); - void GetContentSettingsFromPreferences(OriginIdentifierValueMap* rules); + void GetContentSettingsFromPreferences() + EXCLUSIVE_LOCKS_REQUIRED(value_map_.GetLock()); - void GetAutoSelectCertificateSettingsFromPreferences( - OriginIdentifierValueMap* value_map); + void GetAutoSelectCertificateSettingsFromPreferences() + EXCLUSIVE_LOCKS_REQUIRED(value_map_.GetLock()); void ReadManagedContentSettingsTypes(ContentSettingsType content_type); @@ -76,10 +77,6 @@ raw_ptr<PrefService> prefs_; PrefChangeRegistrar pref_change_registrar_; - - // Used around accesses to the |value_map_| object to guarantee - // thread safety. - mutable base::Lock lock_; }; } // namespace content_settings
diff --git a/components/content_settings/core/browser/content_settings_pref.cc b/components/content_settings/core/browser/content_settings_pref.cc index 5845c67..73a819d 100644 --- a/components/content_settings/core/browser/content_settings_pref.cc +++ b/components/content_settings/core/browser/content_settings_pref.cc
@@ -158,8 +158,8 @@ std::unique_ptr<RuleIterator> ContentSettingsPref::GetRuleIterator( bool off_the_record) const { if (off_the_record) - return off_the_record_value_map_.GetRuleIterator(content_type_, &lock_); - return value_map_.GetRuleIterator(content_type_, &lock_); + return off_the_record_value_map_.GetRuleIterator(content_type_); + return value_map_.GetRuleIterator(content_type_); } void ContentSettingsPref::SetWebsiteSetting( @@ -179,7 +179,7 @@ map_to_modify = &value_map_; { - base::AutoLock auto_lock(lock_); + base::AutoLock auto_lock(map_to_modify->GetLock()); if (!value.is_none()) { map_to_modify->SetValue(primary_pattern, secondary_pattern, content_type_, value.Clone(), metadata); @@ -201,7 +201,7 @@ DCHECK(prefs_); { - base::AutoLock auto_lock(lock_); + base::AutoLock auto_lock(value_map_.GetLock()); value_map_.clear(); } @@ -217,7 +217,7 @@ DCHECK(prefs_); if (off_the_record_) { - base::AutoLock auto_lock(lock_); + base::AutoLock auto_lock(off_the_record_value_map_.GetLock()); off_the_record_value_map_.clear(); } else { ClearPref(); @@ -228,13 +228,15 @@ } size_t ContentSettingsPref::GetNumExceptions() { + base::AutoLock auto_lock(value_map_.GetLock()); return value_map_.size(); } bool ContentSettingsPref::TryLockForTesting() const { - if (!lock_.Try()) + if (!value_map_.GetLock().Try()) { return false; - lock_.Release(); + } + value_map_.GetLock().Release(); return true; } @@ -246,7 +248,7 @@ // notification. base::AutoReset<bool> auto_reset(&updating_preferences_, true); prefs::ScopedDictionaryPrefUpdate update(prefs_, *pref_name_); - base::AutoLock auto_lock(lock_); + base::AutoLock auto_lock(value_map_.GetLock()); value_map_.clear(); @@ -444,8 +446,8 @@ void ContentSettingsPref::AssertLockNotHeld() const { #if !defined(NDEBUG) // |Lock::Acquire()| will assert if the lock is held by this thread. - lock_.Acquire(); - lock_.Release(); + value_map_.GetLock().Acquire(); + value_map_.GetLock().Release(); #endif }
diff --git a/components/content_settings/core/browser/content_settings_pref.h b/components/content_settings/core/browser/content_settings_pref.h index 75ce2f0b..c10008a 100644 --- a/components/content_settings/core/browser/content_settings_pref.h +++ b/components/content_settings/core/browser/content_settings_pref.h
@@ -114,9 +114,6 @@ NotifyObserversCallback notify_callback_; - // Used around accesses to the value map objects to guarantee thread safety. - mutable base::Lock lock_; - base::ThreadChecker thread_checker_; };
diff --git a/components/content_settings/core/browser/content_settings_rule.cc b/components/content_settings/core/browser/content_settings_rule.cc index 0afe3c67..09f1eaa 100644 --- a/components/content_settings/core/browser/content_settings_rule.cc +++ b/components/content_settings/core/browser/content_settings_rule.cc
@@ -30,9 +30,8 @@ RuleIterator::~RuleIterator() = default; ConcatenationIterator::ConcatenationIterator( - std::vector<std::unique_ptr<RuleIterator>> iterators, - base::AutoLock* auto_lock) - : iterators_(std::move(iterators)), auto_lock_(auto_lock) { + std::vector<std::unique_ptr<RuleIterator>> iterators) + : iterators_(std::move(iterators)) { auto it = iterators_.begin(); while (it != iterators_.end()) { if (!(*it)->HasNext())
diff --git a/components/content_settings/core/browser/content_settings_rule.h b/components/content_settings/core/browser/content_settings_rule.h index e8105dd8..d4cc99a3 100644 --- a/components/content_settings/core/browser/content_settings_rule.h +++ b/components/content_settings/core/browser/content_settings_rule.h
@@ -50,16 +50,14 @@ class ConcatenationIterator : public RuleIterator { public: - // |auto_lock| can be null if no locking is needed. - ConcatenationIterator(std::vector<std::unique_ptr<RuleIterator>> iterators, - base::AutoLock* auto_lock); + explicit ConcatenationIterator( + std::vector<std::unique_ptr<RuleIterator>> iterators); ~ConcatenationIterator() override; bool HasNext() const override; Rule Next() override; private: std::vector<std::unique_ptr<RuleIterator>> iterators_; - std::unique_ptr<base::AutoLock> auto_lock_; }; } // namespace content_settings
diff --git a/components/content_settings/core/browser/content_settings_rule_unittest.cc b/components/content_settings/core/browser/content_settings_rule_unittest.cc index 4f07627d..fcb4a4e 100644 --- a/components/content_settings/core/browser/content_settings_rule_unittest.cc +++ b/components/content_settings/core/browser/content_settings_rule_unittest.cc
@@ -61,7 +61,7 @@ std::vector<std::unique_ptr<RuleIterator>> iterators; iterators.push_back(std::make_unique<ListIterator>(std::move(rules1))); iterators.push_back(std::make_unique<ListIterator>(std::move(rules2))); - ConcatenationIterator concatenation_iterator(std::move(iterators), nullptr); + ConcatenationIterator concatenation_iterator(std::move(iterators)); Rule rule; ASSERT_TRUE(concatenation_iterator.HasNext());
diff --git a/components/content_settings/core/test/content_settings_mock_provider.cc b/components/content_settings/core/test/content_settings_mock_provider.cc index 9ed1957..de184c4 100644 --- a/components/content_settings/core/test/content_settings_mock_provider.cc +++ b/components/content_settings/core/test/content_settings_mock_provider.cc
@@ -17,7 +17,7 @@ std::unique_ptr<RuleIterator> MockProvider::GetRuleIterator( ContentSettingsType content_type, bool incognito) const { - return value_map_.GetRuleIterator(content_type, nullptr); + return value_map_.GetRuleIterator(content_type); } bool MockProvider::SetWebsiteSetting( @@ -28,6 +28,7 @@ const ContentSettingConstraints& constraints) { if (read_only_) return false; + base::AutoLock lock(value_map_.GetLock()); if (!in_value.is_none()) { value_map_.SetValue(requesting_url_pattern, embedding_url_pattern, content_type, std::move(in_value),
diff --git a/components/crash/core/app/crashpad_ios.mm b/components/crash/core/app/crashpad_ios.mm index 18fafb18..08157af 100644 --- a/components/crash/core/app/crashpad_ios.mm +++ b/components/crash/core/app/crashpad_ios.mm
@@ -7,7 +7,7 @@ #include <vector> #include "base/apple/bridging.h" -#include "base/mac/bundle_locations.h" +#include "base/apple/bundle_locations.h" #include "base/mac/foundation_util.h" #include "base/strings/sys_string_conversions.h" #include "build/branding_buildflags.h" @@ -32,7 +32,7 @@ static std::map<std::string, std::string> annotations = []() -> auto { std::map<std::string, std::string> process_annotations; @autoreleasepool { - NSBundle* outer_bundle = base::mac::OuterBundle(); + NSBundle* outer_bundle = base::apple::OuterBundle(); #if BUILDFLAG(GOOGLE_CHROME_BRANDING) process_annotations["prod"] = "Chrome_iOS"; #else @@ -56,7 +56,7 @@ channel = @"developer"; process_annotations["channel"] = base::SysNSStringToUTF8(channel); NSString* version = - base::mac::ObjCCast<NSString>([base::mac::FrameworkBundle() + base::mac::ObjCCast<NSString>([base::apple::FrameworkBundle() objectForInfoDictionaryKey:@"CFBundleVersion"]); process_annotations["ver"] = base::SysNSStringToUTF8(version); process_annotations["plat"] = std::string("iOS");
diff --git a/components/crash/core/app/crashpad_mac.mm b/components/crash/core/app/crashpad_mac.mm index 54165c7f..d7351f4 100644 --- a/components/crash/core/app/crashpad_mac.mm +++ b/components/crash/core/app/crashpad_mac.mm
@@ -13,9 +13,9 @@ #include <vector> #include "base/apple/bridging.h" +#include "base/apple/bundle_locations.h" #include "base/check.h" #include "base/files/file_path.h" -#include "base/mac/bundle_locations.h" #include "base/mac/foundation_util.h" #include "base/strings/string_number_conversions.h" #include "base/strings/string_piece.h" @@ -42,7 +42,7 @@ static std::map<std::string, std::string> annotations = []() -> auto { std::map<std::string, std::string> process_annotations; @autoreleasepool { - NSBundle* outer_bundle = base::mac::OuterBundle(); + NSBundle* outer_bundle = base::apple::OuterBundle(); #if BUILDFLAG(GOOGLE_CHROME_BRANDING) process_annotations["prod"] = "Chrome_Mac"; #else @@ -83,7 +83,7 @@ } NSString* version = - base::mac::ObjCCast<NSString>([base::mac::FrameworkBundle() + base::mac::ObjCCast<NSString>([base::apple::FrameworkBundle() objectForInfoDictionaryKey:@"CFBundleShortVersionString"]); process_annotations["ver"] = base::SysNSStringToUTF8(version); @@ -147,7 +147,7 @@ if (initial_client) { @autoreleasepool { - base::FilePath framework_bundle_path = base::mac::FrameworkBundlePath(); + base::FilePath framework_bundle_path = base::apple::FrameworkBundlePath(); base::FilePath handler_path = framework_bundle_path.Append("Helpers").Append( "chrome_crashpad_handler");
diff --git a/components/cronet/ios/Cronet.mm b/components/cronet/ios/Cronet.mm index 190cbbed..f142049 100644 --- a/components/cronet/ios/Cronet.mm +++ b/components/cronet/ios/Cronet.mm
@@ -7,9 +7,9 @@ #include <memory> #include <vector> +#include "base/apple/bundle_locations.h" #include "base/lazy_instance.h" #include "base/logging.h" -#include "base/mac/bundle_locations.h" #include "base/strings/sys_string_conversions.h" #include "base/synchronization/lock.h" #import "base/task/single_thread_task_runner.h"
diff --git a/components/favicon/android/java/src/org/chromium/components/favicon/LargeIconBridge.java b/components/favicon/android/java/src/org/chromium/components/favicon/LargeIconBridge.java index e6e2d599..6f59669 100644 --- a/components/favicon/android/java/src/org/chromium/components/favicon/LargeIconBridge.java +++ b/components/favicon/android/java/src/org/chromium/components/favicon/LargeIconBridge.java
@@ -118,7 +118,13 @@ @Deprecated public boolean getLargeIconForStringUrl( final String pageUrl, int desiredSizePx, final LargeIconCallback callback) { - return getLargeIconForUrl(new GURL(pageUrl), desiredSizePx, callback); + return getLargeIconForUrl(new GURL(pageUrl), desiredSizePx, desiredSizePx, callback); + } + + /** Similar to the called method, but with the minSize and desiredSize combined. */ + public boolean getLargeIconForUrl( + final GURL pageUrl, int desiredSizePx, final LargeIconCallback callback) { + return getLargeIconForUrl(pageUrl, desiredSizePx, desiredSizePx, callback); } /** @@ -129,19 +135,20 @@ * given callback. * * @param pageUrl The URL of the page whose icon will be fetched. + * @param minSizePx The minimum acceptable size of the icon in pixels. * @param desiredSizePx The desired size of the icon in pixels. * @param callback The method to call asynchronously when the result is available. This callback * will not be called if this method returns false. * @return True if a callback should be expected. */ - public boolean getLargeIconForUrl( - final GURL pageUrl, int desiredSizePx, final LargeIconCallback callback) { + public boolean getLargeIconForUrl(final GURL pageUrl, int minSizePx, int desiredSizePx, + final LargeIconCallback callback) { assert mNativeLargeIconBridge != 0; assert callback != null; if (mFaviconCache == null) { return LargeIconBridgeJni.get().getLargeIconForURL(mNativeLargeIconBridge, - mBrowserContextHandle, pageUrl, desiredSizePx, callback); + mBrowserContextHandle, pageUrl, minSizePx, desiredSizePx, callback); } else { CachedFavicon cached = mFaviconCache.get(pageUrl); if (cached != null) { @@ -162,7 +169,7 @@ } }; return LargeIconBridgeJni.get().getLargeIconForURL(mNativeLargeIconBridge, - mBrowserContextHandle, pageUrl, desiredSizePx, callbackWrapper); + mBrowserContextHandle, pageUrl, minSizePx, desiredSizePx, callbackWrapper); } } @@ -178,7 +185,7 @@ long init(); void destroy(long nativeLargeIconBridge); boolean getLargeIconForURL(long nativeLargeIconBridge, - BrowserContextHandle browserContextHandle, GURL pageUrl, int desiredSizePx, - LargeIconCallback callback); + BrowserContextHandle browserContextHandle, GURL pageUrl, int minSizePx, + int desiredSizePx, LargeIconCallback callback); } }
diff --git a/components/favicon/android/large_icon_bridge.cc b/components/favicon/android/large_icon_bridge.cc index b98a84d..a06eacd 100644 --- a/components/favicon/android/large_icon_bridge.cc +++ b/components/favicon/android/large_icon_bridge.cc
@@ -74,6 +74,7 @@ const JavaParamRef<jobject>& j_browser_context, const JavaParamRef<jobject>& j_page_url, jint min_source_size_px, + jint desired_source_size_px, const JavaParamRef<jobject>& j_callback) { content::BrowserContext* browser_context = content::BrowserContextFromJavaHandle(j_browser_context); @@ -93,9 +94,8 @@ // Use desired_size = 0 for getting the icon from the cache (so that // the icon is not poorly rescaled by LargeIconService). LargeIconWorker::GetLargeIconRawBitmap( - favicon_provider, *url, min_source_size_px, - /*desired_size_in_pixel=*/0, std::move(callback_runner), {}, - &cancelable_task_tracker_); + favicon_provider, *url, min_source_size_px, desired_source_size_px, + std::move(callback_runner), {}, &cancelable_task_tracker_); return true; }
diff --git a/components/favicon/android/large_icon_bridge.h b/components/favicon/android/large_icon_bridge.h index db94ad6..ae44179f 100644 --- a/components/favicon/android/large_icon_bridge.h +++ b/components/favicon/android/large_icon_bridge.h
@@ -26,6 +26,7 @@ const base::android::JavaParamRef<jobject>& j_browser_context, const base::android::JavaParamRef<jobject>& j_page_url, jint min_source_size_px, + jint desired_source_size_px, const base::android::JavaParamRef<jobject>& j_callback); private:
diff --git a/components/favicon/core/favicon_database.cc b/components/favicon/core/favicon_database.cc index 5be550a..1e71a09d 100644 --- a/components/favicon/core/favicon_database.cc +++ b/components/favicon/core/favicon_database.cc
@@ -32,7 +32,7 @@ #include "url/origin.h" #if BUILDFLAG(IS_APPLE) -#include "base/mac/backup_util.h" +#include "base/apple/backup_util.h" #endif namespace favicon { @@ -1049,7 +1049,7 @@ #if BUILDFLAG(IS_APPLE) // Exclude the favicons file from backups. - base::mac::SetBackupExclusion(db_name); + base::apple::SetBackupExclusion(db_name); #endif // thumbnails table has been obsolete for a long time, remove any detritus.
diff --git a/components/history/core/browser/history_database.cc b/components/history/core/browser/history_database.cc index 8623684..8172deea 100644 --- a/components/history/core/browser/history_database.cc +++ b/components/history/core/browser/history_database.cc
@@ -29,7 +29,7 @@ #include "sql/transaction.h" #if BUILDFLAG(IS_APPLE) -#include "base/mac/backup_util.h" +#include "base/apple/backup_util.h" #endif namespace history { @@ -117,7 +117,7 @@ #if BUILDFLAG(IS_APPLE) // Exclude the history file from backups. - base::mac::SetBackupExclusion(history_name); + base::apple::SetBackupExclusion(history_name); #endif // Prime the cache.
diff --git a/components/memory_pressure/BUILD.gn b/components/memory_pressure/BUILD.gn index 288d66e9..b145b0a 100644 --- a/components/memory_pressure/BUILD.gn +++ b/components/memory_pressure/BUILD.gn
@@ -30,10 +30,9 @@ if (is_apple) { sources += [ + "system_memory_pressure_evaluator_mac.cc", "system_memory_pressure_evaluator_mac.h", - "system_memory_pressure_evaluator_mac.mm", ] - configs += [ "//build/config/compiler:enable_arc" ] } if (is_fuchsia) {
diff --git a/components/memory_pressure/system_memory_pressure_evaluator_mac.mm b/components/memory_pressure/system_memory_pressure_evaluator_mac.cc similarity index 75% rename from components/memory_pressure/system_memory_pressure_evaluator_mac.mm rename to components/memory_pressure/system_memory_pressure_evaluator_mac.cc index b417b8b..02c5729 100644 --- a/components/memory_pressure/system_memory_pressure_evaluator_mac.mm +++ b/components/memory_pressure/system_memory_pressure_evaluator_mac.cc
@@ -19,10 +19,6 @@ #include "base/memory/memory_pressure_monitor.h" #include "base/task/sequenced_task_runner.h" -#if !defined(__has_feature) || !__has_feature(objc_arc) -#error "This file requires ARC support." -#endif - namespace memory_pressure::mac { namespace { @@ -47,28 +43,22 @@ return base::MemoryPressureListener::MEMORY_PRESSURE_LEVEL_NONE; } -struct SystemMemoryPressureEvaluator::ObjCStorage { - // The dispatch source that generates memory pressure change notifications. - dispatch_source_t __strong memory_level_event_source; -}; - SystemMemoryPressureEvaluator::SystemMemoryPressureEvaluator( std::unique_ptr<MemoryPressureVoter> voter) : memory_pressure::SystemMemoryPressureEvaluator(std::move(voter)), + memory_level_event_source_(dispatch_source_create( + DISPATCH_SOURCE_TYPE_MEMORYPRESSURE, + 0, + DISPATCH_MEMORYPRESSURE_WARN | DISPATCH_MEMORYPRESSURE_CRITICAL | + DISPATCH_MEMORYPRESSURE_NORMAL, + dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0))), renotify_current_vote_timer_( FROM_HERE, kRenotifyVotePeriod, base::BindRepeating(&SystemMemoryPressureEvaluator::SendCurrentVote, base::Unretained(this), /*notify=*/true)), - objc_storage_(std::make_unique<ObjCStorage>()), weak_ptr_factory_(this) { - objc_storage_->memory_level_event_source = dispatch_source_create( - DISPATCH_SOURCE_TYPE_MEMORYPRESSURE, /*handle=*/0, - DISPATCH_MEMORYPRESSURE_WARN | DISPATCH_MEMORYPRESSURE_CRITICAL | - DISPATCH_MEMORYPRESSURE_NORMAL, - dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, /*flags=*/0)); - // WeakPtr needed because there is no guarantee that |this| is still be alive // when the task posted to the TaskRunner or event handler runs. base::WeakPtr<SystemMemoryPressureEvaluator> weak_this = @@ -77,25 +67,24 @@ base::SequencedTaskRunner::GetCurrentDefault(); // Attach an event handler to the memory pressure event source. - if (objc_storage_->memory_level_event_source) { - dispatch_source_set_event_handler( - objc_storage_->memory_level_event_source, ^{ - task_runner->PostTask( - FROM_HERE, - base::BindRepeating( - &SystemMemoryPressureEvaluator::OnMemoryPressureChanged, - weak_this)); - }); + if (memory_level_event_source_.get()) { + dispatch_source_set_event_handler(memory_level_event_source_, ^{ + task_runner->PostTask( + FROM_HERE, + base::BindRepeating( + &SystemMemoryPressureEvaluator::OnMemoryPressureChanged, + weak_this)); + }); // Start monitoring the event source. - dispatch_resume(objc_storage_->memory_level_event_source); + dispatch_resume(memory_level_event_source_); } } SystemMemoryPressureEvaluator::~SystemMemoryPressureEvaluator() { // Remove the memory pressure event source. - if (objc_storage_->memory_level_event_source) { - dispatch_source_cancel(objc_storage_->memory_level_event_source); + if (memory_level_event_source_.get()) { + dispatch_source_cancel(memory_level_event_source_); } } @@ -126,7 +115,7 @@ UpdatePressureLevel(); // Run the callback that's waiting on memory pressure change notifications. - // The convention is to not send notifications on memory pressure returning to + // The convention is to not send notifiations on memory pressure returning to // normal. bool notify = current_vote() != base::MemoryPressureListener::MEMORY_PRESSURE_LEVEL_NONE;
diff --git a/components/memory_pressure/system_memory_pressure_evaluator_mac.h b/components/memory_pressure/system_memory_pressure_evaluator_mac.h index ea6fe840..6f9075f 100644 --- a/components/memory_pressure/system_memory_pressure_evaluator_mac.h +++ b/components/memory_pressure/system_memory_pressure_evaluator_mac.h
@@ -9,13 +9,15 @@ #include <dispatch/dispatch.h> #include "base/mac/scoped_cftyperef.h" +#include "base/mac/scoped_dispatch_object.h" #include "base/message_loop/message_pump_mac.h" #include "base/sequence_checker.h" #include "base/timer/timer.h" #include "components/memory_pressure/memory_pressure_voter.h" #include "components/memory_pressure/system_memory_pressure_evaluator.h" -namespace memory_pressure::mac { +namespace memory_pressure { +namespace mac { class TestSystemMemoryPressureEvaluator; @@ -48,17 +50,18 @@ // Run |dispatch_callback| on memory pressure notifications from the OS. void OnMemoryPressureChanged(); + // The dispatch source that generates memory pressure change notifications. + base::ScopedDispatchObject<dispatch_source_t> memory_level_event_source_; + // Timer that will re-notify with the current vote at regular interval. base::RepeatingTimer renotify_current_vote_timer_; - struct ObjCStorage; - std::unique_ptr<ObjCStorage> objc_storage_; - SEQUENCE_CHECKER(sequence_checker_); base::WeakPtrFactory<SystemMemoryPressureEvaluator> weak_ptr_factory_; }; -} // namespace memory_pressure::mac +} // namespace mac +} // namespace memory_pressure #endif // COMPONENTS_MEMORY_PRESSURE_SYSTEM_MEMORY_PRESSURE_EVALUATOR_MAC_H_
diff --git a/components/nacl/common/BUILD.gn b/components/nacl/common/BUILD.gn index ecc28d0..7075f9c 100644 --- a/components/nacl/common/BUILD.gn +++ b/components/nacl/common/BUILD.gn
@@ -41,10 +41,6 @@ "//native_client/src/trusted/error_code", "//services/service_manager/public/cpp", ] - - if (is_apple) { - deps += [ "//base:base_arc" ] - } } # This exists just to make 'gn check' happy with :minimal. It can't
diff --git a/components/named_mojo_ipc_server/BUILD.gn b/components/named_mojo_ipc_server/BUILD.gn index c784f1c5..71a2f6f 100644 --- a/components/named_mojo_ipc_server/BUILD.gn +++ b/components/named_mojo_ipc_server/BUILD.gn
@@ -37,7 +37,6 @@ sources += [ "named_mojo_server_endpoint_connector_win.cc" ] } else if (is_mac) { sources += [ "named_mojo_server_endpoint_connector_mac.cc" ] - deps += [ "//base:base_arc" ] } else { sources += [ "named_mojo_server_endpoint_connector_unsupported.cc" ] }
diff --git a/components/omnibox/browser/BUILD.gn b/components/omnibox/browser/BUILD.gn index 0116332..71cc4bb 100644 --- a/components/omnibox/browser/BUILD.gn +++ b/components/omnibox/browser/BUILD.gn
@@ -506,15 +506,29 @@ ] } + android_library("scheme_classifier_java") { + resources_package = "org.chromium.components.omnibox" + sources = [ + "android/java/src/org/chromium/components/omnibox/AutocompleteSchemeClassifier.java", + "android/java/src/org/chromium/components/omnibox/OmniboxUrlEmphasizer.java", + "android/java/src/org/chromium/components/omnibox/SecurityStatusIcon.java", + ] + deps = [ + ":java_resources", + "//base:jni_java", + "//components/embedder_support/android:util_java", + "//components/security_state/core:security_state_enums_java", + "//third_party/androidx:androidx_annotation_annotation_java", + ] + annotation_processor_deps = [ "//base/android/jni_generator:jni_processor" ] + } + android_library("browser_java") { sources = [ "android/java/src/org/chromium/components/omnibox/AutocompleteMatch.java", "android/java/src/org/chromium/components/omnibox/AutocompleteResult.java", - "android/java/src/org/chromium/components/omnibox/AutocompleteSchemeClassifier.java", "android/java/src/org/chromium/components/omnibox/OmniboxMetrics.java", - "android/java/src/org/chromium/components/omnibox/OmniboxUrlEmphasizer.java", "android/java/src/org/chromium/components/omnibox/SecurityButtonAnimationDelegate.java", - "android/java/src/org/chromium/components/omnibox/SecurityStatusIcon.java", "android/java/src/org/chromium/components/omnibox/SuggestionAnswer.java", "android/java/src/org/chromium/components/omnibox/action/HistoryClustersAction.java", "android/java/src/org/chromium/components/omnibox/action/OmniboxAction.java", @@ -546,7 +560,10 @@ "//url:gurl_java", ] - public_deps = [ "//third_party/omnibox_proto:omnibox_proto_java" ] + public_deps = [ + ":scheme_classifier_java", + "//third_party/omnibox_proto:omnibox_proto_java", + ] srcjar_deps = [ ":browser_java_enums_srcjar" ] annotation_processor_deps = [ "//base/android/jni_generator:jni_processor" ]
diff --git a/components/omnibox/browser/autocomplete_controller.cc b/components/omnibox/browser/autocomplete_controller.cc index c826c61..7c5a98b 100644 --- a/components/omnibox/browser/autocomplete_controller.cc +++ b/components/omnibox/browser/autocomplete_controller.cc
@@ -208,10 +208,12 @@ if (match.provider) { if (match.provider->type() == AutocompleteProvider::TYPE_ZERO_SUGGEST && (match.type == AutocompleteMatchType::SEARCH_SUGGEST || + match.type == AutocompleteMatchType::TILE_NAVSUGGEST || match.type == AutocompleteMatchType::NAVSUGGEST)) { // Make sure changes here are reflected in UpdateAssistedQueryStats() // below in which the zero-prefix suggestions are counted. - if (match.type == AutocompleteMatchType::NAVSUGGEST) { + if (match.type == AutocompleteMatchType::TILE_NAVSUGGEST || + match.type == AutocompleteMatchType::NAVSUGGEST) { subtypes->emplace(omnibox::SUBTYPE_ZERO_PREFIX_LOCAL_FREQUENT_URLS); } // We abuse this subtype and use it to for zero-suggest suggestions that @@ -247,7 +249,6 @@ } case AutocompleteMatchType::SEARCH_SUGGEST_PERSONALIZED: { *type = omnibox::TYPE_PERSONALIZED_QUERY; - ; subtypes->emplace(omnibox::SUBTYPE_PERSONAL); return; } @@ -255,6 +256,7 @@ *type = omnibox::TYPE_ENTITY; return; } + case AutocompleteMatchType::TILE_NAVSUGGEST: case AutocompleteMatchType::NAVSUGGEST: { // Do not set subtype here; subtype may have been set above. *type = omnibox::TYPE_NAVIGATION; @@ -1244,6 +1246,9 @@ auto subtypes = match->subtypes; omnibox::SuggestType type = omnibox::TYPE_NATIVE_CHROME; GetMatchTypeAndExtendSubtypes(*match, &type, &subtypes); + DCHECK_EQ(match->suggest_type, type) + << "AutocompleteMatchType: " + << AutocompleteMatchType::ToString(match->type); // Count any suggestions that constitute zero-prefix suggestions. if (subtypes.contains(omnibox::SUBTYPE_ZERO_PREFIX_LOCAL_HISTORY) ||
diff --git a/components/omnibox/browser/autocomplete_match.cc b/components/omnibox/browser/autocomplete_match.cc index 9dd2d0f..bf665344 100644 --- a/components/omnibox/browser/autocomplete_match.cc +++ b/components/omnibox/browser/autocomplete_match.cc
@@ -280,8 +280,9 @@ answer(match.answer), transition(match.transition), type(match.type), - has_tab_match(match.has_tab_match), + suggest_type(match.suggest_type), subtypes(match.subtypes), + has_tab_match(match.has_tab_match), associated_keyword(match.associated_keyword ? new AutocompleteMatch(*match.associated_keyword) : nullptr), @@ -341,8 +342,9 @@ answer = std::move(match.answer); transition = std::move(match.transition); type = std::move(match.type); - has_tab_match = std::move(match.has_tab_match); + suggest_type = std::move(match.suggest_type); subtypes = std::move(match.subtypes); + has_tab_match = std::move(match.has_tab_match); associated_keyword = std::move(match.associated_keyword); keyword = std::move(match.keyword); from_keyword = std::move(match.from_keyword); @@ -405,8 +407,9 @@ answer = match.answer; transition = match.transition; type = match.type; - has_tab_match = match.has_tab_match; + suggest_type = match.suggest_type; subtypes = match.subtypes; + has_tab_match = match.has_tab_match; associated_keyword.reset( match.associated_keyword ? new AutocompleteMatch(*match.associated_keyword) @@ -1357,6 +1360,7 @@ fill_into_edit == duplicate_match.fill_into_edit && IsSearchHistoryType(duplicate_match.type)) { type = duplicate_match.type; + suggest_type = duplicate_match.suggest_type; } // And always absorb the higher relevance score of duplicates.
diff --git a/components/omnibox/browser/autocomplete_match.h b/components/omnibox/browser/autocomplete_match.h index b701797e..9cf0058b 100644 --- a/components/omnibox/browser/autocomplete_match.h +++ b/components/omnibox/browser/autocomplete_match.h
@@ -744,24 +744,37 @@ // Type of this match. Type type = AutocompleteMatchType::SEARCH_WHAT_YOU_TYPED; - // True if we saw a tab that matched this suggestion. - // Unset if it has not been computed yet. - absl::optional<bool> has_tab_match; + // The type of this suggestion as reported from and back to the suggest server + // via the server response and the ChromeSearchboxStats (reported in the match + // destination URL) respectively. + // The default value indicates a native Chrome suggestion which must include a + // SUBTYPE_OMNIBOX_* in `subtypes`. + // + // The value is always present in omnibox::SuggestType enum. Although the list + // of types in omnibox::SuggestType enum may not be exhaustive, the known type + // names found in the server response are mapped to the equivalent enum values + // and the unknown types fall back to omnibox::TYPE_QUERY. + omnibox::SuggestType suggest_type{omnibox::TYPE_NATIVE_CHROME}; // Used to identify the specific source / type for suggestions by the // suggest server. See SuggestSubtype in types.proto for more details. // Uses flat_set to deduplicate subtypes (e.g., as a result of Chrome adding - // additional subtypes). The order of elements reported back via AQS is - // irrelevant. flat_set uses std::vector as a container, reducing memory - // overhead of keeping a handful of integers, while offering similar - // functionality as std::set. - // Note this set may contain int values not present in omnibox::SuggestSubtype + // additional subtypes). The order of elements reported back via + // ChromeSearchboxStats is irrelevant. flat_set uses std::vector as a + // container, reducing memory overhead of keeping a handful of integers, while + // offering similar functionality as std::set. + // + // This set may contain int values not present in omnibox::SuggestSubtype // enum. This is because the list of subtypes in omnibox::SuggestSubtype enum // is not exhaustive. However, casting int values into omnibox::SuggestSubtype // enum without testing membership is expected to be safe as // omnibox::SuggestSubtype enum has a fixed int underlying type. base::flat_set<omnibox::SuggestSubtype> subtypes; + // True if we saw a tab that matched this suggestion. + // Unset if it has not been computed yet. + absl::optional<bool> has_tab_match; + // Set with a keyword provider match if this match can show a keyword hint. // For example, if this is a SearchProvider match for "www.amazon.com", // |associated_keyword| could be a KeywordProvider match for "amazon.com".
diff --git a/components/omnibox/browser/autocomplete_provider_unittest.cc b/components/omnibox/browser/autocomplete_provider_unittest.cc index 2db5128c..7e6c844d 100644 --- a/components/omnibox/browser/autocomplete_provider_unittest.cc +++ b/components/omnibox/browser/autocomplete_provider_unittest.cc
@@ -351,6 +351,7 @@ const AutocompleteMatch::Type match_type; const std::string expected_aqs; const omnibox::metrics::ChromeSearchboxStats expected_searchbox_stats; + omnibox::SuggestType type; base::flat_set<omnibox::SuggestSubtype> subtypes; }; @@ -648,6 +649,7 @@ match.keyword = kTestTemplateURLKeyword; match.search_terms_args = std::make_unique<TemplateURLRef::SearchTermsArgs>(std::u16string()); + match.suggest_type = aqs_test_data[i].type; match.subtypes = aqs_test_data[i].subtypes; matches.push_back(match); } @@ -1016,7 +1018,8 @@ omnibox::metrics::ChromeSearchboxStats searchbox_stats; AssistedQueryStatsTestData test_data[] = { // MSVC doesn't support zero-length arrays, so supply some dummy data. - {AutocompleteMatchType::SEARCH_WHAT_YOU_TYPED, "", searchbox_stats}}; + {AutocompleteMatchType::SEARCH_WHAT_YOU_TYPED, "", searchbox_stats, + omnibox::TYPE_NATIVE_CHROME}}; SCOPED_TRACE("No matches"); // Note: We pass 0 here to ignore the dummy data above. RunAssistedQueryStatsTest(test_data, 0); @@ -1036,7 +1039,7 @@ AssistedQueryStatsTestData test_data[] = { {AutocompleteMatchType::SEARCH_WHAT_YOU_TYPED, "chrome..69i57", - searchbox_stats}}; + searchbox_stats, omnibox::TYPE_NATIVE_CHROME}}; SCOPED_TRACE("One match"); RunAssistedQueryStatsTest(test_data, std::size(test_data)); } @@ -1057,6 +1060,7 @@ {AutocompleteMatchType::SEARCH_SUGGEST_ENTITY, "chrome.0.46i39", searchbox_stats, + omnibox::TYPE_ENTITY, {omnibox::SUBTYPE_PERSONAL}}}; SCOPED_TRACE("One match with provider populated subtypes"); RunAssistedQueryStatsTest(test_data, std::size(test_data)); @@ -1126,6 +1130,7 @@ {AutocompleteMatchType::SEARCH_SUGGEST, "chrome.0.0i39i143i362j46i39i143l2j46i39i143i362j46i39i143", searchbox_stats_0, + omnibox::TYPE_QUERY, {omnibox::SUBTYPE_PERSONAL, omnibox::SUBTYPE_TRENDS, omnibox::SUBTYPE_ZERO_PREFIX, omnibox::SUBTYPE_TRENDS}}, // The next two matches should be detected as the same type, despite @@ -1133,10 +1138,12 @@ {AutocompleteMatchType::SEARCH_SUGGEST_ENTITY, "chrome.1.0i39i143i362j46i39i143l2j46i39i143i362j46i39i143", searchbox_stats_1, + omnibox::TYPE_ENTITY, {omnibox::SUBTYPE_PERSONAL, omnibox::SUBTYPE_TRENDS}}, {AutocompleteMatchType::SEARCH_SUGGEST_ENTITY, "chrome.2.0i39i143i362j46i39i143l2j46i39i143i362j46i39i143", searchbox_stats_2, + omnibox::TYPE_ENTITY, {omnibox::SUBTYPE_PERSONAL, omnibox::SUBTYPE_TRENDS, omnibox::SUBTYPE_PERSONAL}}, // This match should not be bundled together with previous two, because @@ -1144,6 +1151,7 @@ {AutocompleteMatchType::SEARCH_SUGGEST_ENTITY, "chrome.3.0i39i143i362j46i39i143l2j46i39i143i362j46i39i143", searchbox_stats_3, + omnibox::TYPE_ENTITY, {omnibox::SUBTYPE_PERSONAL, omnibox::SUBTYPE_TRENDS, omnibox::SUBTYPE_ZERO_PREFIX}}, // This match should not be bundled together with the group before, @@ -1151,6 +1159,7 @@ {AutocompleteMatchType::SEARCH_SUGGEST_ENTITY, "chrome.4.0i39i143i362j46i39i143l2j46i39i143i362j46i39i143", searchbox_stats_4, + omnibox::TYPE_ENTITY, {omnibox::SUBTYPE_PERSONAL, omnibox::SUBTYPE_TRENDS}}, }; SCOPED_TRACE("Complex set of matches with repetitive subtypes"); @@ -1239,33 +1248,36 @@ AssistedQueryStatsTestData test_data[] = { {AutocompleteMatchType::SEARCH_WHAT_YOU_TYPED, "chrome..69i57j69i58j5l2j0i362j0i362i450j0i362i451j69i59", - searchbox_stats_0}, + searchbox_stats_0, omnibox::TYPE_NATIVE_CHROME}, {AutocompleteMatchType::URL_WHAT_YOU_TYPED, "chrome..69i57j69i58j5l2j0i362j0i362i450j0i362i451j69i59", - searchbox_stats_1}, + searchbox_stats_1, omnibox::TYPE_NATIVE_CHROME}, {AutocompleteMatchType::NAVSUGGEST, "chrome.2.69i57j69i58j5l2j0i362j0i362i450j0i362i451j69i59", - searchbox_stats_2}, + searchbox_stats_2, omnibox::TYPE_NAVIGATION}, {AutocompleteMatchType::NAVSUGGEST, "chrome.3.69i57j69i58j5l2j0i362j0i362i450j0i362i451j69i59", - searchbox_stats_3}, + searchbox_stats_3, omnibox::TYPE_NAVIGATION}, {AutocompleteMatchType::SEARCH_SUGGEST, "chrome.4.69i57j69i58j5l2j0i362j0i362i450j0i362i451j69i59", searchbox_stats_4, + omnibox::TYPE_QUERY, {omnibox::SUBTYPE_ZERO_PREFIX}}, {AutocompleteMatchType::SEARCH_SUGGEST, "chrome.5.69i57j69i58j5l2j0i362j0i362i450j0i362i451j69i59", searchbox_stats_5, + omnibox::TYPE_QUERY, {omnibox::SUBTYPE_ZERO_PREFIX, omnibox::SUBTYPE_ZERO_PREFIX_LOCAL_HISTORY}}, {AutocompleteMatchType::SEARCH_SUGGEST, "chrome.6.69i57j69i58j5l2j0i362j0i362i450j0i362i451j69i59", searchbox_stats_6, + omnibox::TYPE_QUERY, {omnibox::SUBTYPE_ZERO_PREFIX, omnibox::SUBTYPE_ZERO_PREFIX_LOCAL_FREQUENT_URLS}}, {AutocompleteMatchType::SEARCH_HISTORY, "chrome.7.69i57j69i58j5l2j0i362j0i362i450j0i362i451j69i59", - searchbox_stats_7}, + searchbox_stats_7, omnibox::TYPE_NATIVE_CHROME}, }; SCOPED_TRACE("Trivial and zero-prefix matches"); RunAssistedQueryStatsTest(test_data, std::size(test_data));
diff --git a/components/omnibox/browser/base_search_provider.cc b/components/omnibox/browser/base_search_provider.cc index 83c1aeb..35f6566 100644 --- a/components/omnibox/browser/base_search_provider.cc +++ b/components/omnibox/browser/base_search_provider.cc
@@ -133,6 +133,7 @@ match.contents_class = suggestion.match_contents_class(); match.suggestion_group_id = suggestion.suggestion_group_id(); match.answer = suggestion.answer(); + match.suggest_type = suggestion.suggest_type(); for (const int subtype : suggestion.subtypes()) { match.subtypes.insert(SuggestSubtypeForNumber(subtype)); } @@ -217,7 +218,8 @@ // mode. They also assume the caller knows what it's doing and we set // this match to look as if it was received/created synchronously. SearchSuggestionParser::SuggestResult suggest_result( - suggestion, type, /*subtypes=*/{}, from_keyword, + suggestion, type, /*suggest_type=*/omnibox::TYPE_NATIVE_CHROME, + /*subtypes=*/{}, from_keyword, /*relevance=*/0, /*relevance_from_server=*/false, /*input_text=*/std::u16string()); suggest_result.set_received_after_last_keystroke(false); @@ -237,10 +239,12 @@ int accepted_suggestion, bool is_tail_suggestion) { AutocompleteMatchType::Type match_type; + omnibox::SuggestType suggest_type = omnibox::TYPE_NATIVE_CHROME; std::u16string match_contents, match_contents_prefix; if (is_tail_suggestion) { match_type = AutocompleteMatchType::SEARCH_SUGGEST_TAIL; + suggest_type = omnibox::TYPE_TAIL; std::u16string sanitized_suggestion = AutocompleteMatch::SanitizeString(suggestion); match_contents = GetMatchContentsForOnDeviceTailSuggestion( @@ -251,12 +255,14 @@ 0, sanitized_suggestion.size() - match_contents.size()); } else { match_type = AutocompleteMatchType::SEARCH_SUGGEST; + suggest_type = omnibox::TYPE_QUERY; match_contents = suggestion; } SearchSuggestionParser::SuggestResult suggest_result( - suggestion, match_type, /*subtypes=*/{omnibox::SUBTYPE_SUGGEST_2G_LITE}, - match_contents, match_contents_prefix, + suggestion, match_type, suggest_type, + /*subtypes=*/{omnibox::SUBTYPE_SUGGEST_2G_LITE}, match_contents, + match_contents_prefix, /*annotation=*/std::u16string(), /*entity_info=*/omnibox::EntityInfo(), /*deletion_url=*/"",
diff --git a/components/omnibox/browser/base_search_provider_unittest.cc b/components/omnibox/browser/base_search_provider_unittest.cc index 2f554fb8..06f438b 100644 --- a/components/omnibox/browser/base_search_provider_unittest.cc +++ b/components/omnibox/browser/base_search_provider_unittest.cc
@@ -34,6 +34,7 @@ SearchSuggestionParser::SuggestResult BuildSuggestion( const std::u16string& query, AutocompleteMatchType::Type type, + omnibox::SuggestType suggest_type, std::vector<int> subtypes, const std::string& additional_query_params, int relevance, @@ -44,6 +45,7 @@ return SearchSuggestionParser::SuggestResult( /*suggestion=*/query, /*type=*/type, + /*suggest_type=*/suggest_type, /*subtypes=*/subtypes, /*match_contents=*/query, /*match_contents_prefix=*/u"", @@ -148,7 +150,7 @@ answer.set_type(2334); SearchSuggestionParser::SuggestResult more_relevant( - query, AutocompleteMatchType::SEARCH_HISTORY, + query, AutocompleteMatchType::SEARCH_HISTORY, omnibox::TYPE_NATIVE_CHROME, /*subtypes=*/{}, /*from_keyword=*/false, /*relevance=*/1300, /*relevance_from_server=*/true, /*input_text=*/query); @@ -158,7 +160,7 @@ TemplateURLRef::NO_SUGGESTION_CHOSEN, false, false, &map); SearchSuggestionParser::SuggestResult less_relevant( - query, AutocompleteMatchType::SEARCH_SUGGEST, + query, AutocompleteMatchType::SEARCH_SUGGEST, omnibox::TYPE_QUERY, /*subtypes=*/{}, /*from_keyword=*/false, /*relevance=*/850, /*relevance_from_server=*/true, /*input_text=*/query); @@ -175,10 +177,12 @@ EXPECT_TRUE(answer.Equals(*match.answer)); EXPECT_EQ(AutocompleteMatchType::SEARCH_HISTORY, match.type); + EXPECT_EQ(omnibox::TYPE_NATIVE_CHROME, match.suggest_type); EXPECT_EQ(1300, match.relevance); EXPECT_TRUE(answer.Equals(*duplicate.answer)); EXPECT_EQ(AutocompleteMatchType::SEARCH_SUGGEST, duplicate.type); + EXPECT_EQ(omnibox::TYPE_QUERY, duplicate.suggest_type); EXPECT_EQ(850, duplicate.relevance); // Ensure answers are not copied over existing answers. @@ -186,7 +190,7 @@ SuggestionAnswer answer2; answer2.set_type(8242); more_relevant = SearchSuggestionParser::SuggestResult( - query, AutocompleteMatchType::SEARCH_HISTORY, + query, AutocompleteMatchType::SEARCH_HISTORY, omnibox::TYPE_NATIVE_CHROME, /*subtypes=*/{}, /*from_keyword=*/false, /*relevance=*/1300, /*relevance_from_server=*/true, /*input_text=*/query); @@ -206,10 +210,12 @@ EXPECT_TRUE(answer2.Equals(*match.answer)); EXPECT_EQ(AutocompleteMatchType::SEARCH_HISTORY, match.type); + EXPECT_EQ(omnibox::TYPE_NATIVE_CHROME, match.suggest_type); EXPECT_EQ(1300, match.relevance); EXPECT_TRUE(answer.Equals(*duplicate.answer)); EXPECT_EQ(AutocompleteMatchType::SEARCH_SUGGEST, duplicate.type); + EXPECT_EQ(omnibox::TYPE_QUERY, duplicate.suggest_type); EXPECT_EQ(850, duplicate.relevance); } @@ -223,10 +229,11 @@ // Ensure that a match with empty additional query params is added to the map // without a pre-computed `stripped_destination_url`. - SearchSuggestionParser::SuggestResult plain_text = BuildSuggestion( - query, AutocompleteMatchType::SEARCH_HISTORY, {omnibox::SUBTYPE_PERSONAL}, - /*additional_query_params=*/"", - /*relevance=*/1300, /*should_prerender=*/false); + SearchSuggestionParser::SuggestResult plain_text = + BuildSuggestion(query, AutocompleteMatchType::SEARCH_HISTORY, + omnibox::TYPE_NATIVE_CHROME, {omnibox::SUBTYPE_PERSONAL}, + /*additional_query_params=*/"", + /*relevance=*/1300, /*should_prerender=*/false); provider_->AddMatchToMap( plain_text, std::string(), AutocompleteInput(), template_url.get(), client_->GetTemplateURLService()->search_terms_data(), @@ -243,10 +250,11 @@ // additional query params, and with a lower relevance is added as a duplicate // of the existing match in the map without a pre-computed // `stripped_destination_url`. - SearchSuggestionParser::SuggestResult duplicate_plain_text = BuildSuggestion( - query, AutocompleteMatchType::SEARCH_HISTORY, {omnibox::SUBTYPE_PERSONAL}, - /*additional_query_params=*/"", - /*relevance=*/1299, /*should_prerender=*/false); + SearchSuggestionParser::SuggestResult duplicate_plain_text = + BuildSuggestion(query, AutocompleteMatchType::SEARCH_HISTORY, + omnibox::TYPE_NATIVE_CHROME, {omnibox::SUBTYPE_PERSONAL}, + /*additional_query_params=*/"", + /*relevance=*/1299, /*should_prerender=*/false); provider_->AddMatchToMap( duplicate_plain_text, std::string(), AutocompleteInput(), template_url.get(), client_->GetTemplateURLService()->search_terms_data(), @@ -263,10 +271,11 @@ // Ensure that the first match, with duplicate search terms and a unique // non-empty additional query params, is added to the map without a // pre-computed `stripped_destination_url`. - SearchSuggestionParser::SuggestResult entity_1 = BuildSuggestion( - query, AutocompleteMatchType::SEARCH_HISTORY, {omnibox::SUBTYPE_PERSONAL}, - /*additional_query_params=*/"gs_ssp=1", - /*relevance=*/1298, /*should_prerender=*/false); + SearchSuggestionParser::SuggestResult entity_1 = + BuildSuggestion(query, AutocompleteMatchType::SEARCH_HISTORY, + omnibox::TYPE_NATIVE_CHROME, {omnibox::SUBTYPE_PERSONAL}, + /*additional_query_params=*/"gs_ssp=1", + /*relevance=*/1298, /*should_prerender=*/false); provider_->AddMatchToMap( entity_1, std::string(), AutocompleteInput(), template_url.get(), client_->GetTemplateURLService()->search_terms_data(), @@ -283,10 +292,11 @@ // non-empty additional query params, is added to the map with a pre-computed // `stripped_destination_url`, if omnibox::kDisambiguateEntitySuggestions is // enabled. - SearchSuggestionParser::SuggestResult entity_2 = BuildSuggestion( - query, AutocompleteMatchType::SEARCH_HISTORY, {omnibox::SUBTYPE_PERSONAL}, - /*additional_query_params=*/"gs_ssp=2", - /*relevance=*/1297, /*should_prerender=*/false); + SearchSuggestionParser::SuggestResult entity_2 = + BuildSuggestion(query, AutocompleteMatchType::SEARCH_HISTORY, + omnibox::TYPE_NATIVE_CHROME, {omnibox::SUBTYPE_PERSONAL}, + /*additional_query_params=*/"gs_ssp=2", + /*relevance=*/1297, /*should_prerender=*/false); provider_->AddMatchToMap( entity_2, std::string(), AutocompleteInput(), template_url.get(), client_->GetTemplateURLService()->search_terms_data(), @@ -303,10 +313,11 @@ // Ensure that a duplicate match, with identical search terms and additional // query params, and with a lower relevance is added as a duplicate of the // existing match in the map. - SearchSuggestionParser::SuggestResult duplicate_1_entity_2 = BuildSuggestion( - query, AutocompleteMatchType::SEARCH_HISTORY, {omnibox::SUBTYPE_PERSONAL}, - /*additional_query_params=*/"gs_ssp=2", - /*relevance=*/1296, /*should_prerender=*/false); + SearchSuggestionParser::SuggestResult duplicate_1_entity_2 = + BuildSuggestion(query, AutocompleteMatchType::SEARCH_HISTORY, + omnibox::TYPE_NATIVE_CHROME, {omnibox::SUBTYPE_PERSONAL}, + /*additional_query_params=*/"gs_ssp=2", + /*relevance=*/1296, /*should_prerender=*/false); provider_->AddMatchToMap( duplicate_1_entity_2, std::string(), AutocompleteInput(), template_url.get(), client_->GetTemplateURLService()->search_terms_data(), @@ -325,10 +336,11 @@ // query params, and with a higher relevance replaces the existing match in // the map with a pre-computed `stripped_destination_url`, if // omnibox::kDisambiguateEntitySuggestions is enabled. - SearchSuggestionParser::SuggestResult duplicate_2_entity_2 = BuildSuggestion( - query, AutocompleteMatchType::SEARCH_HISTORY, {omnibox::SUBTYPE_PERSONAL}, - /*additional_query_params=*/"gs_ssp=2", - /*relevance=*/1301, /*should_prerender=*/false); + SearchSuggestionParser::SuggestResult duplicate_2_entity_2 = + BuildSuggestion(query, AutocompleteMatchType::SEARCH_HISTORY, + omnibox::TYPE_NATIVE_CHROME, {omnibox::SUBTYPE_PERSONAL}, + /*additional_query_params=*/"gs_ssp=2", + /*relevance=*/1301, /*should_prerender=*/false); provider_->AddMatchToMap( duplicate_2_entity_2, std::string(), AutocompleteInput(), template_url.get(), client_->GetTemplateURLService()->search_terms_data(), @@ -355,10 +367,10 @@ std::u16string query = u"angeles now"; std::u16string suggestion = u"weather los " + query; - SearchSuggestionParser::SuggestResult suggest_result = - BuildSuggestion(suggestion, AutocompleteMatchType::SEARCH_SUGGEST_TAIL, - /*subtypes=*/{}, /*additional_query_params=*/"", - /*relevance=*/1300, /*should_prerender=*/false); + SearchSuggestionParser::SuggestResult suggest_result = BuildSuggestion( + suggestion, AutocompleteMatchType::SEARCH_SUGGEST_TAIL, + omnibox::TYPE_TAIL, /*subtypes=*/{}, /*additional_query_params=*/"", + /*relevance=*/1300, /*should_prerender=*/false); TestBaseSearchProvider::MatchMap map; provider_->AddMatchToMap( @@ -386,6 +398,7 @@ SearchSuggestionParser::SuggestResult more_relevant( query, AutocompleteMatchType::SEARCH_WHAT_YOU_TYPED, + omnibox::TYPE_NATIVE_CHROME, /*subtypes=*/{}, /*from_keyword=*/false, /*relevance=*/850, /*relevance_from_server=*/true, /*input_text=*/query); @@ -395,7 +408,7 @@ TemplateURLRef::NO_SUGGESTION_CHOSEN, false, false, &map); SearchSuggestionParser::SuggestResult less_relevant( - query, AutocompleteMatchType::SEARCH_HISTORY, + query, AutocompleteMatchType::SEARCH_HISTORY, omnibox::TYPE_NATIVE_CHROME, /*subtypes=*/{}, /*from_keyword=*/false, /*relevance=*/735, /*relevance_from_server=*/true, /*input_text=*/query); @@ -427,7 +440,7 @@ SearchSuggestionParser::SuggestResult default_suggestion( query, AutocompleteMatchType::SEARCH_WHAT_YOU_TYPED, - /*subtypes=*/{}, /*from_keyword=*/false, + omnibox::TYPE_NATIVE_CHROME, /*subtypes=*/{}, /*from_keyword=*/false, /*relevance=*/850, /*relevance_from_server=*/true, /*input_text=*/query); provider_->AddMatchToMap( @@ -437,10 +450,10 @@ /*mark_as_deletable=*/false, /*in_keyword_mode=*/false, &map); - SearchSuggestionParser::SuggestResult prerender_suggestion = - BuildSuggestion(query, AutocompleteMatchType::SEARCH_SUGGEST, - /*subtypes=*/{}, /*additional_query_params=*/"", - /*relevance=*/850, /*should_prerender=*/true); + SearchSuggestionParser::SuggestResult prerender_suggestion = BuildSuggestion( + query, AutocompleteMatchType::SEARCH_SUGGEST, omnibox::TYPE_QUERY, + /*subtypes=*/{}, /*additional_query_params=*/"", + /*relevance=*/850, /*should_prerender=*/true); provider_->AddMatchToMap( prerender_suggestion, std::string(), AutocompleteInput(), template_url.get(), client_->GetTemplateURLService()->search_terms_data(), @@ -487,5 +500,7 @@ ASSERT_EQ(match.type, is_tail_suggestion ? AutocompleteMatchType::SEARCH_SUGGEST_TAIL : AutocompleteMatchType::SEARCH_SUGGEST); + ASSERT_EQ(match.suggest_type, + is_tail_suggestion ? omnibox::TYPE_TAIL : omnibox::TYPE_QUERY); } }
diff --git a/components/omnibox/browser/builtin_provider.cc b/components/omnibox/browser/builtin_provider.cc index 61cce80..63d10f5 100644 --- a/components/omnibox/browser/builtin_provider.cc +++ b/components/omnibox/browser/builtin_provider.cc
@@ -192,6 +192,7 @@ const ACMatchClassifications& styles) { AutocompleteMatch match(this, kRelevance, false, AutocompleteMatchType::NAVSUGGEST); + match.suggest_type = omnibox::TYPE_NAVIGATION; match.fill_into_edit = match_string; match.inline_autocompletion = inline_completion; match.destination_url = GURL(match_string);
diff --git a/components/omnibox/browser/local_history_zero_suggest_provider.cc b/components/omnibox/browser/local_history_zero_suggest_provider.cc index edcd65f..91d15aa 100644 --- a/components/omnibox/browser/local_history_zero_suggest_provider.cc +++ b/components/omnibox/browser/local_history_zero_suggest_provider.cc
@@ -215,6 +215,7 @@ SearchSuggestionParser::SuggestResult suggestion( /*suggestion=*/result->normalized_term, AutocompleteMatchType::SEARCH_HISTORY, + /*suggest_type=*/omnibox::TYPE_NATIVE_CHROME, /*subtypes=*/{}, /*from_keyword=*/false, relevance--, /*relevance_from_server=*/false, /*input_text=*/base::ASCIIToUTF16(std::string()));
diff --git a/components/omnibox/browser/most_visited_sites_provider.cc b/components/omnibox/browser/most_visited_sites_provider.cc index 4df906d..4f48574 100644 --- a/components/omnibox/browser/most_visited_sites_provider.cc +++ b/components/omnibox/browser/most_visited_sites_provider.cc
@@ -51,6 +51,7 @@ int relevance, AutocompleteMatchType::Type type) { AutocompleteMatch match(provider, relevance, true, type); + match.suggest_type = omnibox::TYPE_NAVIGATION; match.destination_url = url; match.fill_into_edit +=
diff --git a/components/omnibox/browser/search_provider.cc b/components/omnibox/browser/search_provider.cc index 514f09e..f928056 100644 --- a/components/omnibox/browser/search_provider.cc +++ b/components/omnibox/browser/search_provider.cc
@@ -987,6 +987,7 @@ SearchSuggestionParser::SuggestResult verbatim( /*suggestion=*/trimmed_verbatim, AutocompleteMatchType::SEARCH_WHAT_YOU_TYPED, + /*suggest_type=*/omnibox::TYPE_NATIVE_CHROME, /*subtypes=*/{}, /*from_keyword=*/false, verbatim_relevance, relevance_from_server, /*input_text=*/trimmed_verbatim); @@ -1021,6 +1022,7 @@ SearchSuggestionParser::SuggestResult verbatim( /*suggestion=*/trimmed_verbatim, AutocompleteMatchType::SEARCH_OTHER_ENGINE, + /*suggest_type=*/omnibox::TYPE_NATIVE_CHROME, /*subtypes=*/{}, /*from_keyword=*/true, keyword_verbatim_relevance, keyword_relevance_from_server, /*input_text=*/trimmed_verbatim); @@ -1203,7 +1205,9 @@ } SearchSuggestionParser::SuggestResult history_suggestion( /*suggestion=*/trimmed_suggestion, - AutocompleteMatchType::SEARCH_HISTORY, {}, is_keyword, relevance, + AutocompleteMatchType::SEARCH_HISTORY, + /*suggest_type=*/omnibox::TYPE_NATIVE_CHROME, /*subtypes=*/{}, + is_keyword, relevance, /*relevance_from_server=*/false, /*input_text=*/trimmed_input); // History results are synchronous; they are received on the last keystroke. history_suggestion.set_received_after_last_keystroke(false); @@ -1448,6 +1452,7 @@ AutocompleteMatch match(this, navigation.relevance(), false, navigation.type()); match.destination_url = navigation.url(); + match.suggest_type = navigation.suggest_type(); for (const int subtype : navigation.subtypes()) { match.subtypes.insert(SuggestSubtypeForNumber(subtype)); }
diff --git a/components/omnibox/browser/search_suggestion_parser.cc b/components/omnibox/browser/search_suggestion_parser.cc index 7a3be88..bd173cc 100644 --- a/components/omnibox/browser/search_suggestion_parser.cc +++ b/components/omnibox/browser/search_suggestion_parser.cc
@@ -44,22 +44,61 @@ namespace { -AutocompleteMatchType::Type GetAutocompleteMatchType(const std::string& type) { - if (type == "CALCULATOR") - return AutocompleteMatchType::CALCULATOR; - if (type == "ENTITY") - return AutocompleteMatchType::SEARCH_SUGGEST_ENTITY; - if (type == "TAIL") - return AutocompleteMatchType::SEARCH_SUGGEST_TAIL; - if (type == "PERSONALIZED_QUERY") - return AutocompleteMatchType::SEARCH_SUGGEST_PERSONALIZED; - if (type == "PROFILE") - return AutocompleteMatchType::SEARCH_SUGGEST_PROFILE; - if (type == "NAVIGATION") - return AutocompleteMatchType::NAVSUGGEST; - if (type == "PERSONALIZED_NAVIGATION") - return AutocompleteMatchType::NAVSUGGEST_PERSONALIZED; - return AutocompleteMatchType::SEARCH_SUGGEST; +// Converts a suggestion type name found in the JSON response to an equivalent +// omnibox::SuggestType enum value. +omnibox::SuggestType GetSuggestType(const std::string& type) { + if (type == "CALCULATOR") { + return omnibox::TYPE_CALCULATOR; + } + if (type == "ENTITY") { + return omnibox::TYPE_ENTITY; + } + if (type == "TAIL") { + return omnibox::TYPE_TAIL; + } + if (type == "PERSONALIZED_QUERY") { + return omnibox::TYPE_PERSONALIZED_QUERY; + } + if (type == "PROFILE") { + return omnibox::TYPE_PROFILE; + } + if (type == "NAVIGATION") { + return omnibox::TYPE_NAVIGATION; + } + if (type == "PERSONALIZED_NAVIGATION") { + return omnibox::TYPE_PERSONALIZED_NAVIGATION; + } + if (type == "CHROME_QUERY_TILES") { + return omnibox::TYPE_CHROME_QUERY_TILES; + } + if (type == "CATEGORICAL_QUERY") { + return omnibox::TYPE_CATEGORICAL_QUERY; + } + return omnibox::TYPE_QUERY; +} + +// Converts an omnibox::SuggestType enum value to an equivalent +// AutocompleteMatchType::Type enum values. +AutocompleteMatchType::Type GetAutocompleteMatchType( + omnibox::SuggestType suggest_type) { + switch (suggest_type) { + case omnibox::TYPE_CALCULATOR: + return AutocompleteMatchType::CALCULATOR; + case omnibox::TYPE_ENTITY: + return AutocompleteMatchType::SEARCH_SUGGEST_ENTITY; + case omnibox::TYPE_TAIL: + return AutocompleteMatchType::SEARCH_SUGGEST_TAIL; + case omnibox::TYPE_PERSONALIZED_QUERY: + return AutocompleteMatchType::SEARCH_SUGGEST_PERSONALIZED; + case omnibox::TYPE_PROFILE: + return AutocompleteMatchType::SEARCH_SUGGEST_PROFILE; + case omnibox::TYPE_NAVIGATION: + return AutocompleteMatchType::NAVSUGGEST; + case omnibox::TYPE_PERSONALIZED_NAVIGATION: + return AutocompleteMatchType::NAVSUGGEST_PERSONALIZED; + default: + return AutocompleteMatchType::SEARCH_SUGGEST; + } } // Convert the supplied Json::Value representation of list-of-lists-of-integers @@ -186,10 +225,12 @@ int relevance, bool relevance_from_server, AutocompleteMatchType::Type type, + omnibox::SuggestType suggest_type, std::vector<int> subtypes, const std::string& deletion_url) : from_keyword_(from_keyword), type_(type), + suggest_type_(suggest_type), subtypes_(std::move(subtypes)), relevance_(relevance), relevance_from_server_(relevance_from_server), @@ -205,6 +246,7 @@ SearchSuggestionParser::SuggestResult::SuggestResult( const std::u16string& suggestion, AutocompleteMatchType::Type type, + omnibox::SuggestType suggest_type, std::vector<int> subtypes, bool from_keyword, int relevance, @@ -212,6 +254,7 @@ const std::u16string& input_text) : SuggestResult(suggestion, type, + suggest_type, std::move(subtypes), suggestion, /*match_contents_prefix=*/std::u16string(), @@ -228,6 +271,7 @@ SearchSuggestionParser::SuggestResult::SuggestResult( const std::u16string& suggestion, AutocompleteMatchType::Type type, + omnibox::SuggestType suggest_type, std::vector<int> subtypes, const std::u16string& match_contents, const std::u16string& match_contents_prefix, @@ -244,6 +288,7 @@ relevance, relevance_from_server, type, + suggest_type, std::move(subtypes), deletion_url), suggestion_(suggestion), @@ -337,6 +382,7 @@ const AutocompleteSchemeClassifier& scheme_classifier, const GURL& url, AutocompleteMatchType::Type match_type, + omnibox::SuggestType suggest_type, std::vector<int> subtypes, const std::u16string& description, const std::string& deletion_url, @@ -348,6 +394,7 @@ relevance, relevance_from_server, match_type, + suggest_type, std::move(subtypes), deletion_url), url_(url), @@ -674,6 +721,7 @@ AutocompleteMatchType::Type match_type = AutocompleteMatchType::SEARCH_SUGGEST; + omnibox::SuggestType suggest_type = omnibox::TYPE_QUERY; // Legacy code: if the server sends us a single subtype ID, place it beside // other subtypes. @@ -684,8 +732,8 @@ if (suggest_types && index < suggest_types->size() && (*suggest_types)[index].is_string()) { - match_type = - GetAutocompleteMatchType((*suggest_types)[index].GetString()); + suggest_type = GetSuggestType((*suggest_types)[index].GetString()); + match_type = GetAutocompleteMatchType(suggest_type); } std::string deletion_url; @@ -711,9 +759,9 @@ } } results->navigation_results.push_back(NavigationResult( - scheme_classifier, url, match_type, subtypes[index], title, - deletion_url, is_keyword_result, relevance, relevances != nullptr, - input.text())); + scheme_classifier, url, match_type, suggest_type, subtypes[index], + title, deletion_url, is_keyword_result, relevance, + relevances != nullptr, input.text())); } } else { std::u16string annotation; @@ -789,7 +837,7 @@ bool should_prefetch = int_index == prefetch_index; bool should_prerender = int_index == prerender_index; results->suggest_results.push_back(SuggestResult( - suggestion, match_type, subtypes[index], match_contents, + suggestion, match_type, suggest_type, subtypes[index], match_contents, match_contents_prefix, annotation, std::move(entity_info), deletion_url, is_keyword_result, relevance, relevances != nullptr, should_prefetch, should_prerender, trimmed_input));
diff --git a/components/omnibox/browser/search_suggestion_parser.h b/components/omnibox/browser/search_suggestion_parser.h index 4928c7f..a45311f7 100644 --- a/components/omnibox/browser/search_suggestion_parser.h +++ b/components/omnibox/browser/search_suggestion_parser.h
@@ -53,6 +53,7 @@ int relevance, bool relevance_from_server, AutocompleteMatchType::Type type, + omnibox::SuggestType suggest_type, std::vector<int> subtypes, const std::string& deletion_url); Result(const Result& other); @@ -66,6 +67,7 @@ } AutocompleteMatchType::Type type() const { return type_; } + omnibox::SuggestType suggest_type() const { return suggest_type_; } const std::vector<int>& subtypes() const { return subtypes_; } int relevance() const { return relevance_; } void set_relevance(int relevance) { relevance_ = relevance; } @@ -99,8 +101,12 @@ // True if the result came from a keyword suggestion. bool from_keyword_; + // AutocompleteMatch type. AutocompleteMatchType::Type type_; + // Suggestion type. + omnibox::SuggestType suggest_type_; + // Suggestion subtypes. std::vector<int> subtypes_; @@ -130,6 +136,7 @@ public: SuggestResult(const std::u16string& suggestion, AutocompleteMatchType::Type type, + omnibox::SuggestType suggest_type, std::vector<int> subtypes, bool from_keyword, int relevance, @@ -137,6 +144,7 @@ const std::u16string& input_text); SuggestResult(const std::u16string& suggestion, AutocompleteMatchType::Type type, + omnibox::SuggestType suggest_type, std::vector<int> subtypes, const std::u16string& match_contents, const std::u16string& match_contents_prefix, @@ -225,6 +233,7 @@ NavigationResult(const AutocompleteSchemeClassifier& scheme_classifier, const GURL& url, AutocompleteMatchType::Type type, + omnibox::SuggestType suggest_type, std::vector<int> subtypes, const std::u16string& description, const std::string& deletion_url,
diff --git a/components/omnibox/browser/search_suggestion_parser_unittest.cc b/components/omnibox/browser/search_suggestion_parser_unittest.cc index 0e23e2f1..7689d4f 100644 --- a/components/omnibox/browser/search_suggestion_parser_unittest.cc +++ b/components/omnibox/browser/search_suggestion_parser_unittest.cc
@@ -300,8 +300,8 @@ TEST(SearchSuggestionParserTest, SuggestClassification) { SearchSuggestionParser::SuggestResult result( - u"foobar", AutocompleteMatchType::SEARCH_SUGGEST, {}, false, 400, true, - std::u16string()); + u"foobar", AutocompleteMatchType::SEARCH_SUGGEST, omnibox::TYPE_QUERY, {}, + false, 400, true, std::u16string()); AutocompleteMatch::ValidateClassifications(result.match_contents(), result.match_contents_class()); @@ -344,8 +344,8 @@ TestSchemeClassifier scheme_classifier; SearchSuggestionParser::NavigationResult result( scheme_classifier, GURL("https://news.google.com/"), - AutocompleteMatchType::Type::NAVSUGGEST, {}, std::u16string(), - std::string(), false, 400, true, u"google"); + AutocompleteMatchType::Type::NAVSUGGEST, omnibox::TYPE_NAVIGATION, {}, + std::u16string(), std::string(), false, 400, true, u"google"); AutocompleteMatch::ValidateClassifications(result.match_contents(), result.match_contents_class()); const ACMatchClassifications kBoldMiddle = {
diff --git a/components/omnibox/browser/voice_suggest_provider.cc b/components/omnibox/browser/voice_suggest_provider.cc index 2786e57..3a44105 100644 --- a/components/omnibox/browser/voice_suggest_provider.cc +++ b/components/omnibox/browser/voice_suggest_provider.cc
@@ -11,6 +11,7 @@ #include "components/omnibox/browser/autocomplete_match_classification.h" #include "components/search_engines/template_url.h" #include "components/search_engines/template_url_service.h" +#include "third_party/omnibox_proto/types.pb.h" namespace { // Maximum and minimum score allowed for voice suggestions. @@ -46,7 +47,9 @@ AddMatchToMap( SearchSuggestionParser::SuggestResult( score_and_suggestion_pair.second, - AutocompleteMatchType::VOICE_SUGGEST, {}, false, + AutocompleteMatchType::VOICE_SUGGEST, + /*suggest_type=*/omnibox::TYPE_NATIVE_CHROME, /*subtypes=*/{}, + false, ConfidenceScoreToSuggestionScore(score_and_suggestion_pair.first), false, {}), {}, input,
diff --git a/components/omnibox/browser/zero_suggest_provider.cc b/components/omnibox/browser/zero_suggest_provider.cc index d1786ee..4faaac9 100644 --- a/components/omnibox/browser/zero_suggest_provider.cc +++ b/components/omnibox/browser/zero_suggest_provider.cc
@@ -696,6 +696,7 @@ AutocompleteMatch::SanitizeString(navigation.description()); match.description_class = ClassifyTermMatches({}, match.description.length(), 0, ACMatchClassification::NONE); + match.suggest_type = navigation.suggest_type(); for (const int subtype : navigation.subtypes()) { match.subtypes.insert(SuggestSubtypeForNumber(subtype)); }
diff --git a/components/optimization_guide/core/BUILD.gn b/components/optimization_guide/core/BUILD.gn index a2d21f6..7d77505a 100644 --- a/components/optimization_guide/core/BUILD.gn +++ b/components/optimization_guide/core/BUILD.gn
@@ -376,6 +376,7 @@ "hints_processing_util_unittest.cc", "insertion_ordered_set_unittest.cc", "model_handler_unittest.cc", + "model_store_metadata_entry_unittest.cc", "model_util_unittest.cc", "noisy_metrics_recorder_unittest.cc", "optimization_filter_unittest.cc",
diff --git a/components/optimization_guide/core/entity_annotator_native_library.cc b/components/optimization_guide/core/entity_annotator_native_library.cc index 763d3c62..3bd69a8 100644 --- a/components/optimization_guide/core/entity_annotator_native_library.cc +++ b/components/optimization_guide/core/entity_annotator_native_library.cc
@@ -16,7 +16,7 @@ #include "components/optimization_guide/proto/page_entities_model_metadata.pb.h" #if BUILDFLAG(IS_MAC) -#include "base/mac/bundle_locations.h" +#include "base/apple/bundle_locations.h" #include "base/mac/foundation_util.h" #endif @@ -87,7 +87,7 @@ #if !BUILDFLAG(IS_ANDROID) #if BUILDFLAG(IS_MAC) if (base::mac::AmIBundled()) { - base_dir = base::mac::FrameworkBundlePath().Append("Libraries"); + base_dir = base::apple::FrameworkBundlePath().Append("Libraries"); } else { #endif // BUILDFLAG(IS_MAC) if (!base::PathService::Get(base::DIR_MODULE, &base_dir)) {
diff --git a/components/optimization_guide/core/model_store_metadata_entry.cc b/components/optimization_guide/core/model_store_metadata_entry.cc index 98670f2..37914ab6 100644 --- a/components/optimization_guide/core/model_store_metadata_entry.cc +++ b/components/optimization_guide/core/model_store_metadata_entry.cc
@@ -167,6 +167,7 @@ PrefService* local_state) { ScopedDictPrefUpdate updater(local_state, prefs::localstate::kModelStoreMetadata); + std::vector<std::pair<std::string, std::string>> entries_to_remove; std::vector<base::FilePath> inactive_model_dirs; for (auto optimization_target_entry : *updater) { if (!optimization_target_entry.second.is_dict()) { @@ -195,8 +196,13 @@ if (base_model_dir) { inactive_model_dirs.emplace_back(*base_model_dir); } - optimization_target_entry.second.GetDict().Remove( - model_cache_key_hash.first); + entries_to_remove.emplace_back(optimization_target_entry.first, + model_cache_key_hash.first); + } + } + for (const auto& entry : entries_to_remove) { + if (auto* optimization_target_dict = updater->FindDict(entry.first)) { + optimization_target_dict->Remove(entry.second); } } }
diff --git a/components/optimization_guide/core/model_store_metadata_entry_unittest.cc b/components/optimization_guide/core/model_store_metadata_entry_unittest.cc new file mode 100644 index 0000000..5e682f6 --- /dev/null +++ b/components/optimization_guide/core/model_store_metadata_entry_unittest.cc
@@ -0,0 +1,151 @@ +// Copyright 2023 The Chromium Authors +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "components/optimization_guide/core/model_store_metadata_entry.h" + +#include "base/files/file_path.h" +#include "base/test/task_environment.h" +#include "components/optimization_guide/core/optimization_guide_prefs.h" +#include "components/sync_preferences/testing_pref_service_syncable.h" +#include "testing/gtest/include/gtest/gtest.h" + +namespace optimization_guide { + +namespace { + +const proto::OptimizationTarget kTestOptimizationTargetFoo = + proto::OptimizationTarget::OPTIMIZATION_TARGET_PAINFUL_PAGE_LOAD; +const proto::OptimizationTarget kTestOptimizationTargetBar = + proto::OptimizationTarget::OPTIMIZATION_TARGET_MODEL_VALIDATION; + +const char kTestLocaleFoo[] = "foo"; +const char kTestLocaleBar[] = "bar"; + +proto::ModelCacheKey CreateModelCacheKey(const std::string& locale) { + proto::ModelCacheKey model_cache_key; + model_cache_key.set_locale(locale); + return model_cache_key; +} + +} // namespace + +class ModelStoreMetadataEntryTest : public testing::Test { + public: + void SetUp() override { + local_state_ = std::make_unique<TestingPrefServiceSimple>(); + prefs::RegisterLocalStatePrefs(local_state_->registry()); + } + + PrefService* local_state() const { return local_state_.get(); } + + private: + base::test::TaskEnvironment task_environment_; + std::unique_ptr<TestingPrefServiceSimple> local_state_; +}; + +TEST_F(ModelStoreMetadataEntryTest, PurgeAllMetadata) { + auto model_cache_key_foo = CreateModelCacheKey(kTestLocaleFoo); + auto model_cache_key_bar = CreateModelCacheKey(kTestLocaleBar); + + ModelStoreMetadataEntryUpdater::UpdateModelCacheKeyMapping( + local_state(), kTestOptimizationTargetFoo, model_cache_key_foo, + model_cache_key_foo); + ModelStoreMetadataEntryUpdater::UpdateModelCacheKeyMapping( + local_state(), kTestOptimizationTargetFoo, model_cache_key_bar, + model_cache_key_bar); + auto expired_time = base::Time::Now() - base::Hours(1); + { + ModelStoreMetadataEntryUpdater updater( + local_state(), kTestOptimizationTargetFoo, model_cache_key_foo); + updater.SetModelBaseDir(base::FilePath::FromASCII("opt_target_foo") + .AppendASCII("model_cache_key_foo")); + updater.SetExpiryTime(expired_time); + } + { + ModelStoreMetadataEntryUpdater updater( + local_state(), kTestOptimizationTargetBar, model_cache_key_foo); + updater.SetModelBaseDir(base::FilePath::FromASCII("opt_target_bar") + .AppendASCII("model_cache_key_foo")); + updater.SetExpiryTime(expired_time); + } + { + ModelStoreMetadataEntryUpdater updater( + local_state(), kTestOptimizationTargetFoo, model_cache_key_bar); + updater.SetModelBaseDir(base::FilePath::FromASCII("opt_target_foo") + .AppendASCII("model_cache_key_bar")); + updater.SetExpiryTime(expired_time); + } + { + ModelStoreMetadataEntryUpdater updater( + local_state(), kTestOptimizationTargetBar, model_cache_key_bar); + updater.SetModelBaseDir(base::FilePath::FromASCII("opt_target_bar") + .AppendASCII("model_cache_key_bar")); + updater.SetExpiryTime(expired_time); + } + ModelStoreMetadataEntryUpdater::PurgeAllInactiveMetadata(local_state()); + + // All entries should be purged. + EXPECT_FALSE(ModelStoreMetadataEntry::GetModelMetadataEntryIfExists( + local_state(), kTestOptimizationTargetFoo, model_cache_key_foo)); + EXPECT_FALSE(ModelStoreMetadataEntry::GetModelMetadataEntryIfExists( + local_state(), kTestOptimizationTargetBar, model_cache_key_foo)); + EXPECT_FALSE(ModelStoreMetadataEntry::GetModelMetadataEntryIfExists( + local_state(), kTestOptimizationTargetFoo, model_cache_key_bar)); + EXPECT_FALSE(ModelStoreMetadataEntry::GetModelMetadataEntryIfExists( + local_state(), kTestOptimizationTargetBar, model_cache_key_bar)); +} + +TEST_F(ModelStoreMetadataEntryTest, PurgeExpiredMetadata) { + auto model_cache_key_foo = CreateModelCacheKey(kTestLocaleFoo); + auto model_cache_key_bar = CreateModelCacheKey(kTestLocaleBar); + + ModelStoreMetadataEntryUpdater::UpdateModelCacheKeyMapping( + local_state(), kTestOptimizationTargetFoo, model_cache_key_foo, + model_cache_key_foo); + ModelStoreMetadataEntryUpdater::UpdateModelCacheKeyMapping( + local_state(), kTestOptimizationTargetFoo, model_cache_key_bar, + model_cache_key_bar); + auto expired_time = base::Time::Now() - base::Hours(1); + { + ModelStoreMetadataEntryUpdater updater( + local_state(), kTestOptimizationTargetFoo, model_cache_key_foo); + updater.SetModelBaseDir(base::FilePath::FromASCII("opt_target_foo") + .AppendASCII("model_cache_key_foo")); + updater.SetExpiryTime(base::Time::Now() + base::Hours(1)); + } + { + ModelStoreMetadataEntryUpdater updater( + local_state(), kTestOptimizationTargetBar, model_cache_key_foo); + updater.SetModelBaseDir(base::FilePath::FromASCII("opt_target_bar") + .AppendASCII("model_cache_key_foo")); + updater.SetExpiryTime(base::Time::Now() + base::Hours(1)); + } + { + ModelStoreMetadataEntryUpdater updater( + local_state(), kTestOptimizationTargetFoo, model_cache_key_bar); + updater.SetModelBaseDir(base::FilePath::FromASCII("opt_target_foo") + .AppendASCII("model_cache_key_bar")); + updater.SetExpiryTime(expired_time); + } + { + ModelStoreMetadataEntryUpdater updater( + local_state(), kTestOptimizationTargetBar, model_cache_key_bar); + updater.SetModelBaseDir(base::FilePath::FromASCII("opt_target_bar") + .AppendASCII("model_cache_key_bar")); + updater.SetExpiryTime(expired_time); + } + ModelStoreMetadataEntryUpdater::PurgeAllInactiveMetadata(local_state()); + + // Only expired entries will be purged. + EXPECT_TRUE(ModelStoreMetadataEntry::GetModelMetadataEntryIfExists( + local_state(), kTestOptimizationTargetFoo, model_cache_key_foo)); + EXPECT_TRUE(ModelStoreMetadataEntry::GetModelMetadataEntryIfExists( + local_state(), kTestOptimizationTargetBar, model_cache_key_foo)); + EXPECT_FALSE(ModelStoreMetadataEntry::GetModelMetadataEntryIfExists( + local_state(), kTestOptimizationTargetFoo, model_cache_key_bar)); + EXPECT_FALSE(ModelStoreMetadataEntry::GetModelMetadataEntryIfExists( + local_state(), kTestOptimizationTargetBar, model_cache_key_bar)); +} + +} // namespace optimization_guide
diff --git a/components/optimization_guide/core/optimization_guide_features.cc b/components/optimization_guide/core/optimization_guide_features.cc index 87bac91..a2c430c2 100644 --- a/components/optimization_guide/core/optimization_guide_features.cc +++ b/components/optimization_guide/core/optimization_guide_features.cc
@@ -201,6 +201,19 @@ "PageContentAnnotationsPersistSalientImageMetadata", base::FEATURE_DISABLED_BY_DEFAULT); +// Enables the model store to save relative paths computed from the base model +// store dir. Storing as relative path in the model store is needed for IOS, +// since the directories could change after Chrome upgrade. This feature is +// expected to be enabled only for IOS. +BASE_FEATURE(kModelStoreUseRelativePath, + "ModelStoreUseRelativePath", +#if BUILDFLAG(IS_IOS) + base::FEATURE_ENABLED_BY_DEFAULT +#else + base::FEATURE_DISABLED_BY_DEFAULT +#endif +); + // The default value here is a bit of a guess. // TODO(crbug/1163244): This should be tuned once metrics are available. base::TimeDelta PageTextExtractionOutstandingRequestsGracePeriod() {
diff --git a/components/optimization_guide/core/optimization_guide_features.h b/components/optimization_guide/core/optimization_guide_features.h index b5130ae..b572a817 100644 --- a/components/optimization_guide/core/optimization_guide_features.h +++ b/components/optimization_guide/core/optimization_guide_features.h
@@ -46,6 +46,7 @@ BASE_DECLARE_FEATURE(kOptimizationGuideInstallWideModelStore); BASE_DECLARE_FEATURE(kExtractRelatedSearchesFromPrefetchedZPSResponse); BASE_DECLARE_FEATURE(kPageContentAnnotationsPersistSalientImageMetadata); +BASE_DECLARE_FEATURE(kModelStoreUseRelativePath); // Enables use of task runner with trait CONTINUE_ON_SHUTDOWN for page content // annotations on-device models.
diff --git a/components/optimization_guide/core/optimization_guide_store.cc b/components/optimization_guide/core/optimization_guide_store.cc index 86497c4e..2263ad52 100644 --- a/components/optimization_guide/core/optimization_guide_store.cc +++ b/components/optimization_guide/core/optimization_guide_store.cc
@@ -105,6 +105,23 @@ return key_set.find(key) != key_set.end(); } +// Returns the relative filepath for |child| w.r.t. parent. For example, with +// child="/foo/bar/baz/abc.txt" and parent="/foo/bar/", this returns the +// relative path "baz/abc.txt". +base::FilePath ConvertToRelativePath(const base::FilePath& parent, + const base::FilePath& child) { + DCHECK(parent.IsAbsolute()); + DCHECK(child.IsAbsolute()); + DCHECK(parent.IsParent(child)); + const auto parent_components = parent.GetComponents(); + const auto child_components = child.GetComponents(); + base::FilePath relative_path; + for (size_t i = parent_components.size(); i < child_components.size(); i++) { + relative_path = relative_path.Append(child_components[i]); + } + return relative_path; +} + } // namespace OptimizationGuideStore::OptimizationGuideStore( @@ -112,7 +129,21 @@ const base::FilePath& database_dir, scoped_refptr<base::SequencedTaskRunner> store_task_runner, PrefService* pref_service) - : store_task_runner_(store_task_runner), pref_service_(pref_service) { + : OptimizationGuideStore(database_provider, + database_dir, + /*base_model_store_dir=*/base::FilePath(), + store_task_runner, + pref_service) {} + +OptimizationGuideStore::OptimizationGuideStore( + leveldb_proto::ProtoDatabaseProvider* database_provider, + const base::FilePath& database_dir, + const base::FilePath& base_model_store_dir, + scoped_refptr<base::SequencedTaskRunner> store_task_runner, + PrefService* pref_service) + : base_model_store_dir_(base_model_store_dir), + store_task_runner_(store_task_runner), + pref_service_(pref_service) { database_ = database_provider->GetDB<proto::StoreEntry>( leveldb_proto::ProtoDbType::HINT_CACHE_STORE, database_dir, store_task_runner_); @@ -125,9 +156,11 @@ OptimizationGuideStore::OptimizationGuideStore( std::unique_ptr<leveldb_proto::ProtoDatabase<proto::StoreEntry>> database, + const base::FilePath& base_model_store_dir, scoped_refptr<base::SequencedTaskRunner> store_task_runner, PrefService* pref_service) : database_(std::move(database)), + base_model_store_dir_(base_model_store_dir), store_task_runner_(store_task_runner), pref_service_(pref_service) { RecordStatusChange(status_); @@ -880,6 +913,7 @@ base::OnceClosure callback) { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); DCHECK(prediction_models_update_data); + DCHECK(!base_model_store_dir_.empty()); if (!IsAvailable()) { std::move(callback).Run(); @@ -889,6 +923,22 @@ std::unique_ptr<EntryVector> entry_vector = prediction_models_update_data->TakeUpdateEntries(); + if (base::FeatureList::IsEnabled(features::kModelStoreUseRelativePath)) { + for (auto& entry : *entry_vector) { + proto::PredictionModel* prediction_model = + entry.second.mutable_prediction_model(); + if (!prediction_model) { + continue; + } + absl::optional<base::FilePath> model_file_path = + StringToFilePath(prediction_model->model().download_url()); + if (model_file_path) { + prediction_model->mutable_model()->set_download_url(FilePathToString( + ConvertToRelativePath(base_model_store_dir_, *model_file_path))); + } + } + } + EntryKeySet keys_to_update; for (const auto& entry : *entry_vector) keys_to_update.insert(entry.first); @@ -914,6 +964,7 @@ base::OnceClosure callback, bool success, std::unique_ptr<EntryMap> entries) { + DCHECK(!base_model_store_dir_.empty()); if (!success || !entries) { std::move(callback).Run(); return; @@ -977,6 +1028,11 @@ base::FilePath model_file_path = StringToFilePath(*delete_download_file).value(); base::FilePath path_to_delete; + if (!model_file_path.IsAbsolute()) { + // |kModelStoreUseRelativePath| will save the relative path in the + // store. Convert it to absolute path using base model store dir. + model_file_path = base_model_store_dir_.Append(model_file_path); + } // Backwards compatibility: Once upon a time (<M93), model files were // stored as @@ -1080,6 +1136,7 @@ bool success, std::unique_ptr<proto::StoreEntry> entry) { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); + DCHECK(!base_model_store_dir_.empty()); // If either the request failed or the store was set to unavailable after the // request was started, then the loaded model should not be considered valid. @@ -1118,14 +1175,39 @@ absl::optional<base::FilePath> model_file_path = StringToFilePath(loaded_prediction_model->model().download_url()); if (model_file_path) { - file_paths_to_check.emplace_back(*model_file_path); + if (!model_file_path->IsAbsolute()) { + // |kModelStoreUseRelativePath| will save the relative path in the store. + // Create the absolute path using base model store dir. + base::FilePath absolute_model_path = + base_model_store_dir_.Append(*model_file_path); + loaded_prediction_model->mutable_model()->set_download_url( + FilePathToString(absolute_model_path)); + file_paths_to_check.emplace_back(absolute_model_path); + } else { + file_paths_to_check.emplace_back(*model_file_path); + } } - for (const proto::AdditionalModelFile& additional_file : - loaded_prediction_model->model_info().additional_files()) { + for (int i = 0; + i < + loaded_prediction_model->mutable_model_info()->additional_files_size(); + i++) { + proto::AdditionalModelFile* additional_file = + loaded_prediction_model->mutable_model_info()->mutable_additional_files( + i); absl::optional<base::FilePath> additional_file_path = - StringToFilePath(additional_file.file_path()); + StringToFilePath(additional_file->file_path()); if (additional_file_path) { - file_paths_to_check.emplace_back(*additional_file_path); + if (!additional_file_path->IsAbsolute()) { + // |kModelStoreUseRelativePath| will save the relative path in the + // store. Create the absolute path using base model store dir. + base::FilePath absolute_additional_path = + base_model_store_dir_.Append(*additional_file_path); + additional_file->set_file_path( + FilePathToString(absolute_additional_path)); + file_paths_to_check.emplace_back(absolute_additional_path); + } else { + file_paths_to_check.emplace_back(*additional_file_path); + } } }
diff --git a/components/optimization_guide/core/optimization_guide_store.h b/components/optimization_guide/core/optimization_guide_store.h index 5b6bb55..546bf400 100644 --- a/components/optimization_guide/core/optimization_guide_store.h +++ b/components/optimization_guide/core/optimization_guide_store.h
@@ -33,10 +33,11 @@ class StoreEntry; } // namespace proto -// The HintCache backing store, which is responsible for storing all hints that -// are locally available. While the HintCache itself may retain some hints in a -// memory cache, all of its hints are initially loaded asynchronously by the -// store. All calls to this store must be made from the same thread. +// The backing store for hints and models, which is responsible for storing all +// hints and models locally on-device. While the HintCache itself may retain +// some hints in a memory cache, all of its hints are initially loaded +// asynchronously by the store. All calls to this store must be made from the +// same thread. class OptimizationGuideStore { public: using HintLoadedCallback = @@ -89,14 +90,25 @@ kMaxValue = kDeprecatedHostModelFeatures, }; + // Creates a hint store. OptimizationGuideStore( leveldb_proto::ProtoDatabaseProvider* database_provider, const base::FilePath& database_dir, scoped_refptr<base::SequencedTaskRunner> store_task_runner, PrefService* pref_service); - // For tests only. - explicit OptimizationGuideStore( + + // Creates a model store. + OptimizationGuideStore( + leveldb_proto::ProtoDatabaseProvider* database_provider, + const base::FilePath& database_dir, + const base::FilePath& base_model_store_dir, + scoped_refptr<base::SequencedTaskRunner> store_task_runner, + PrefService* pref_service); + + // Creates a model store. For tests only. + OptimizationGuideStore( std::unique_ptr<StoreEntryProtoDatabase> database, + const base::FilePath& base_model_store_dir, scoped_refptr<base::SequencedTaskRunner> store_task_runner, PrefService* pref_service); @@ -446,6 +458,11 @@ // The keys of the entries available within the store. std::unique_ptr<EntryKeySet> entry_keys_; + // The base model store dir where all the models are stored. Populated only + // when |this| is used as model store. Will be empty path for hint cache + // store. + const base::FilePath base_model_store_dir_; + // The background task runner used to perform operations on the store. scoped_refptr<base::SequencedTaskRunner> store_task_runner_;
diff --git a/components/optimization_guide/core/optimization_guide_store_unittest.cc b/components/optimization_guide/core/optimization_guide_store_unittest.cc index 2c23bd0..a25c6250 100644 --- a/components/optimization_guide/core/optimization_guide_store_unittest.cc +++ b/components/optimization_guide/core/optimization_guide_store_unittest.cc
@@ -210,7 +210,7 @@ db_ = db.get(); guide_store_ = std::make_unique<OptimizationGuideStore>( - std::move(db), task_environment_.GetMainThreadTaskRunner(), + std::move(db), temp_dir(), task_environment_.GetMainThreadTaskRunner(), pref_service_.get()); }
diff --git a/components/optimization_guide/core/prediction_manager_unittest.cc b/components/optimization_guide/core/prediction_manager_unittest.cc index 994a2cc9..01d0d4b81 100644 --- a/components/optimization_guide/core/prediction_manager_unittest.cc +++ b/components/optimization_guide/core/prediction_manager_unittest.cc
@@ -295,8 +295,10 @@ public: TestOptimizationGuideStore( std::unique_ptr<StoreEntryProtoDatabase> database, + const base::FilePath& base_model_store_dir, scoped_refptr<base::SequencedTaskRunner> store_task_runner) : OptimizationGuideStore(std::move(database), + base_model_store_dir, store_task_runner, nullptr) {} @@ -438,7 +440,7 @@ auto db = std::make_unique<FakeDB<StoreEntry>>(&db_store_); return std::make_unique<TestOptimizationGuideStore>( - std::move(db), task_environment_.GetMainThreadTaskRunner()); + std::move(db), temp_dir(), task_environment_.GetMainThreadTaskRunner()); } TestPredictionManager* prediction_manager() const {
diff --git a/components/page_info/android/BUILD.gn b/components/page_info/android/BUILD.gn index 72afe37..d57bcfe 100644 --- a/components/page_info/android/BUILD.gn +++ b/components/page_info/android/BUILD.gn
@@ -98,7 +98,7 @@ "//components/embedder_support/android:util_java", "//components/feature_engagement/public:public_java", "//components/location/android:location_java", - "//components/omnibox/browser:browser_java", + "//components/omnibox/browser:scheme_classifier_java", "//components/permissions/android:java", "//components/security_state/content/android:java", "//components/security_state/core:security_state_enums_java",
diff --git a/components/password_manager/core/browser/sync_username_test_base.cc b/components/password_manager/core/browser/sync_username_test_base.cc index 62a7c6cf..260a4ee 100644 --- a/components/password_manager/core/browser/sync_username_test_base.cc +++ b/components/password_manager/core/browser/sync_username_test_base.cc
@@ -93,9 +93,10 @@ void SyncUsernameTestBase::SetSyncingPasswords(bool syncing_passwords) { sync_service_.GetUserSettings()->SetSelectedTypes( /*sync_everything=*/false, - /*types=*/syncing_passwords ? syncer::UserSelectableTypeSet( - syncer::UserSelectableType::kPasswords) - : syncer::UserSelectableTypeSet()); + /*types=*/syncing_passwords + ? syncer::UserSelectableTypeSet( + {syncer::UserSelectableType::kPasswords}) + : syncer::UserSelectableTypeSet()); } } // namespace password_manager
diff --git a/components/password_manager/ios/password_form_helper_unittest.mm b/components/password_manager/ios/password_form_helper_unittest.mm index d25bc4b..05d1da63 100644 --- a/components/password_manager/ios/password_form_helper_unittest.mm +++ b/components/password_manager/ios/password_form_helper_unittest.mm
@@ -6,7 +6,7 @@ #include <stddef.h> -#include "base/mac/bundle_locations.h" +#include "base/apple/bundle_locations.h" #include "base/strings/sys_string_conversions.h" #include "base/strings/utf_string_conversions.h" #include "base/test/ios/wait_util.h"
diff --git a/components/permissions/android/BUILD.gn b/components/permissions/android/BUILD.gn index 2cfba80..5509da9 100644 --- a/components/permissions/android/BUILD.gn +++ b/components/permissions/android/BUILD.gn
@@ -123,7 +123,7 @@ "//components/browser_ui/modaldialog/android:java", "//components/browser_ui/util/android:java", "//components/content_settings/android:content_settings_enums_java", - "//components/omnibox/browser:browser_java", + "//components/omnibox/browser:scheme_classifier_java", "//content/public/android:content_java", "//third_party/androidx:androidx_annotation_annotation_java", "//third_party/androidx:androidx_appcompat_appcompat_resources_java",
diff --git a/components/policy/core/common/policy_loader_win.cc b/components/policy/core/common/policy_loader_win.cc index e197049..8a3dd1ba 100644 --- a/components/policy/core/common/policy_loader_win.cc +++ b/components/policy/core/common/policy_loader_win.cc
@@ -135,7 +135,6 @@ &::NetGetJoinInformation; decltype(&::NetApiBufferFree) net_api_buffer_free_function = &::NetApiBufferFree; - bool got_function_addresses = false; // Use an absolute path to load the DLL to avoid DLL preloading attacks. base::FilePath path; if (base::PathService::Get(base::DIR_SYSTEM, &path)) { @@ -156,16 +155,12 @@ reinterpret_cast<decltype(&::NetApiBufferFree)>( ::GetProcAddress(net_api_library, "NetApiBufferFree")); - if (net_get_join_information_function && net_api_buffer_free_function) { - got_function_addresses = true; - } else { + if (!net_get_join_information_function || !net_api_buffer_free_function) { net_get_join_information_function = &::NetGetJoinInformation; net_api_buffer_free_function = &::NetApiBufferFree; } } } - base::UmaHistogramBoolean("EnterpriseCheck.NetGetJoinInformationAddress", - got_function_addresses); LPWSTR buffer = nullptr; NETSETUP_JOIN_STATUS buffer_type = NetSetupUnknownStatus;
diff --git a/components/policy/core/common/policy_pref_names.cc b/components/policy/core/common/policy_pref_names.cc index 998e9237..502e6e5 100644 --- a/components/policy/core/common/policy_pref_names.cc +++ b/components/policy/core/common/policy_pref_names.cc
@@ -122,11 +122,6 @@ const char kSendMouseEventsDisabledFormControlsEnabled[] = "policy.send_mouse_events_disabled_form_controls_enabled"; -// If true the feature UseMojoVideoDecoderForPepper will be allowed, otherwise -// feature will be forced off. -const char kUseMojoVideoDecoderForPepperAllowed[] = - "policy.use_mojo_video_decoder_for_pepper_allowed"; - // If true the feature PPAPISharedImagesSwapChain will be allowed, otherwise // feature will be forced off. const char kPPAPISharedImagesSwapChainAllowed[] =
diff --git a/components/policy/core/common/policy_pref_names.h b/components/policy/core/common/policy_pref_names.h index 3482934..84870dcac 100644 --- a/components/policy/core/common/policy_pref_names.h +++ b/components/policy/core/common/policy_pref_names.h
@@ -63,7 +63,6 @@ extern const char kEventPathEnabled[]; extern const char kOffsetParentNewSpecBehaviorEnabled[]; extern const char kSendMouseEventsDisabledFormControlsEnabled[]; -extern const char kUseMojoVideoDecoderForPepperAllowed[]; extern const char kPPAPISharedImagesSwapChainAllowed[]; extern const char kForceEnablePepperVideoDecoderDevAPI[]; extern const char kForceGoogleSafeSearch[];
diff --git a/components/policy/proto/device_management_backend.proto b/components/policy/proto/device_management_backend.proto index 2258140c8..8afb954 100644 --- a/components/policy/proto/device_management_backend.proto +++ b/components/policy/proto/device_management_backend.proto
@@ -275,7 +275,12 @@ // milliseconds since Epoch in UTC timezone (Java time). optional int64 psm_determination_timestamp_ms = 20; - // Next id: 21. + // Information specific to Demo Mode about the device and the demo context. + // Only set when the device is enrolling into Demo Mode, as defined by + // DeviceRegisterRequest.requisition == "cros-demo-mode". + optional DemoModeDimensions demo_mode_dimensions = 21; + + // Next id: 22. } // Identification of a device used during its registration. @@ -1493,6 +1498,25 @@ optional BrowserReport browser_report = 2; } +// Information specific to Demo Mode about the device and the demo context. +message DemoModeDimensions { + // Two-letter country code. + optional string country = 1; + // Name of the retailer whose store the device is running in. Also called + // retailer_id elsewhere in some legacy field names. + optional string retailer_name = 2; + // Retailer-defined number to identify the store that a device is running in. + // Also called store_id elsewhere in some legacy field names. + optional string store_number = 3; + // Device attributes significant to Demo Mode for customization purposes. + enum CustomizationFacet { + UNDEFINED = 0; + CLOUD_GAMING_DEVICE = 1; + FEATURE_AWARE_DEVICE = 2; + } + repeated CustomizationFacet customization_facets = 4; +} + // Report device level status. message DeviceStatusReportRequest { reserved 4, 7, 13, 20; @@ -1640,6 +1664,10 @@ // Flag whether LaCros is the primary browser. optional bool is_lacros_primary_browser = 48; + + // Information specific to Demo Mode about the device and the demo context. + // Only included for devices in Demo Mode. + optional DemoModeDimensions demo_mode_dimensions = 49; } message OsUpdateStatus {
diff --git a/components/policy/resources/templates/policy_definitions/Miscellaneous/UseMojoVideoDecoderForPepperAllowed.yaml b/components/policy/resources/templates/policy_definitions/Miscellaneous/UseMojoVideoDecoderForPepperAllowed.yaml index 3d6d354..e20e299 100644 --- a/components/policy/resources/templates/policy_definitions/Miscellaneous/UseMojoVideoDecoderForPepperAllowed.yaml +++ b/components/policy/resources/templates/policy_definitions/Miscellaneous/UseMojoVideoDecoderForPepperAllowed.yaml
@@ -28,9 +28,9 @@ policy while the browser is running. supported_on: -# TODO(crbug.com/1410758): Remove this policy on ~May 6 after 114 has branched. -- chrome.*:110- -- chrome_os:110- +- chrome.*:110-114 +- chrome_os:110-114 +deprecated: true device_only: false features: dynamic_refresh: true
diff --git a/components/policy/test/data/policy_test_cases.json b/components/policy/test/data/policy_test_cases.json index 93ebbc8..b4abee3d 100644 --- a/components/policy/test/data/policy_test_cases.json +++ b/components/policy/test/data/policy_test_cases.json
@@ -21783,42 +21783,7 @@ ] }, "UseMojoVideoDecoderForPepperAllowed": { - "os": [ - "win", - "linux", - "mac", - "chromeos_ash", - "chromeos_lacros" - ], - "policy_pref_mapping_tests": [ - { - "policies": {}, - "prefs": { - "policy.use_mojo_video_decoder_for_pepper_allowed": { - "location": "local_state", - "default_value": true - } - } - }, - { - "policies": { "UseMojoVideoDecoderForPepperAllowed": true }, - "prefs": { - "policy.use_mojo_video_decoder_for_pepper_allowed": { - "location": "local_state", - "value": true - } - } - }, - { - "policies": { "UseMojoVideoDecoderForPepperAllowed": false }, - "prefs": { - "policy.use_mojo_video_decoder_for_pepper_allowed": { - "location": "local_state", - "value": false - } - } - } - ] + "reason_for_missing_test": "Policy was removed" }, "PPAPISharedImagesSwapChainAllowed": { "os": [
diff --git a/components/printing/renderer/print_render_frame_helper.cc b/components/printing/renderer/print_render_frame_helper.cc index 9328ac37..3a1fce46a 100644 --- a/components/printing/renderer/print_render_frame_helper.cc +++ b/components/printing/renderer/print_render_frame_helper.cc
@@ -831,19 +831,19 @@ } // static - Not anonymous so that platform implementations can use it. -float PrintRenderFrameHelper::RenderPageContent(blink::WebLocalFrame* frame, - uint32_t page_number, - const gfx::Rect& canvas_area, - const gfx::Rect& content_area, - double scale_factor, - cc::PaintCanvas* canvas) { +void PrintRenderFrameHelper::RenderPageContent(blink::WebLocalFrame* frame, + uint32_t page_number, + const gfx::Rect& canvas_area, + const gfx::Rect& content_area, + double scale_factor, + cc::PaintCanvas* canvas) { TRACE_EVENT1("print", "PrintRenderFrameHelper::RenderPageContent", "page_number", page_number); cc::PaintCanvasAutoRestore auto_restore(canvas, true); canvas->translate((content_area.x() - canvas_area.x()) / scale_factor, (content_area.y() - canvas_area.y()) / scale_factor); - return frame->PrintPage(page_number, canvas); + frame->PrintPage(page_number, canvas); } // Class that calls the Begin and End print functions on the frame and changes @@ -2603,10 +2603,8 @@ final_scale_factor, *page_layout_in_points, params); } - float webkit_scale_factor = - RenderPageContent(frame, page_number, canvas_area, content_area, - final_scale_factor, canvas); - DCHECK_GT(webkit_scale_factor, 0.0f); + RenderPageContent(frame, page_number, canvas_area, content_area, + final_scale_factor, canvas); // Done printing. Close the canvas to retrieve the compiled metafile. bool ret = metafile->FinishPage();
diff --git a/components/printing/renderer/print_render_frame_helper.h b/components/printing/renderer/print_render_frame_helper.h index 63376c5..9376c3f 100644 --- a/components/printing/renderer/print_render_frame_helper.h +++ b/components/printing/renderer/print_render_frame_helper.h
@@ -390,12 +390,12 @@ // |page_number| is zero-based. // When method is called, canvas should be setup to draw to |canvas_area| // with |scale_factor|. - static float RenderPageContent(blink::WebLocalFrame* frame, - uint32_t page_number, - const gfx::Rect& canvas_area, - const gfx::Rect& content_area, - double scale_factor, - cc::PaintCanvas* canvas); + static void RenderPageContent(blink::WebLocalFrame* frame, + uint32_t page_number, + const gfx::Rect& canvas_area, + const gfx::Rect& content_area, + double scale_factor, + cc::PaintCanvas* canvas); // Helper methods -----------------------------------------------------------
diff --git a/components/remote_cocoa/app_shim/native_widget_ns_window_bridge.mm b/components/remote_cocoa/app_shim/native_widget_ns_window_bridge.mm index f3355c3..6a27c026 100644 --- a/components/remote_cocoa/app_shim/native_widget_ns_window_bridge.mm +++ b/components/remote_cocoa/app_shim/native_widget_ns_window_bridge.mm
@@ -721,7 +721,8 @@ // - A parent changing visibility updates child window visibility. // * But only when changed via this function - ignore changes via the // NSWindow API, or changes propagating out from here. - wants_to_be_visible_ = new_state != WindowVisibilityState::kHideWindow; + wants_to_be_visible_ = new_state != WindowVisibilityState::kHideWindow && + new_state != WindowVisibilityState::kMiniaturizeWindow; [show_animation_ stopAnimation]; // If set, calls OnShowAnimationComplete(). CHECK(!show_animation_); @@ -743,6 +744,9 @@ [window_ orderOut:nil]; DCHECK(!window_visible_); return; + } else if (new_state == WindowVisibilityState::kMiniaturizeWindow) { + [window_ miniaturize:nil]; + return; } DCHECK(wants_to_be_visible_);
diff --git a/components/remote_cocoa/common/native_widget_ns_window.mojom b/components/remote_cocoa/common/native_widget_ns_window.mojom index 14c8ef0c..8ab4aa8 100644 --- a/components/remote_cocoa/common/native_widget_ns_window.mojom +++ b/components/remote_cocoa/common/native_widget_ns_window.mojom
@@ -53,7 +53,9 @@ kShowAndActivateWindow, // Shows with -[NSWindow orderWindow:..]. Orders the window above its parent // if it has one. - kShowInactive + kShowInactive, + // Miniaturizes with -[NSWindow miniaturize:]. + kMiniaturizeWindow }; // Window transitions to animate, mirrors views::Widget::VisibilityTransition.
diff --git a/components/safe_browsing/android/BUILD.gn b/components/safe_browsing/android/BUILD.gn index f54df06..7dcff55 100644 --- a/components/safe_browsing/android/BUILD.gn +++ b/components/safe_browsing/android/BUILD.gn
@@ -129,13 +129,34 @@ ] } +android_library("native_java_unittests_java") { + testonly = true + deps = [ + ":safe_browsing_java", + "//base:base_java", + "//base:base_java_test_support", + "//base:jni_java", + "//third_party/junit", + ] + annotation_processor_deps = [ "//base/android/jni_generator:jni_processor" ] + sources = [ "native_java_unittests/src/org/chromium/components/safe_browsing/SafeBrowsingApiHandlerBridgeNativeUnitTestHelper.java" ] +} + +generate_jni("native_j_unittests_jni_headers") { + testonly = true + sources = [ "native_java_unittests/src/org/chromium/components/safe_browsing/SafeBrowsingApiHandlerBridgeNativeUnitTestHelper.java" ] +} + source_set("unit_tests_mobile") { testonly = true sources = [ "remote_database_manager_unittest.cc", + "safe_browsing_api_handler_bridge_unittest.cc", "safe_browsing_api_handler_util_unittest.cc", ] deps = [ + ":native_j_unittests_jni_headers", + ":native_java_unittests_java", ":remote_database_manager", ":safe_browsing_api_handler", ":safe_browsing_api_handler_util",
diff --git a/components/safe_browsing/android/java/src/org/chromium/components/safe_browsing/SafeBrowsingApiBridge.java b/components/safe_browsing/android/java/src/org/chromium/components/safe_browsing/SafeBrowsingApiBridge.java index f27482c..527472b 100644 --- a/components/safe_browsing/android/java/src/org/chromium/components/safe_browsing/SafeBrowsingApiBridge.java +++ b/components/safe_browsing/android/java/src/org/chromium/components/safe_browsing/SafeBrowsingApiBridge.java
@@ -56,6 +56,18 @@ } /** + * Clear the handler to prepare for the next run. + * This is needed for native to Java bridge test because the bridge is not destroyed between + * each tests. + */ + public static void clearHandlerForTesting() { + synchronized (sLock) { + sHandlerInitCalled = false; + sHandler = null; + } + } + + /** * Initializes the singleton SafeBrowsingApiHandler instance on the first call. On subsequent * calls it does nothing, returns the same value as returned on the first call. *
diff --git a/components/safe_browsing/android/native_java_unittests/src/org/chromium/components/safe_browsing/SafeBrowsingApiHandlerBridgeNativeUnitTestHelper.java b/components/safe_browsing/android/native_java_unittests/src/org/chromium/components/safe_browsing/SafeBrowsingApiHandlerBridgeNativeUnitTestHelper.java new file mode 100644 index 0000000..b1cfa43 --- /dev/null +++ b/components/safe_browsing/android/native_java_unittests/src/org/chromium/components/safe_browsing/SafeBrowsingApiHandlerBridgeNativeUnitTestHelper.java
@@ -0,0 +1,129 @@ +// Copyright 2023 The Chromium Authors +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +package org.chromium.components.safe_browsing; + +import org.junit.Assert; + +import org.chromium.base.annotations.CalledByNative; + +import java.util.Arrays; +import java.util.HashMap; +import java.util.Map; + +/** + * Helper class to verify the JNI bridge. Invoked by native unit tests: + * (components/safe_browsing/android/safe_browsing_api_handler_bridge_unittest.cc/). + */ +public class SafeBrowsingApiHandlerBridgeNativeUnitTestHelper { + /** + * A fake SafeBrowsingApiHandler which verifies the parameters of the overridden functions and + * returns lookup result based on preset values. + */ + public static class MockSafeBrowsingApiHandler implements SafeBrowsingApiHandler { + private Observer mObserver; + // The result that will be returned in {@link #startUriLookup(long, String, int[])}. + private static int sResult = SafeBrowsingResult.SUCCESS; + // Mock time it takes for a lookup request to complete. This value is verified on the native + // side. + private static final long DEFAULT_CHECK_DELTA_MS = 10; + // See safe_browsing_handler_util.h --> JavaThreatTypes + private static final int THREAT_TYPE_CSD_ALLOWLIST = 16; + private static final int THREAT_TYPE_HIGH_CONFIDENCE_ALLOWLIST = 17; + + // Maps to store preset values, keyed by uri. + private static final Map<String, Boolean> sCsdAllowlistMap = new HashMap<>(); + private static final Map<String, Boolean> sHighConfidenceAllowlistMap = new HashMap<>(); + private static final Map<String, int[]> sThreatsOfInterestMap = new HashMap<>(); + private static final Map<String, String> sMetadataMap = new HashMap<>(); + + @Override + public boolean init(Observer result) { + mObserver = result; + return true; + } + + @Override + public void startUriLookup(final long callbackId, String uri, int[] threatsOfInterest) { + if (sResult != SafeBrowsingResult.SUCCESS) { + mObserver.onUrlCheckDone(callbackId, sResult, "{}", DEFAULT_CHECK_DELTA_MS); + return; + } + int[] expectedThreatsOfInterest = sThreatsOfInterestMap.get(uri); + Assert.assertNotNull(expectedThreatsOfInterest); + // The order of threatsOfInterest doesn't matter. + Arrays.sort(expectedThreatsOfInterest); + Arrays.sort(threatsOfInterest); + Assert.assertArrayEquals(threatsOfInterest, expectedThreatsOfInterest); + Assert.assertTrue(sMetadataMap.containsKey(uri)); + mObserver.onUrlCheckDone( + callbackId, sResult, sMetadataMap.get(uri), DEFAULT_CHECK_DELTA_MS); + } + + @Override + public boolean startAllowlistLookup(final String uri, int threatType) { + Assert.assertTrue(threatType == THREAT_TYPE_CSD_ALLOWLIST + || threatType == THREAT_TYPE_HIGH_CONFIDENCE_ALLOWLIST); + if (threatType == THREAT_TYPE_CSD_ALLOWLIST) { + return Boolean.TRUE.equals(sCsdAllowlistMap.get(uri)); + } + return Boolean.TRUE.equals(sHighConfidenceAllowlistMap.get(uri)); + } + + public static void setExpectedThreatsOfInterest(String uri, int[] threatOfInterests) { + sThreatsOfInterestMap.put(uri, threatOfInterests); + } + + public static void setMetadata(String uri, String metadata) { + sMetadataMap.put(uri, metadata); + } + + public static void setCsdAllowlistMatch(String uri, boolean match) { + sCsdAllowlistMap.put(uri, match); + } + + public static void setHighConfidenceAllowlistMatch(String uri, boolean match) { + sHighConfidenceAllowlistMap.put(uri, match); + } + + public static void setResult(int result) { + sResult = result; + } + } + + @CalledByNative + static void setUp() { + SafeBrowsingApiBridge.setHandler(new MockSafeBrowsingApiHandler()); + } + + @CalledByNative + static void tearDown() { + SafeBrowsingApiBridge.clearHandlerForTesting(); + } + + @CalledByNative + static void setExpectedThreatsOfInterest(String uri, int[] threatsOfInterest) { + MockSafeBrowsingApiHandler.setExpectedThreatsOfInterest(uri, threatsOfInterest); + } + + @CalledByNative + static void setMetadata(String uri, String metadata) { + MockSafeBrowsingApiHandler.setMetadata(uri, metadata); + } + + @CalledByNative + static void setCsdAllowlistMatch(String uri, boolean match) { + MockSafeBrowsingApiHandler.setCsdAllowlistMatch(uri, match); + } + + @CalledByNative + static void setHighConfidenceAllowlistMatch(String uri, boolean match) { + MockSafeBrowsingApiHandler.setHighConfidenceAllowlistMatch(uri, match); + } + + @CalledByNative + static void setResult(int result) { + MockSafeBrowsingApiHandler.setResult(result); + } +}
diff --git a/components/safe_browsing/android/safe_browsing_api_handler_bridge_unittest.cc b/components/safe_browsing/android/safe_browsing_api_handler_bridge_unittest.cc new file mode 100644 index 0000000..69bf2049 --- /dev/null +++ b/components/safe_browsing/android/safe_browsing_api_handler_bridge_unittest.cc
@@ -0,0 +1,281 @@ +// Copyright 2023 The Chromium Authors +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "components/safe_browsing/android/safe_browsing_api_handler_bridge.h" + +#include "base/android/jni_android.h" +#include "base/android/jni_array.h" +#include "base/android/jni_string.h" +#include "base/test/metrics/histogram_tester.h" +#include "base/test/mock_callback.h" +#include "components/safe_browsing/android/native_j_unittests_jni_headers/SafeBrowsingApiHandlerBridgeNativeUnitTestHelper_jni.h" +#include "components/safe_browsing/android/safe_browsing_api_handler_util.h" +#include "components/safe_browsing/core/browser/db/util.h" +#include "components/safe_browsing/core/browser/db/v4_protocol_manager_util.h" +#include "content/public/test/browser_task_environment.h" +#include "testing/gmock/include/gmock/gmock.h" +#include "testing/gtest/include/gtest/gtest.h" +#include "url/gurl.h" + +using base::android::ConvertUTF8ToJavaString; +using base::android::ScopedJavaLocalRef; +using base::android::ToJavaIntArray; + +using ::testing::NotNull; + +namespace safe_browsing { + +namespace { + +// This value should be aligned with DEFAULT_CHECK_DELTA_MS in +// SafeBrowsingApiHandlerBridgeNativeUnitTestHelper. +constexpr int kExpectedCheckDeltaMs = 10; + +constexpr int kAllThreatsOfInterest[] = { + JAVA_THREAT_TYPE_UNWANTED_SOFTWARE, + JAVA_THREAT_TYPE_POTENTIALLY_HARMFUL_APPLICATION, + JAVA_THREAT_TYPE_SOCIAL_ENGINEERING, JAVA_THREAT_TYPE_BILLING}; + +SBThreatTypeSet GetAllThreatTypes() { + return CreateSBThreatTypeSet( + {SB_THREAT_TYPE_URL_UNWANTED, SB_THREAT_TYPE_URL_MALWARE, + SB_THREAT_TYPE_URL_PHISHING, SB_THREAT_TYPE_BILLING}); +} + +} // namespace + +class SafeBrowsingApiHandlerBridgeTest : public testing::Test { + public: + void SetUp() override { + env_ = base::android::AttachCurrentThread(); + ASSERT_THAT(env_, NotNull()); + Java_SafeBrowsingApiHandlerBridgeNativeUnitTestHelper_setUp(env_); + } + + void TearDown() override { + Java_SafeBrowsingApiHandlerBridgeNativeUnitTestHelper_tearDown(env_); + } + + protected: + void AddBlocklistResponse(const GURL& url, + const std::string& metadata, + const int* expected_threats_of_interest, + const size_t expected_threat_size) { + ScopedJavaLocalRef<jstring> j_url = + ConvertUTF8ToJavaString(env_, url.spec()); + Java_SafeBrowsingApiHandlerBridgeNativeUnitTestHelper_setExpectedThreatsOfInterest( + env_, j_url, + ToJavaIntArray(env_, expected_threats_of_interest, + expected_threat_size)); + Java_SafeBrowsingApiHandlerBridgeNativeUnitTestHelper_setMetadata( + env_, j_url, ConvertUTF8ToJavaString(env_, metadata)); + } + + void CheckHistogramValues(int expected_result) { + histogram_tester_.ExpectUniqueSample("SB2.RemoteCall.CheckDelta", + /*sample=*/kExpectedCheckDeltaMs, + /*expected_bucket_count=*/1); + histogram_tester_.ExpectUniqueSample("SB2.RemoteCall.Result", + /*sample=*/expected_result, + /*expected_bucket_count=*/1); + } + + raw_ptr<JNIEnv> env_; + content::BrowserTaskEnvironment task_environment_; + base::HistogramTester histogram_tester_; +}; + +TEST_F(SafeBrowsingApiHandlerBridgeTest, UrlCheck_Safe) { + GURL url("https://example.com"); + AddBlocklistResponse(url, /*metadata=*/"{}", kAllThreatsOfInterest, + /*expected_threat_size=*/4); + + auto callback = + std::make_unique<SafeBrowsingApiHandlerBridge::ResponseCallback>( + base::BindOnce([](SBThreatType matched_threat_type, + const ThreatMetadata& metadata) { + EXPECT_EQ(matched_threat_type, SB_THREAT_TYPE_SAFE); + })); + SafeBrowsingApiHandlerBridge::GetInstance().StartURLCheck( + std::move(callback), url, GetAllThreatTypes()); + task_environment_.RunUntilIdle(); + + CheckHistogramValues(/*expected_result=*/UMA_STATUS_SAFE); +} + +TEST_F(SafeBrowsingApiHandlerBridgeTest, UrlCheck_SingleThreatMatch) { + base::HistogramTester histogram_tester; + GURL url("https://example.com"); + // threat_type: 3 is unwanted. + std::string metadata = "{\"matches\":[{\"threat_type\":\"3\"}]}"; + AddBlocklistResponse(url, metadata, kAllThreatsOfInterest, + /*expected_threat_size=*/4); + + auto callback = + std::make_unique<SafeBrowsingApiHandlerBridge::ResponseCallback>( + base::BindOnce([](SBThreatType matched_threat_type, + const ThreatMetadata& metadata) { + EXPECT_EQ(matched_threat_type, SB_THREAT_TYPE_URL_UNWANTED); + })); + SafeBrowsingApiHandlerBridge::GetInstance().StartURLCheck( + std::move(callback), url, GetAllThreatTypes()); + task_environment_.RunUntilIdle(); + + CheckHistogramValues(/*expected_result=*/UMA_STATUS_MATCH); +} + +TEST_F(SafeBrowsingApiHandlerBridgeTest, UrlCheck_MultipleThreatMatch) { + GURL url("https://example.com"); + std::string metadata = + "{\"matches\":[{\"threat_type\":\"4\"}, {\"threat_type\":\"5\"}]}"; + AddBlocklistResponse(url, metadata, kAllThreatsOfInterest, + /*expected_threat_size=*/4); + + auto callback = + std::make_unique<SafeBrowsingApiHandlerBridge::ResponseCallback>( + base::BindOnce([](SBThreatType matched_threat_type, + const ThreatMetadata& metadata) { + // Although the URL matches both malware and phishing, the returned + // threat type should be malware because the severity of malware + // threat is higher. + EXPECT_EQ(matched_threat_type, SB_THREAT_TYPE_URL_MALWARE); + })); + SafeBrowsingApiHandlerBridge::GetInstance().StartURLCheck( + std::move(callback), url, GetAllThreatTypes()); + task_environment_.RunUntilIdle(); + + CheckHistogramValues(/*expected_result=*/UMA_STATUS_MATCH); +} + +TEST_F(SafeBrowsingApiHandlerBridgeTest, + UrlCheck_ThreatMatchWithSubresourceFilter) { + GURL url("https://example.com"); + const int expected_java_threat_types[] = { + JAVA_THREAT_TYPE_SUBRESOURCE_FILTER}; + std::string metadata = + "{\"matches\":[{\"threat_type\":\"13\", " + "\"sf_absv\":\"enforce\"}]}"; + AddBlocklistResponse(url, metadata, expected_java_threat_types, + /*expected_threat_size=*/1); + + auto callback = + std::make_unique<SafeBrowsingApiHandlerBridge::ResponseCallback>( + base::BindOnce([](SBThreatType matched_threat_type, + const ThreatMetadata& metadata) { + EXPECT_EQ(matched_threat_type, SB_THREAT_TYPE_SUBRESOURCE_FILTER); + SubresourceFilterMatch expected_subresource_filter_match = { + {SubresourceFilterType::ABUSIVE, + SubresourceFilterLevel::ENFORCE}}; + EXPECT_EQ(metadata.subresource_filter_match, + expected_subresource_filter_match); + })); + SafeBrowsingApiHandlerBridge::GetInstance().StartURLCheck( + std::move(callback), url, + CreateSBThreatTypeSet({SB_THREAT_TYPE_SUBRESOURCE_FILTER})); + task_environment_.RunUntilIdle(); + + CheckHistogramValues(/*expected_result=*/UMA_STATUS_MATCH); +} + +TEST_F(SafeBrowsingApiHandlerBridgeTest, UrlCheck_MultipleRequests) { + GURL unsafe_url("https://unsafe.com"); + GURL safe_url("https://safe.com"); + const int expected_java_threat_types[] = { + JAVA_THREAT_TYPE_SOCIAL_ENGINEERING}; + std::string metadata_unsafe = "{\"matches\":[{\"threat_type\":\"5\"}]}"; + std::string metadata_safe = "{}"; + AddBlocklistResponse(unsafe_url, metadata_unsafe, expected_java_threat_types, + /*expected_threat_size=*/1); + AddBlocklistResponse(safe_url, metadata_safe, expected_java_threat_types, + /*expected_threat_size=*/1); + + auto unsafe_callback = + std::make_unique<SafeBrowsingApiHandlerBridge::ResponseCallback>( + base::BindOnce([](SBThreatType matched_threat_type, + const ThreatMetadata& metadata) { + EXPECT_EQ(matched_threat_type, SB_THREAT_TYPE_URL_PHISHING); + })); + SafeBrowsingApiHandlerBridge::GetInstance().StartURLCheck( + std::move(unsafe_callback), unsafe_url, + CreateSBThreatTypeSet({SB_THREAT_TYPE_URL_PHISHING})); + auto safe_callback = + std::make_unique<SafeBrowsingApiHandlerBridge::ResponseCallback>( + base::BindOnce([](SBThreatType matched_threat_type, + const ThreatMetadata& metadata) { + EXPECT_EQ(matched_threat_type, SB_THREAT_TYPE_SAFE); + })); + SafeBrowsingApiHandlerBridge::GetInstance().StartURLCheck( + std::move(safe_callback), safe_url, + CreateSBThreatTypeSet({SB_THREAT_TYPE_URL_PHISHING})); + task_environment_.RunUntilIdle(); + + histogram_tester_.ExpectUniqueSample("SB2.RemoteCall.CheckDelta", + /*sample=*/kExpectedCheckDeltaMs, + /*expected_bucket_count=*/2); + histogram_tester_.ExpectBucketCount("SB2.RemoteCall.Result", + /*sample=*/UMA_STATUS_MATCH, + /*expected_count=*/1); + histogram_tester_.ExpectBucketCount("SB2.RemoteCall.Result", + /*sample=*/UMA_STATUS_SAFE, + /*expected_count=*/1); +} + +TEST_F(SafeBrowsingApiHandlerBridgeTest, UrlCheck_Timeout) { + Java_SafeBrowsingApiHandlerBridgeNativeUnitTestHelper_setResult( + env_, RESULT_STATUS_TIMEOUT); + GURL url("https://example.com"); + + auto callback = + std::make_unique<SafeBrowsingApiHandlerBridge::ResponseCallback>( + base::BindOnce([](SBThreatType matched_threat_type, + const ThreatMetadata& metadata) { + EXPECT_EQ(matched_threat_type, SB_THREAT_TYPE_SAFE); + })); + SafeBrowsingApiHandlerBridge::GetInstance().StartURLCheck( + std::move(callback), url, GetAllThreatTypes()); + task_environment_.RunUntilIdle(); + + CheckHistogramValues(/*expected_result=*/UMA_STATUS_TIMEOUT); +} + +TEST_F(SafeBrowsingApiHandlerBridgeTest, AllowlistCheck) { + // Csd allowlist + GURL url("https://example.com"); + ScopedJavaLocalRef<jstring> j_url = ConvertUTF8ToJavaString(env_, url.spec()); + Java_SafeBrowsingApiHandlerBridgeNativeUnitTestHelper_setCsdAllowlistMatch( + env_, j_url, true); + EXPECT_TRUE( + SafeBrowsingApiHandlerBridge::GetInstance().StartCSDAllowlistCheck(url)); + EXPECT_FALSE(SafeBrowsingApiHandlerBridge::GetInstance() + .StartHighConfidenceAllowlistCheck(url) + .value()); + Java_SafeBrowsingApiHandlerBridgeNativeUnitTestHelper_setCsdAllowlistMatch( + env_, j_url, false); + EXPECT_FALSE( + SafeBrowsingApiHandlerBridge::GetInstance().StartCSDAllowlistCheck(url)); + + // High confidence allowlist + GURL url2("https://example2.com"); + ScopedJavaLocalRef<jstring> j_url2 = + ConvertUTF8ToJavaString(env_, url2.spec()); + Java_SafeBrowsingApiHandlerBridgeNativeUnitTestHelper_setHighConfidenceAllowlistMatch( + env_, j_url2, true); + EXPECT_TRUE(SafeBrowsingApiHandlerBridge::GetInstance() + .StartHighConfidenceAllowlistCheck(url2)); + EXPECT_FALSE( + SafeBrowsingApiHandlerBridge::GetInstance().StartCSDAllowlistCheck(url2)); + Java_SafeBrowsingApiHandlerBridgeNativeUnitTestHelper_setHighConfidenceAllowlistMatch( + env_, j_url2, false); + absl::optional<bool> result = SafeBrowsingApiHandlerBridge::GetInstance() + .StartHighConfidenceAllowlistCheck(url2); + EXPECT_TRUE(result.has_value()); + EXPECT_FALSE(result.value()); + // Uninitialized + Java_SafeBrowsingApiHandlerBridgeNativeUnitTestHelper_tearDown(env_); + result = SafeBrowsingApiHandlerBridge::GetInstance() + .StartHighConfidenceAllowlistCheck(url2); + EXPECT_FALSE(result.has_value()); +} + +} // namespace safe_browsing
diff --git a/components/safe_browsing/core/browser/db/v4_database.cc b/components/safe_browsing/core/browser/db/v4_database.cc index a613814..eb5f11a 100644 --- a/components/safe_browsing/core/browser/db/v4_database.cc +++ b/components/safe_browsing/core/browser/db/v4_database.cc
@@ -21,7 +21,7 @@ #include "components/safe_browsing/core/common/proto/webui.pb.h" #if BUILDFLAG(IS_APPLE) -#include "base/mac/backup_util.h" +#include "base/apple/backup_util.h" #endif using base::TimeTicks; @@ -111,7 +111,7 @@ } #if BUILDFLAG(IS_APPLE) - base::mac::SetBackupExclusion(base_path); + base::apple::SetBackupExclusion(base_path); #endif std::unique_ptr<StoreMap> store_map = std::make_unique<StoreMap>();
diff --git a/components/sync/base/model_type.h b/components/sync/base/model_type.h index 0b0c87a..2e234d4 100644 --- a/components/sync/base/model_type.h +++ b/components/sync/base/model_type.h
@@ -264,17 +264,49 @@ // representations. This distinguishes them from Proxy types, which have no // protocol representation and are never sent to the server. constexpr ModelTypeSet ProtocolTypes() { - return ModelTypeSet( - BOOKMARKS, PREFERENCES, PASSWORDS, AUTOFILL_PROFILE, AUTOFILL, - AUTOFILL_WALLET_DATA, AUTOFILL_WALLET_METADATA, AUTOFILL_WALLET_OFFER, - AUTOFILL_WALLET_USAGE, THEMES, TYPED_URLS, EXTENSIONS, SEARCH_ENGINES, - SESSIONS, APPS, APP_SETTINGS, EXTENSION_SETTINGS, - HISTORY_DELETE_DIRECTIVES, DICTIONARY, DEVICE_INFO, PRIORITY_PREFERENCES, - SUPERVISED_USER_SETTINGS, APP_LIST, ARC_PACKAGE, PRINTERS, READING_LIST, - USER_EVENTS, NIGORI, USER_CONSENTS, SEND_TAB_TO_SELF, SECURITY_EVENTS, - WEB_APPS, WIFI_CONFIGURATIONS, OS_PREFERENCES, OS_PRIORITY_PREFERENCES, - SHARING_MESSAGE, WORKSPACE_DESK, HISTORY, PRINTERS_AUTHORIZATION_SERVERS, - CONTACT_INFO, SAVED_TAB_GROUP, POWER_BOOKMARK, WEBAUTHN_CREDENTIAL); + return {BOOKMARKS, + PREFERENCES, + PASSWORDS, + AUTOFILL_PROFILE, + AUTOFILL, + AUTOFILL_WALLET_DATA, + AUTOFILL_WALLET_METADATA, + AUTOFILL_WALLET_OFFER, + AUTOFILL_WALLET_USAGE, + THEMES, + TYPED_URLS, + EXTENSIONS, + SEARCH_ENGINES, + SESSIONS, + APPS, + APP_SETTINGS, + EXTENSION_SETTINGS, + HISTORY_DELETE_DIRECTIVES, + DICTIONARY, + DEVICE_INFO, + PRIORITY_PREFERENCES, + SUPERVISED_USER_SETTINGS, + APP_LIST, + ARC_PACKAGE, + PRINTERS, + READING_LIST, + USER_EVENTS, + NIGORI, + USER_CONSENTS, + SEND_TAB_TO_SELF, + SECURITY_EVENTS, + WEB_APPS, + WIFI_CONFIGURATIONS, + OS_PREFERENCES, + OS_PRIORITY_PREFERENCES, + SHARING_MESSAGE, + WORKSPACE_DESK, + HISTORY, + PRINTERS_AUTHORIZATION_SERVERS, + CONTACT_INFO, + SAVED_TAB_GROUP, + POWER_BOOKMARK, + WEBAUTHN_CREDENTIAL}; } // These are the normal user-controlled types. This is to distinguish from @@ -286,9 +318,12 @@ // User types which are not user-controlled. constexpr ModelTypeSet AlwaysPreferredUserTypes() { - return ModelTypeSet(DEVICE_INFO, USER_CONSENTS, SECURITY_EVENTS, - SEND_TAB_TO_SELF, SUPERVISED_USER_SETTINGS, - SHARING_MESSAGE); + return {DEVICE_INFO, + USER_CONSENTS, + SECURITY_EVENTS, + SEND_TAB_TO_SELF, + SUPERVISED_USER_SETTINGS, + SHARING_MESSAGE}; } // User types which are always encrypted. @@ -296,7 +331,7 @@ // If you add a new model type here that is conceptually different from a // password, make sure you audit UI code that refers to these types as // passwords, e.g. consumers of IsEncryptEverythingEnabled(). - return ModelTypeSet(PASSWORDS, WIFI_CONFIGURATIONS); + return {PASSWORDS, WIFI_CONFIGURATIONS}; } // This is the subset of UserTypes() that have priority over other types. These @@ -305,7 +340,7 @@ // active before all the data for non-prio types has been downloaded (which may // be a lot of data). constexpr ModelTypeSet HighPriorityUserTypes() { - return ModelTypeSet( + return { // The "Send to Your Devices" feature needs fast updating of the list of // your devices and also fast sending of the actual messages. DEVICE_INFO, SHARING_MESSAGE, @@ -321,7 +356,7 @@ // in the creation flow for a new profile. If the user has no theme in // their sync data, the browser offers a theme customization bubble which // should appear soon after opening the browser. - THEMES); + THEMES}; } // This is the subset of UserTypes() that have a *lower* priority than other @@ -330,12 +365,12 @@ // high-priority and regular types can become active before all the data for // low-priority types has been downloaded (which may be a lot of data). constexpr ModelTypeSet LowPriorityUserTypes() { - return ModelTypeSet( + return { // Downloading History may take a while, but should not block the download // of other data types. HISTORY, // User Events should not block or delay commits for other data types. - USER_EVENTS); + USER_EVENTS}; } // Returns a list of all control types. @@ -349,14 +384,13 @@ // - They support custom update application and conflict resolution logic. // - All change processing occurs on the sync thread. constexpr ModelTypeSet ControlTypes() { - return ModelTypeSet(NIGORI); + return {NIGORI}; } // Types that may commit data, but should never be included in a GetUpdates. // These are never encrypted. constexpr ModelTypeSet CommitOnlyTypes() { - return ModelTypeSet(USER_EVENTS, USER_CONSENTS, SECURITY_EVENTS, - SHARING_MESSAGE); + return {USER_EVENTS, USER_CONSENTS, SECURITY_EVENTS, SHARING_MESSAGE}; } // Types for which downloaded updates are applied immediately, before all @@ -365,7 +399,7 @@ // called (since without downloading all the data, no initial merge is // possible). constexpr ModelTypeSet ApplyUpdatesImmediatelyTypes() { - return ModelTypeSet(HISTORY); + return {HISTORY}; } // User types that can be encrypted, which is a subset of UserTypes() and a
diff --git a/components/sync/base/model_type_unittest.cc b/components/sync/base/model_type_unittest.cc index ac41874..12fb622 100644 --- a/components/sync/base/model_type_unittest.cc +++ b/components/sync/base/model_type_unittest.cc
@@ -27,7 +27,7 @@ } TEST_F(ModelTypeTest, ModelTypeSetToValue) { - const ModelTypeSet model_types(BOOKMARKS, APPS); + const ModelTypeSet model_types = {BOOKMARKS, APPS}; base::Value::List value_list(ModelTypeSetToValue(model_types)); ASSERT_EQ(2u, value_list.size());
diff --git a/components/sync/base/sync_prefs_unittest.cc b/components/sync/base/sync_prefs_unittest.cc index d7b0a37..d96ddff3c 100644 --- a/components/sync/base/sync_prefs_unittest.cc +++ b/components/sync/base/sync_prefs_unittest.cc
@@ -155,7 +155,7 @@ /*keep_everything_synced=*/false, /*registered_types=*/UserSelectableTypeSet::All(), /*selected_types=*/{type}); - EXPECT_EQ(UserSelectableTypeSet{type}, sync_prefs_->GetSelectedTypes()); + EXPECT_EQ(UserSelectableTypeSet({type}), sync_prefs_->GetSelectedTypes()); } } @@ -174,7 +174,7 @@ /*keep_everything_synced=*/false, /*registered_types=*/UserSelectableTypeSet::All(), /*selected_types=*/{type}); - UserSelectableTypeSet expected_type_set = UserSelectableTypeSet{type}; + UserSelectableTypeSet expected_type_set = {type}; expected_type_set.Remove(UserSelectableType::kPreferences); EXPECT_EQ(expected_type_set, sync_prefs_->GetSelectedTypes()); } @@ -260,7 +260,8 @@ /*sync_all_os_types=*/false, /*registered_types=*/UserSelectableOsTypeSet::All(), /*selected_types=*/{type}); - EXPECT_EQ(UserSelectableOsTypeSet{type}, sync_prefs_->GetSelectedOsTypes()); + EXPECT_EQ(UserSelectableOsTypeSet({type}), + sync_prefs_->GetSelectedOsTypes()); // Browser types are not changed. EXPECT_EQ(browser_types, sync_prefs_->GetSelectedTypes()); } @@ -292,7 +293,7 @@ /*sync_all_os_types=*/false, /*registered_types=*/UserSelectableOsTypeSet::All(), /*selected_types=*/{type}); - UserSelectableOsTypeSet expected_type_set = UserSelectableOsTypeSet{type}; + UserSelectableOsTypeSet expected_type_set = {type}; expected_type_set.Remove(UserSelectableOsType::kOsPreferences); EXPECT_EQ(expected_type_set, sync_prefs_->GetSelectedOsTypes()); } @@ -469,8 +470,8 @@ } TEST_F(SyncPrefsMigrationTest, SyncRequested_SyncRequestedWithSomeTypes) { - const UserSelectableTypeSet enabled_types{UserSelectableType::kBookmarks, - UserSelectableType::kPreferences}; + const UserSelectableTypeSet enabled_types = { + UserSelectableType::kBookmarks, UserSelectableType::kPreferences}; pref_service_.SetBoolean(prefs::internal::kSyncRequested, true); pref_service_.SetBoolean(prefs::internal::kSyncFirstSetupComplete, true); pref_service_.SetBoolean(prefs::internal::kSyncKeepEverythingSynced, false); @@ -526,8 +527,8 @@ } TEST_F(SyncPrefsMigrationTest, SyncRequested_SyncNotRequestedWithSomeTypes) { - const UserSelectableTypeSet enabled_types{UserSelectableType::kBookmarks, - UserSelectableType::kPreferences}; + const UserSelectableTypeSet enabled_types = { + UserSelectableType::kBookmarks, UserSelectableType::kPreferences}; pref_service_.SetBoolean(prefs::internal::kSyncRequested, false); pref_service_.SetBoolean(prefs::internal::kSyncFirstSetupComplete, true); pref_service_.SetBoolean(prefs::internal::kSyncKeepEverythingSynced, false); @@ -549,8 +550,8 @@ } TEST_F(SyncPrefsMigrationTest, SyncRequested_SyncNotRequestedWithAllTypes) { - const UserSelectableTypeSet enabled_types{UserSelectableType::kBookmarks, - UserSelectableType::kPreferences}; + const UserSelectableTypeSet enabled_types = { + UserSelectableType::kBookmarks, UserSelectableType::kPreferences}; pref_service_.SetBoolean(prefs::internal::kSyncRequested, false); pref_service_.SetBoolean(prefs::internal::kSyncFirstSetupComplete, true); pref_service_.SetBoolean(prefs::internal::kSyncKeepEverythingSynced, true);
diff --git a/components/sync/driver/data_type_manager_impl_unittest.cc b/components/sync/driver/data_type_manager_impl_unittest.cc index 1797239..33366a7 100644 --- a/components/sync/driver/data_type_manager_impl_unittest.cc +++ b/components/sync/driver/data_type_manager_impl_unittest.cc
@@ -33,7 +33,7 @@ // Helpers for unioning with control types. ModelTypeSet AddControlTypesTo(ModelType type) { - return Union(ControlTypes(), ModelTypeSet(type)); + return Union(ControlTypes(), {type}); } ConfigureContext BuildConfigureContext(ConfigureReason reason, @@ -300,13 +300,13 @@ SetConfigureStartExpectation(); SetConfigureDoneExpectation(DataTypeManager::OK, DataTypeStatusTable()); - Configure(ModelTypeSet(BOOKMARKS)); + Configure({BOOKMARKS}); EXPECT_EQ(DataTypeManager::CONFIGURING, dtm_->state()); - EXPECT_EQ(ModelTypeSet(BOOKMARKS), configurer_.connected_types()); + EXPECT_EQ(ModelTypeSet({BOOKMARKS}), configurer_.connected_types()); EXPECT_TRUE(dtm_->GetTypesWithPendingDownloadForInitialSync().Has(BOOKMARKS)); FinishDownload(ModelTypeSet(), ModelTypeSet()); // control types - FinishDownload(ModelTypeSet(BOOKMARKS), ModelTypeSet()); + FinishDownload({BOOKMARKS}, ModelTypeSet()); EXPECT_EQ(DataTypeManager::CONFIGURED, dtm_->state()); EXPECT_EQ(1U, configurer_.connected_types().Size()); EXPECT_TRUE(dtm_->GetTypesWithPendingDownloadForInitialSync().Empty()); @@ -327,7 +327,7 @@ SetConfigureStartExpectation(); SetConfigureDoneExpectation(DataTypeManager::OK, DataTypeStatusTable()); - Configure(ModelTypeSet(BOOKMARKS)); + Configure({BOOKMARKS}); ASSERT_EQ(DataTypeManager::CONFIGURING, dtm_->state()); FinishDownload(ModelTypeSet(), ModelTypeSet()); // control types @@ -354,9 +354,9 @@ SetConfigureDoneExpectation(DataTypeManager::ABORTED, DataTypeStatusTable()); - Configure(ModelTypeSet(BOOKMARKS)); + Configure({BOOKMARKS}); EXPECT_EQ(DataTypeManager::CONFIGURING, dtm_->state()); - EXPECT_EQ(ModelTypeSet(BOOKMARKS), configurer_.connected_types()); + EXPECT_EQ(ModelTypeSet({BOOKMARKS}), configurer_.connected_types()); EXPECT_TRUE( dtm_->GetTypesWithPendingDownloadForInitialSync().Has(BOOKMARKS)); @@ -366,7 +366,7 @@ EXPECT_TRUE(dtm_->GetTypesWithPendingDownloadForInitialSync().Empty()); } - FinishDownloadWhileStopped(ModelTypeSet(BOOKMARKS), ModelTypeSet()); + FinishDownloadWhileStopped({BOOKMARKS}, ModelTypeSet()); EXPECT_TRUE(configurer_.connected_types().Empty()); } @@ -383,7 +383,7 @@ SetConfigureDoneExpectation(DataTypeManager::ABORTED, DataTypeStatusTable()); - Configure(ModelTypeSet(BOOKMARKS)); + Configure({BOOKMARKS}); ASSERT_EQ(DataTypeManager::CONFIGURING, dtm_->state()); ASSERT_EQ(DataTypeController::MODEL_STARTING, GetController(BOOKMARKS)->state()); @@ -414,7 +414,7 @@ SetConfigureDoneExpectation(DataTypeManager::OK, DataTypeStatusTable()); // Step 1. - Configure(ModelTypeSet(PASSWORDS)); + Configure({PASSWORDS}); EXPECT_EQ(DataTypeManager::CONFIGURING, dtm_->state()); // Step 2. @@ -423,15 +423,14 @@ EXPECT_EQ(DataTypeManager::CONFIGURED, dtm_->state()); // Step 3. - FailEncryptionFor(ModelTypeSet(PASSWORDS)); + FailEncryptionFor({PASSWORDS}); // Step 4. SetConfigureStartExpectation(); - SetConfigureDoneExpectation( - DataTypeManager::OK, - BuildStatusTable(/*crypto_errors=*/ModelTypeSet(PASSWORDS), - ModelTypeSet(), ModelTypeSet())); - Configure(ModelTypeSet(PASSWORDS)); + SetConfigureDoneExpectation(DataTypeManager::OK, + BuildStatusTable(/*crypto_errors=*/{PASSWORDS}, + ModelTypeSet(), ModelTypeSet())); + Configure({PASSWORDS}); EXPECT_EQ(DataTypeManager::CONFIGURING, dtm_->state()); FinishDownload(ModelTypeSet(), ModelTypeSet()); // priority types EXPECT_EQ(DataTypeManager::CONFIGURED, dtm_->state()); @@ -456,17 +455,17 @@ SetConfigureDoneExpectation(DataTypeManager::OK, DataTypeStatusTable()); // Step 1. - Configure(ModelTypeSet(BOOKMARKS)); + Configure({BOOKMARKS}); EXPECT_EQ(DataTypeManager::CONFIGURING, dtm_->state()); - EXPECT_EQ(ModelTypeSet(BOOKMARKS), configurer_.connected_types()); - EXPECT_EQ(ModelTypeSet(BOOKMARKS), + EXPECT_EQ(ModelTypeSet({BOOKMARKS}), configurer_.connected_types()); + EXPECT_EQ(ModelTypeSet({BOOKMARKS}), dtm_->GetTypesWithPendingDownloadForInitialSync()); // Step 2. - FinishDownload(ModelTypeSet(NIGORI), ModelTypeSet()); // control types - EXPECT_EQ(ModelTypeSet(BOOKMARKS), + FinishDownload({NIGORI}, ModelTypeSet()); // control types + EXPECT_EQ(ModelTypeSet({BOOKMARKS}), dtm_->GetTypesWithPendingDownloadForInitialSync()); - FinishDownload(ModelTypeSet(BOOKMARKS), ModelTypeSet()); + FinishDownload({BOOKMARKS}, ModelTypeSet()); EXPECT_EQ(DataTypeManager::CONFIGURED, dtm_->state()); EXPECT_EQ(ModelTypeSet(), dtm_->GetTypesWithPendingDownloadForInitialSync()); @@ -475,19 +474,19 @@ SetConfigureDoneExpectation(DataTypeManager::OK, DataTypeStatusTable()); // Step 3. - Configure(ModelTypeSet(BOOKMARKS, PREFERENCES)); + Configure({BOOKMARKS, PREFERENCES}); EXPECT_EQ(DataTypeManager::CONFIGURING, dtm_->state()); - EXPECT_EQ(ModelTypeSet(BOOKMARKS, PREFERENCES), + EXPECT_EQ(ModelTypeSet({BOOKMARKS, PREFERENCES}), configurer_.connected_types()); - EXPECT_EQ(ModelTypeSet(PREFERENCES), + EXPECT_EQ(ModelTypeSet({PREFERENCES}), dtm_->GetTypesWithPendingDownloadForInitialSync()); EXPECT_EQ(0, GetController(BOOKMARKS)->model()->clear_metadata_call_count()); // Step 4. FinishDownload(ModelTypeSet(), ModelTypeSet()); // control types - EXPECT_EQ(ModelTypeSet(PREFERENCES), + EXPECT_EQ(ModelTypeSet({PREFERENCES}), dtm_->GetTypesWithPendingDownloadForInitialSync()); - FinishDownload(ModelTypeSet(BOOKMARKS, PREFERENCES), ModelTypeSet()); + FinishDownload({BOOKMARKS, PREFERENCES}, ModelTypeSet()); EXPECT_EQ(DataTypeManager::CONFIGURED, dtm_->state()); EXPECT_EQ(ModelTypeSet(), dtm_->GetTypesWithPendingDownloadForInitialSync()); @@ -512,13 +511,13 @@ SetConfigureDoneExpectation(DataTypeManager::OK, DataTypeStatusTable()); // Step 1. - Configure(ModelTypeSet(BOOKMARKS)); + Configure({BOOKMARKS}); EXPECT_EQ(DataTypeManager::CONFIGURING, dtm_->state()); - EXPECT_EQ(ModelTypeSet(BOOKMARKS), configurer_.connected_types()); + EXPECT_EQ(ModelTypeSet({BOOKMARKS}), configurer_.connected_types()); // Step 2. FinishDownload(ModelTypeSet(), ModelTypeSet()); // control types - FinishDownload(ModelTypeSet(BOOKMARKS), ModelTypeSet()); + FinishDownload({BOOKMARKS}, ModelTypeSet()); EXPECT_EQ(DataTypeManager::CONFIGURED, dtm_->state()); observer_.ResetExpectations(); @@ -526,14 +525,14 @@ SetConfigureDoneExpectation(DataTypeManager::OK, DataTypeStatusTable()); // Step 3. - Configure(ModelTypeSet(PREFERENCES)); + Configure({PREFERENCES}); EXPECT_EQ(DataTypeManager::CONFIGURING, dtm_->state()); - EXPECT_EQ(ModelTypeSet(PREFERENCES), configurer_.connected_types()); + EXPECT_EQ(ModelTypeSet({PREFERENCES}), configurer_.connected_types()); EXPECT_EQ(1, GetController(BOOKMARKS)->model()->clear_metadata_call_count()); // Step 4. FinishDownload(ModelTypeSet(), ModelTypeSet()); // control types - FinishDownload(ModelTypeSet(PREFERENCES), ModelTypeSet()); + FinishDownload({PREFERENCES}, ModelTypeSet()); EXPECT_EQ(DataTypeManager::CONFIGURED, dtm_->state()); // Step 5. @@ -553,7 +552,7 @@ SetConfigureDoneExpectation(DataTypeManager::OK, DataTypeStatusTable()); // Step 1: Configure with first controller (model stays loading). - Configure(ModelTypeSet(BOOKMARKS)); + Configure({BOOKMARKS}); EXPECT_EQ(DataTypeManager::CONFIGURING, dtm_->state()); EXPECT_TRUE(configurer_.connected_types().Empty()); @@ -563,7 +562,7 @@ ASSERT_EQ(DataTypeController::MODEL_STARTING, GetController(BOOKMARKS)->state()); ASSERT_FALSE(dtm_->needs_reconfigure_for_test()); - Configure(ModelTypeSet(BOOKMARKS, PREFERENCES)); + Configure({BOOKMARKS, PREFERENCES}); EXPECT_EQ(DataTypeManager::CONFIGURING, dtm_->state()); EXPECT_TRUE(dtm_->needs_reconfigure_for_test()); @@ -580,9 +579,9 @@ ASSERT_EQ(DataTypeController::RUNNING, GetController(PREFERENCES)->state()); EXPECT_EQ(DataTypeManager::CONFIGURING, dtm_->state()); FinishDownload(ModelTypeSet(), ModelTypeSet()); // control types - FinishDownload(ModelTypeSet(BOOKMARKS, PREFERENCES), ModelTypeSet()); + FinishDownload({BOOKMARKS, PREFERENCES}, ModelTypeSet()); EXPECT_EQ(DataTypeManager::CONFIGURED, dtm_->state()); - EXPECT_EQ(ModelTypeSet(BOOKMARKS, PREFERENCES), + EXPECT_EQ(ModelTypeSet({BOOKMARKS, PREFERENCES}), configurer_.connected_types()); // Step 5: Stop the DTM. @@ -601,10 +600,9 @@ SetConfigureDoneExpectation( DataTypeManager::UNKNOWN, BuildStatusTable(ModelTypeSet(), - /*datatype_errors=*/ModelTypeSet(BOOKMARKS), - ModelTypeSet())); + /*datatype_errors=*/{BOOKMARKS}, ModelTypeSet())); - Configure(ModelTypeSet(BOOKMARKS)); + Configure({BOOKMARKS}); EXPECT_EQ(DataTypeManager::CONFIGURING, dtm_->state()); EXPECT_TRUE(configurer_.connected_types().Empty()); @@ -635,12 +633,12 @@ SetConfigureDoneExpectation(DataTypeManager::OK, DataTypeStatusTable()); // Step 1. - Configure(ModelTypeSet(BOOKMARKS)); + Configure({BOOKMARKS}); EXPECT_EQ(DataTypeManager::CONFIGURING, dtm_->state()); - EXPECT_EQ(ModelTypeSet(BOOKMARKS), configurer_.connected_types()); + EXPECT_EQ(ModelTypeSet({BOOKMARKS}), configurer_.connected_types()); // Step 2. - Configure(ModelTypeSet(BOOKMARKS, PREFERENCES)); + Configure({BOOKMARKS, PREFERENCES}); EXPECT_EQ(DataTypeManager::CONFIGURING, dtm_->state()); // Step 3. @@ -649,9 +647,9 @@ EXPECT_EQ(DataTypeManager::CONFIGURING, dtm_->state()); // Step 4. - FinishDownload(ModelTypeSet(BOOKMARKS, PREFERENCES), ModelTypeSet()); + FinishDownload({BOOKMARKS, PREFERENCES}, ModelTypeSet()); EXPECT_EQ(DataTypeManager::CONFIGURED, dtm_->state()); - EXPECT_EQ(ModelTypeSet(BOOKMARKS, PREFERENCES), + EXPECT_EQ(ModelTypeSet({BOOKMARKS, PREFERENCES}), configurer_.connected_types()); // Step 5. @@ -677,24 +675,24 @@ SetConfigureDoneExpectation(DataTypeManager::OK, DataTypeStatusTable()); // Step 1. - Configure(ModelTypeSet(BOOKMARKS)); + Configure({BOOKMARKS}); FinishDownload(ModelTypeSet(), ModelTypeSet()); // control types EXPECT_EQ(DataTypeManager::CONFIGURING, dtm_->state()); - EXPECT_EQ(ModelTypeSet(BOOKMARKS), configurer_.connected_types()); + EXPECT_EQ(ModelTypeSet({BOOKMARKS}), configurer_.connected_types()); // Step 2. - Configure(ModelTypeSet(BOOKMARKS, PREFERENCES)); + Configure({BOOKMARKS, PREFERENCES}); EXPECT_EQ(DataTypeManager::CONFIGURING, dtm_->state()); // Step 3. FinishDownload(ModelTypeSet(), ModelTypeSet()); // control types - FinishDownload(ModelTypeSet(BOOKMARKS), ModelTypeSet()); + FinishDownload({BOOKMARKS}, ModelTypeSet()); EXPECT_EQ(DataTypeManager::CONFIGURING, dtm_->state()); // Step 4. - FinishDownload(ModelTypeSet(BOOKMARKS, PREFERENCES), ModelTypeSet()); + FinishDownload({BOOKMARKS, PREFERENCES}, ModelTypeSet()); EXPECT_EQ(DataTypeManager::CONFIGURED, dtm_->state()); - EXPECT_EQ(ModelTypeSet(BOOKMARKS, PREFERENCES), + EXPECT_EQ(ModelTypeSet({BOOKMARKS, PREFERENCES}), configurer_.connected_types()); // Step 5. @@ -712,9 +710,9 @@ SetConfigureDoneExpectation(DataTypeManager::OK, DataTypeStatusTable()); // Initial setup. - Configure(ModelTypeSet(PRIORITY_PREFERENCES)); + Configure({PRIORITY_PREFERENCES}); FinishDownload(ModelTypeSet(), ModelTypeSet()); // control types - FinishDownload(ModelTypeSet(PRIORITY_PREFERENCES), ModelTypeSet()); + FinishDownload({PRIORITY_PREFERENCES}, ModelTypeSet()); // We've now configured priority prefs and (implicitly) the control types. EXPECT_EQ(DataTypeManager::CONFIGURED, dtm_->state()); @@ -746,7 +744,7 @@ SetConfigureDoneExpectation(DataTypeManager::OK, DataTypeStatusTable()); Configure(to_migrate); FinishDownload(ControlTypes(), ModelTypeSet()); // control types - FinishDownload(ModelTypeSet(PRIORITY_PREFERENCES), ModelTypeSet()); + FinishDownload({PRIORITY_PREFERENCES}, ModelTypeSet()); EXPECT_EQ(DataTypeManager::CONFIGURED, dtm_->state()); EXPECT_EQ(1, GetController(PRIORITY_PREFERENCES) ->model() @@ -761,15 +759,15 @@ // Initial configure. SetConfigureStartExpectation(); SetConfigureDoneExpectation(DataTypeManager::OK, DataTypeStatusTable()); - Configure(ModelTypeSet(BOOKMARKS)); + Configure({BOOKMARKS}); FinishDownload(ModelTypeSet(), ModelTypeSet()); // control types - FinishDownload(ModelTypeSet(BOOKMARKS), ModelTypeSet()); + FinishDownload(ModelTypeSet({BOOKMARKS}), ModelTypeSet()); EXPECT_EQ(DataTypeManager::CONFIGURED, dtm_->state()); observer_.ResetExpectations(); // Purge the Nigori type. SetConfigureStartExpectation(); - dtm_->PurgeForMigration(ModelTypeSet(NIGORI)); + dtm_->PurgeForMigration({NIGORI}); EXPECT_EQ(DataTypeManager::CONFIGURING, dtm_->state()); observer_.ResetExpectations(); @@ -783,7 +781,7 @@ // - PREFERENCES: which is new and will need to be downloaded, and // - NIGORI: (added implicitly because it is a control type) which // the DTM is part-way through purging. - Configure(ModelTypeSet(BOOKMARKS, PREFERENCES)); + Configure({BOOKMARKS, PREFERENCES}); EXPECT_EQ(DataTypeManager::CONFIGURING, dtm_->state()); // Invoke the callback we've been waiting for since we asked to purge NIGORI. @@ -795,7 +793,7 @@ // Now invoke the callback for the second configure request. FinishDownload(ModelTypeSet(), ModelTypeSet()); // control types - FinishDownload(ModelTypeSet(BOOKMARKS, PREFERENCES), ModelTypeSet()); + FinishDownload({BOOKMARKS, PREFERENCES}, ModelTypeSet()); EXPECT_EQ(DataTypeManager::CONFIGURED, dtm_->state()); EXPECT_EQ(0, GetController(BOOKMARKS)->model()->clear_metadata_call_count()); @@ -820,7 +818,7 @@ // Start the configuration. ASSERT_EQ(0, configurer_.configure_call_count()); - Configure(ModelTypeSet(BOOKMARKS, HISTORY, PRIORITY_PREFERENCES)); + Configure({BOOKMARKS, HISTORY, PRIORITY_PREFERENCES}); // This causes an immediate ConfigureDataTypes() call for control types, i.e. // Nigori. It's important that this does *not* ask for any types to be // downloaded, see crbug.com/1170318 and crbug.com/1187914. @@ -834,16 +832,16 @@ last_configure_params().to_download); // BOOKMARKS is downloaded after PRIORITY_PREFERENCES finishes. - FinishDownload(ModelTypeSet(PRIORITY_PREFERENCES), ModelTypeSet()); + FinishDownload({PRIORITY_PREFERENCES}, ModelTypeSet()); EXPECT_EQ(DataTypeManager::CONFIGURING, dtm_->state()); EXPECT_EQ(AddControlTypesTo(BOOKMARKS), last_configure_params().to_download); // HISTORY is downloaded after BOOKMARKS finishes. - FinishDownload(ModelTypeSet(BOOKMARKS), ModelTypeSet()); + FinishDownload({BOOKMARKS}, ModelTypeSet()); EXPECT_EQ(DataTypeManager::CONFIGURING, dtm_->state()); EXPECT_EQ(AddControlTypesTo(HISTORY), last_configure_params().to_download); - FinishDownload(ModelTypeSet(HISTORY), ModelTypeSet()); + FinishDownload({HISTORY}, ModelTypeSet()); EXPECT_EQ(DataTypeManager::CONFIGURED, dtm_->state()); } @@ -858,22 +856,22 @@ // Start a configuration with BOOKMARKS and PRIORITY_PREFERENCES, and finish // the download of PRIORITY_PREFERENCES. - Configure(ModelTypeSet(BOOKMARKS, PRIORITY_PREFERENCES)); + Configure({BOOKMARKS, PRIORITY_PREFERENCES}); EXPECT_EQ(DataTypeManager::CONFIGURING, dtm_->state()); FinishDownload(ModelTypeSet(), ModelTypeSet()); // control types EXPECT_EQ(AddControlTypesTo(PRIORITY_PREFERENCES), last_configure_params().to_download); - FinishDownload(ModelTypeSet(PRIORITY_PREFERENCES), ModelTypeSet()); + FinishDownload({PRIORITY_PREFERENCES}, ModelTypeSet()); EXPECT_EQ(DataTypeManager::CONFIGURING, dtm_->state()); EXPECT_EQ(AddControlTypesTo(BOOKMARKS), last_configure_params().to_download); // Enable syncing for APPS while the download of BOOKMARKS is still pending. - Configure(ModelTypeSet(BOOKMARKS, PRIORITY_PREFERENCES, APPS)); + Configure({BOOKMARKS, PRIORITY_PREFERENCES, APPS}); EXPECT_EQ(DataTypeManager::CONFIGURING, dtm_->state()); // Reconfiguration starts after downloading of previous types finishes. - FinishDownload(ModelTypeSet(BOOKMARKS), ModelTypeSet()); + FinishDownload({BOOKMARKS}, ModelTypeSet()); EXPECT_EQ(DataTypeManager::CONFIGURING, dtm_->state()); EXPECT_EQ(ModelTypeSet(), last_configure_params().to_download); @@ -881,12 +879,12 @@ // Priority types: Nothing to download, since PRIORITY_PREFERENCES was // downloaded before. EXPECT_EQ(ModelTypeSet(), last_configure_params().to_download); - FinishDownload(ModelTypeSet(PRIORITY_PREFERENCES), ModelTypeSet()); + FinishDownload({PRIORITY_PREFERENCES}, ModelTypeSet()); EXPECT_EQ(DataTypeManager::CONFIGURING, dtm_->state()); // Regular types: Only the newly-enabled APPS still needs to be downloaded. EXPECT_EQ(AddControlTypesTo(APPS), last_configure_params().to_download); - FinishDownload(ModelTypeSet(BOOKMARKS, APPS), ModelTypeSet()); + FinishDownload({BOOKMARKS, APPS}, ModelTypeSet()); EXPECT_EQ(DataTypeManager::CONFIGURED, dtm_->state()); } @@ -899,14 +897,14 @@ SetConfigureDoneExpectation(DataTypeManager::ABORTED, DataTypeStatusTable()); // Initially only PRIORITY_PREFERENCES is configured. - Configure(ModelTypeSet(BOOKMARKS, PRIORITY_PREFERENCES)); + Configure({BOOKMARKS, PRIORITY_PREFERENCES}); EXPECT_EQ(DataTypeManager::CONFIGURING, dtm_->state()); FinishDownload(ModelTypeSet(), ModelTypeSet()); // control types EXPECT_EQ(AddControlTypesTo(PRIORITY_PREFERENCES), last_configure_params().to_download); // BOOKMARKS is configured after download of PRIORITY_PREFERENCES finishes. - FinishDownload(ModelTypeSet(PRIORITY_PREFERENCES), ModelTypeSet()); + FinishDownload({PRIORITY_PREFERENCES}, ModelTypeSet()); EXPECT_EQ(DataTypeManager::CONFIGURING, dtm_->state()); EXPECT_EQ(AddControlTypesTo(BOOKMARKS), last_configure_params().to_download); @@ -932,18 +930,17 @@ SetConfigureDoneExpectation( DataTypeManager::OK, BuildStatusTable(ModelTypeSet(), - /*datatype_errors=*/ModelTypeSet(BOOKMARKS), - ModelTypeSet())); + /*datatype_errors=*/{BOOKMARKS}, ModelTypeSet())); // Initially only PRIORITY_PREFERENCES is configured. - Configure(ModelTypeSet(BOOKMARKS, PRIORITY_PREFERENCES)); + Configure({BOOKMARKS, PRIORITY_PREFERENCES}); EXPECT_EQ(DataTypeManager::CONFIGURING, dtm_->state()); FinishDownload(ModelTypeSet(), ModelTypeSet()); // control types EXPECT_EQ(AddControlTypesTo(PRIORITY_PREFERENCES), last_configure_params().to_download); // BOOKMARKS is configured after download of PRIORITY_PREFERENCES finishes. - FinishDownload(ModelTypeSet(PRIORITY_PREFERENCES), ModelTypeSet()); + FinishDownload({PRIORITY_PREFERENCES}, ModelTypeSet()); EXPECT_EQ(DataTypeManager::CONFIGURING, dtm_->state()); EXPECT_EQ(AddControlTypesTo(BOOKMARKS), last_configure_params().to_download); @@ -953,7 +950,7 @@ EXPECT_EQ(DataTypeController::RUNNING, GetController(BOOKMARKS)->state()); // Make BOOKMARKS download fail. PRIORITY_PREFERENCES is still running. - FinishDownload(ModelTypeSet(), ModelTypeSet(BOOKMARKS)); + FinishDownload(ModelTypeSet(), {BOOKMARKS}); EXPECT_EQ(DataTypeManager::CONFIGURING, dtm_->state()); EXPECT_EQ(DataTypeController::RUNNING, GetController(PRIORITY_PREFERENCES)->state()); @@ -961,7 +958,7 @@ // Finish downloading of PRIORITY_PREFERENCES. This will trigger a // reconfiguration to disable bookmarks. FinishDownload(ModelTypeSet(), ModelTypeSet()); // control types - FinishDownload(ModelTypeSet(PRIORITY_PREFERENCES), ModelTypeSet()); + FinishDownload({PRIORITY_PREFERENCES}, ModelTypeSet()); EXPECT_EQ(DataTypeManager::CONFIGURED, dtm_->state()); EXPECT_EQ(ModelTypeSet(), last_configure_params().to_download); EXPECT_EQ(DataTypeController::RUNNING, @@ -978,7 +975,7 @@ Configure({BOOKMARKS, APPS}); FinishDownload(ModelTypeSet(), ModelTypeSet()); // control types EXPECT_EQ(AddControlTypesTo(BOOKMARKS), last_configure_params().to_download); - FinishDownload(ModelTypeSet(BOOKMARKS), ModelTypeSet()); + FinishDownload({BOOKMARKS}, ModelTypeSet()); dtm_->Stop(SyncStopMetadataFate::KEEP_METADATA); EXPECT_EQ(DataTypeManager::STOPPED, dtm_->state()); @@ -991,11 +988,10 @@ // Bookmarks is never started due to failing preconditions. SetConfigureStartExpectation(); - SetConfigureDoneExpectation( - DataTypeManager::OK, - BuildStatusTable(ModelTypeSet(), ModelTypeSet(), - /*unready_errors=*/ModelTypeSet(BOOKMARKS))); - Configure(ModelTypeSet(BOOKMARKS)); + SetConfigureDoneExpectation(DataTypeManager::OK, + BuildStatusTable(ModelTypeSet(), ModelTypeSet(), + /*unready_errors=*/{BOOKMARKS})); + Configure({BOOKMARKS}); FinishDownload(ModelTypeSet(), ModelTypeSet()); // control types EXPECT_EQ(DataTypeController::NOT_RUNNING, GetController(BOOKMARKS)->state()); EXPECT_EQ(DataTypeManager::CONFIGURED, dtm_->state()); @@ -1010,7 +1006,7 @@ EXPECT_EQ(DataTypeManager::CONFIGURING, dtm_->state()); FinishDownload(ModelTypeSet(), ModelTypeSet()); // control types - FinishDownload(ModelTypeSet(BOOKMARKS), ModelTypeSet()); + FinishDownload({BOOKMARKS}, ModelTypeSet()); EXPECT_EQ(DataTypeManager::CONFIGURED, dtm_->state()); EXPECT_EQ(1U, configurer_.connected_types().Size()); @@ -1039,7 +1035,7 @@ SetConfigureStartExpectation(); SetConfigureDoneExpectation(DataTypeManager::OK, expected_status_table); - Configure(ModelTypeSet(BOOKMARKS)); + Configure({BOOKMARKS}); FinishDownload(ModelTypeSet(), ModelTypeSet()); // control types EXPECT_EQ(DataTypeController::NOT_RUNNING, GetController(BOOKMARKS)->state()); @@ -1058,14 +1054,13 @@ // Bookmarks is never started due to failing preconditions. SetConfigureStartExpectation(); - SetConfigureDoneExpectation( - DataTypeManager::OK, - BuildStatusTable(ModelTypeSet(), ModelTypeSet(), - /*unready_errors=*/ModelTypeSet(BOOKMARKS))); - Configure(ModelTypeSet(BOOKMARKS)); + SetConfigureDoneExpectation(DataTypeManager::OK, + BuildStatusTable(ModelTypeSet(), ModelTypeSet(), + /*unready_errors=*/{BOOKMARKS})); + Configure({BOOKMARKS}); // Second Configure sets a flag to perform reconfiguration after the first one // is done. - Configure(ModelTypeSet(BOOKMARKS)); + Configure({BOOKMARKS}); // Reset errors before triggering reconfiguration. dtm_->ResetDataTypeErrors(); @@ -1085,11 +1080,10 @@ // Bookmarks is never started due to failing preconditions. SetConfigureStartExpectation(); - SetConfigureDoneExpectation( - DataTypeManager::OK, - BuildStatusTable(ModelTypeSet(), ModelTypeSet(), - /*unready_errors=*/ModelTypeSet(BOOKMARKS))); - Configure(ModelTypeSet(BOOKMARKS)); + SetConfigureDoneExpectation(DataTypeManager::OK, + BuildStatusTable(ModelTypeSet(), ModelTypeSet(), + /*unready_errors=*/{BOOKMARKS})); + Configure({BOOKMARKS}); FinishDownload(ModelTypeSet(), ModelTypeSet()); // control types ASSERT_EQ(DataTypeController::NOT_RUNNING, GetController(BOOKMARKS)->state()); ASSERT_EQ(DataTypeManager::CONFIGURED, dtm_->state()); @@ -1106,7 +1100,7 @@ SetConfigureDoneExpectation(DataTypeManager::OK, DataTypeStatusTable()); FinishDownload(ModelTypeSet(), ModelTypeSet()); // control types - FinishDownload(ModelTypeSet(BOOKMARKS), ModelTypeSet()); + FinishDownload({BOOKMARKS}, ModelTypeSet()); EXPECT_EQ(DataTypeManager::CONFIGURED, dtm_->state()); EXPECT_EQ(1U, configurer_.connected_types().Size()); @@ -1126,10 +1120,9 @@ SetConfigureStartExpectation(); SetConfigureDoneExpectation( DataTypeManager::OK, - BuildStatusTable( - ModelTypeSet(), ModelTypeSet(), - /*unready_errors=*/ModelTypeSet(BOOKMARKS, PREFERENCES))); - Configure(ModelTypeSet(BOOKMARKS, PREFERENCES)); + BuildStatusTable(ModelTypeSet(), ModelTypeSet(), + /*unready_errors=*/{BOOKMARKS, PREFERENCES})); + Configure({BOOKMARKS, PREFERENCES}); FinishDownload(ModelTypeSet(), ModelTypeSet()); // control types ASSERT_EQ(DataTypeController::NOT_RUNNING, GetController(BOOKMARKS)->state()); ASSERT_EQ(DataTypeController::NOT_RUNNING, @@ -1156,7 +1149,7 @@ SetConfigureDoneExpectation(DataTypeManager::OK, DataTypeStatusTable()); FinishDownload(ModelTypeSet(), ModelTypeSet()); // control types - FinishDownload(ModelTypeSet(BOOKMARKS, PREFERENCES), ModelTypeSet()); + FinishDownload({BOOKMARKS, PREFERENCES}, ModelTypeSet()); EXPECT_EQ(DataTypeManager::CONFIGURED, dtm_->state()); EXPECT_EQ(2U, configurer_.connected_types().Size()); @@ -1175,10 +1168,9 @@ SetConfigureStartExpectation(); SetConfigureDoneExpectation( DataTypeManager::OK, - BuildStatusTable( - ModelTypeSet(), ModelTypeSet(), - /*unready_errors=*/ModelTypeSet(BOOKMARKS, PREFERENCES))); - Configure(ModelTypeSet(BOOKMARKS, PREFERENCES)); + BuildStatusTable(ModelTypeSet(), ModelTypeSet(), + /*unready_errors=*/{BOOKMARKS, PREFERENCES})); + Configure({BOOKMARKS, PREFERENCES}); FinishDownload(ModelTypeSet(), ModelTypeSet()); // control types ASSERT_EQ(DataTypeController::NOT_RUNNING, GetController(BOOKMARKS)->state()); ASSERT_EQ(DataTypeController::NOT_RUNNING, @@ -1197,12 +1189,11 @@ // Set the expectations for the reconfiguration - just prefs are unready now. SetConfigureDoneExpectation( - DataTypeManager::OK, - BuildStatusTable(ModelTypeSet(), ModelTypeSet(), - /*unready_errors=*/ModelTypeSet(PREFERENCES))); + DataTypeManager::OK, BuildStatusTable(ModelTypeSet(), ModelTypeSet(), + /*unready_errors=*/{PREFERENCES})); FinishDownload(ModelTypeSet(), ModelTypeSet()); // control types - FinishDownload(ModelTypeSet(BOOKMARKS), ModelTypeSet()); + FinishDownload({BOOKMARKS}, ModelTypeSet()); EXPECT_EQ(DataTypeManager::CONFIGURED, dtm_->state()); EXPECT_EQ(1U, configurer_.connected_types().Size()); @@ -1216,11 +1207,10 @@ // Bookmarks is never started due to failing preconditions. SetConfigureStartExpectation(); - SetConfigureDoneExpectation( - DataTypeManager::OK, - BuildStatusTable(ModelTypeSet(), ModelTypeSet(), - /*unready_errors=*/ModelTypeSet(BOOKMARKS))); - Configure(ModelTypeSet(BOOKMARKS)); + SetConfigureDoneExpectation(DataTypeManager::OK, + BuildStatusTable(ModelTypeSet(), ModelTypeSet(), + /*unready_errors=*/{BOOKMARKS})); + Configure({BOOKMARKS}); FinishDownload(ModelTypeSet(), ModelTypeSet()); // control types ASSERT_EQ(DataTypeController::NOT_RUNNING, GetController(BOOKMARKS)->state()); ASSERT_EQ(DataTypeManager::CONFIGURED, dtm_->state()); @@ -1240,9 +1230,9 @@ SetConfigureStartExpectation(); SetConfigureDoneExpectation(DataTypeManager::OK, DataTypeStatusTable()); - Configure(ModelTypeSet(BOOKMARKS)); + Configure({BOOKMARKS}); FinishDownload(ModelTypeSet(), ModelTypeSet()); // control types - FinishDownload(ModelTypeSet(BOOKMARKS), ModelTypeSet()); + FinishDownload({BOOKMARKS}, ModelTypeSet()); ASSERT_EQ(DataTypeManager::CONFIGURED, dtm_->state()); ASSERT_EQ(DataTypeController::RUNNING, GetController(BOOKMARKS)->state()); @@ -1263,9 +1253,8 @@ SetConfigureDoneExpectation( DataTypeManager::OK, BuildStatusTable(ModelTypeSet(), - /*datatype_errors=*/ModelTypeSet(BOOKMARKS), - ModelTypeSet())); - Configure(ModelTypeSet(BOOKMARKS)); + /*datatype_errors=*/{BOOKMARKS}, ModelTypeSet())); + Configure({BOOKMARKS}); FinishDownload(ModelTypeSet(), ModelTypeSet()); // control types // No need to finish the download of BOOKMARKS since it was never started. EXPECT_EQ(DataTypeManager::CONFIGURED, dtm_->state()); @@ -1302,7 +1291,7 @@ /*datatype_errors=*/{BOOKMARKS}, /*unready_errors=*/{})); FinishDownload(ModelTypeSet(), ModelTypeSet()); // control types - FinishDownload(ModelTypeSet(PREFERENCES), ModelTypeSet()); + FinishDownload({PREFERENCES}, ModelTypeSet()); EXPECT_TRUE(dtm_->GetActiveDataTypes().Has(PREFERENCES)); EXPECT_FALSE(dtm_->GetActiveDataTypes().Has(BOOKMARKS)); @@ -1328,7 +1317,7 @@ SetConfigureStartExpectation(); SetConfigureDoneExpectation(DataTypeManager::OK, DataTypeStatusTable()); - Configure(ModelTypeSet(PRIORITY_PREFERENCES, BOOKMARKS)); + Configure({PRIORITY_PREFERENCES, BOOKMARKS}); EXPECT_EQ(DataTypeManager::CONFIGURING, dtm_->state()); // Both types were downloaded already, so they aren't downloading initial @@ -1352,7 +1341,7 @@ EXPECT_TRUE(last_configure_params().to_download.Empty()); // Finish downloading (configuring, really) priority types. - FinishDownload(ModelTypeSet(PRIORITY_PREFERENCES), ModelTypeSet()); + FinishDownload({PRIORITY_PREFERENCES}, ModelTypeSet()); // This started the configuration of regular types, i.e. BOOKMARKS, which is // already downloaded. ASSERT_EQ(3, configurer_.configure_call_count()); @@ -1363,7 +1352,7 @@ // Finish downloading (configuring, really) regular types. This finishes the // configuration. - FinishDownload(ModelTypeSet(BOOKMARKS), ModelTypeSet()); + FinishDownload({BOOKMARKS}, ModelTypeSet()); ASSERT_EQ(3, configurer_.configure_call_count()); // Not increased. EXPECT_EQ(DataTypeManager::CONFIGURED, dtm_->state()); @@ -1385,7 +1374,7 @@ SetConfigureStartExpectation(); SetConfigureDoneExpectation(DataTypeManager::OK, DataTypeStatusTable()); - Configure(ModelTypeSet(BOOKMARKS)); + Configure({BOOKMARKS}); EXPECT_EQ(DataTypeManager::CONFIGURING, dtm_->state()); // Bookmarks model isn't loaded yet and it is required to complete before // call to configure. Ensure that configure wasn't called. @@ -1398,7 +1387,7 @@ EXPECT_EQ(1, GetController(BOOKMARKS)->activate_call_count()); FinishDownload(ModelTypeSet(), ModelTypeSet()); // control types - FinishDownload(ModelTypeSet(BOOKMARKS), ModelTypeSet()); + FinishDownload({BOOKMARKS}, ModelTypeSet()); EXPECT_EQ(DataTypeManager::CONFIGURED, dtm_->state()); EXPECT_EQ(1U, configurer_.connected_types().Size()); } @@ -1412,8 +1401,8 @@ GetController(PASSWORDS)->model()->EnableManualModelStart(); SetConfigureStartExpectation(); - FailEncryptionFor(ModelTypeSet(BOOKMARKS)); - Configure(ModelTypeSet(BOOKMARKS, PASSWORDS)); + FailEncryptionFor({BOOKMARKS}); + Configure({BOOKMARKS, PASSWORDS}); EXPECT_EQ(DataTypeManager::CONFIGURING, dtm_->state()); EXPECT_EQ(DataTypeController::NOT_RUNNING, GetController(BOOKMARKS)->state()); EXPECT_EQ(DataTypeController::MODEL_STARTING, @@ -1435,7 +1424,7 @@ GetController(BOOKMARKS)->model()->EnableManualModelStart(); GetController(PASSWORDS)->model()->EnableManualModelStart(); SetConfigureStartExpectation(); - Configure(ModelTypeSet(BOOKMARKS, PASSWORDS)); + Configure({BOOKMARKS, PASSWORDS}); EXPECT_EQ(DataTypeController::MODEL_STARTING, GetController(BOOKMARKS)->state()); EXPECT_EQ(DataTypeController::MODEL_STARTING, @@ -1458,7 +1447,7 @@ SetConfigureStartExpectation(); SetConfigureDoneExpectation(DataTypeManager::ABORTED, DataTypeStatusTable()); - Configure(ModelTypeSet(BOOKMARKS)); + Configure({BOOKMARKS}); EXPECT_EQ(DataTypeController::RUNNING, GetController(BOOKMARKS)->state()); dtm_->Stop(SyncStopMetadataFate::CLEAR_METADATA); @@ -1475,11 +1464,11 @@ SetConfigureStartExpectation(); SetConfigureDoneExpectation(DataTypeManager::OK, DataTypeStatusTable()); - Configure(ModelTypeSet(BOOKMARKS, AUTOFILL_WALLET_DATA), SyncMode::kFull); + Configure({BOOKMARKS, AUTOFILL_WALLET_DATA}, SyncMode::kFull); ASSERT_EQ(DataTypeManager::CONFIGURING, dtm_->state()); FinishDownload(ModelTypeSet(), ModelTypeSet()); // control types - FinishDownload(ModelTypeSet(BOOKMARKS, AUTOFILL_WALLET_DATA), ModelTypeSet()); + FinishDownload({BOOKMARKS, AUTOFILL_WALLET_DATA}, ModelTypeSet()); ASSERT_EQ(DataTypeManager::CONFIGURED, dtm_->state()); ASSERT_EQ(2U, configurer_.connected_types().Size()); @@ -1492,11 +1481,11 @@ // Now we restart with a reduced set of data types. SetConfigureStartExpectation(); SetConfigureDoneExpectation(DataTypeManager::OK, DataTypeStatusTable()); - Configure(ModelTypeSet(AUTOFILL_WALLET_DATA), SyncMode::kFull); + Configure({AUTOFILL_WALLET_DATA}, SyncMode::kFull); ASSERT_EQ(DataTypeManager::CONFIGURING, dtm_->state()); FinishDownload(ModelTypeSet(), ModelTypeSet()); // control types - FinishDownload(ModelTypeSet(AUTOFILL_WALLET_DATA), ModelTypeSet()); + FinishDownload({AUTOFILL_WALLET_DATA}, ModelTypeSet()); ASSERT_EQ(DataTypeManager::CONFIGURED, dtm_->state()); ASSERT_EQ(1U, configurer_.connected_types().Size()); @@ -1516,22 +1505,22 @@ SetConfigureStartExpectation(); SetConfigureDoneExpectation(DataTypeManager::OK, DataTypeStatusTable()); - Configure(ModelTypeSet(BOOKMARKS, AUTOFILL_WALLET_DATA), SyncMode::kFull); + Configure({BOOKMARKS, AUTOFILL_WALLET_DATA}, SyncMode::kFull); ASSERT_EQ(DataTypeManager::CONFIGURING, dtm_->state()); FinishDownload(ModelTypeSet(), ModelTypeSet()); // control types - FinishDownload(ModelTypeSet(BOOKMARKS, AUTOFILL_WALLET_DATA), ModelTypeSet()); + FinishDownload({BOOKMARKS, AUTOFILL_WALLET_DATA}, ModelTypeSet()); ASSERT_EQ(DataTypeManager::CONFIGURED, dtm_->state()); ASSERT_EQ(2U, configurer_.connected_types().Size()); // Now we reconfigure with a reduced set of data types. SetConfigureStartExpectation(); SetConfigureDoneExpectation(DataTypeManager::OK, DataTypeStatusTable()); - Configure(ModelTypeSet(AUTOFILL_WALLET_DATA), SyncMode::kFull); + Configure({AUTOFILL_WALLET_DATA}, SyncMode::kFull); ASSERT_EQ(DataTypeManager::CONFIGURING, dtm_->state()); FinishDownload(ModelTypeSet(), ModelTypeSet()); // control types - FinishDownload(ModelTypeSet(AUTOFILL_WALLET_DATA), ModelTypeSet()); + FinishDownload({AUTOFILL_WALLET_DATA}, ModelTypeSet()); ASSERT_EQ(DataTypeManager::CONFIGURED, dtm_->state()); ASSERT_EQ(1U, configurer_.connected_types().Size()); @@ -1550,11 +1539,10 @@ SetConfigureStartExpectation(); SetConfigureDoneExpectation(DataTypeManager::OK, DataTypeStatusTable()); - Configure(ModelTypeSet(BOOKMARKS), SyncMode::kFull, - CONFIGURE_REASON_NEW_CLIENT); + Configure({BOOKMARKS}, SyncMode::kFull, CONFIGURE_REASON_NEW_CLIENT); FinishDownload(ModelTypeSet(), ModelTypeSet()); // control types - FinishDownload(ModelTypeSet(BOOKMARKS), ModelTypeSet()); + FinishDownload({BOOKMARKS}, ModelTypeSet()); histogram_tester.ExpectTotalCount("Sync.ConfigureTime_Initial.OK", 1); } @@ -1567,11 +1555,10 @@ SetConfigureStartExpectation(); SetConfigureDoneExpectation(DataTypeManager::OK, DataTypeStatusTable()); - Configure(ModelTypeSet(BOOKMARKS), SyncMode::kFull, - CONFIGURE_REASON_RECONFIGURATION); + Configure({BOOKMARKS}, SyncMode::kFull, CONFIGURE_REASON_RECONFIGURATION); FinishDownload(ModelTypeSet(), ModelTypeSet()); // control types - FinishDownload(ModelTypeSet(BOOKMARKS), ModelTypeSet()); + FinishDownload({BOOKMARKS}, ModelTypeSet()); histogram_tester.ExpectTotalCount("Sync.ConfigureTime_Subsequent.OK", 1); } @@ -1584,17 +1571,17 @@ // The DataTypeManagerObserver::OnConfigureStart() call may, in some cases, // result in a reentrant call to Configure(). - SetConfigureStartExpectation(base::BindLambdaForTesting( - [&]() { Configure(ModelTypeSet(PREFERENCES)); })); + SetConfigureStartExpectation( + base::BindLambdaForTesting([&]() { Configure({PREFERENCES}); })); - Configure(ModelTypeSet(PREFERENCES, BOOKMARKS)); + Configure({PREFERENCES, BOOKMARKS}); // Implicit expectation: No crash here! // Eventually, the second (reentrant) Configure() call should win, i.e. here // only PREFERENCES gets configured. SetConfigureDoneExpectation(DataTypeManager::OK, DataTypeStatusTable()); FinishDownload(ModelTypeSet(), ModelTypeSet()); // control types - FinishDownload(ModelTypeSet(PREFERENCES), ModelTypeSet()); + FinishDownload({PREFERENCES}, ModelTypeSet()); EXPECT_EQ(DataTypeManager::CONFIGURED, dtm_->state()); EXPECT_EQ(1U, configurer_.connected_types().Size()); } @@ -1613,13 +1600,13 @@ SetConfigureStartExpectation(); SetConfigureDoneExpectation(DataTypeManager::OK, DataTypeStatusTable()); - Configure(ModelTypeSet(PREFERENCES, BOOKMARKS)); + Configure({PREFERENCES, BOOKMARKS}); ASSERT_EQ(DataTypeManager::CONFIGURING, dtm_->state()); // Because Bookmarks are already downloaded, configuration finishes as soon // as preferences are downloaded. FinishDownload(ModelTypeSet(), ModelTypeSet()); // control types - FinishDownload(ModelTypeSet(PREFERENCES), ModelTypeSet()); + FinishDownload({PREFERENCES}, ModelTypeSet()); ASSERT_EQ(DataTypeManager::CONFIGURED, dtm_->state()); } @@ -1634,9 +1621,8 @@ SetConfigureDoneExpectation( DataTypeManager::OK, BuildStatusTable(ModelTypeSet(), - /*datatype_errors=*/ModelTypeSet(BOOKMARKS), - ModelTypeSet())); - Configure(ModelTypeSet(BOOKMARKS)); + /*datatype_errors=*/{BOOKMARKS}, ModelTypeSet())); + Configure({BOOKMARKS}); FinishDownload(ModelTypeSet(), ModelTypeSet()); // control types // No need to finish the download of BOOKMARKS since it was never started. ASSERT_EQ(DataTypeController::FAILED, GetController(BOOKMARKS)->state()); @@ -1658,10 +1644,9 @@ SetConfigureStartExpectation(); SetConfigureDoneExpectation( DataTypeManager::OK, - BuildStatusTable(ModelTypeSet(), ModelTypeSet(BOOKMARKS), - ModelTypeSet())); + BuildStatusTable(ModelTypeSet(), {BOOKMARKS}, ModelTypeSet())); - Configure(ModelTypeSet(BOOKMARKS, PREFERENCES)); + Configure({BOOKMARKS, PREFERENCES}); // BOOKMARKS blocks configuration. EXPECT_TRUE(configurer_.connected_types().Empty()); @@ -1674,19 +1659,19 @@ task_environment_.FastForwardBy(kSyncLoadModelsTimeoutDuration.Get()); // BOOKMARKS is ignored and PREFERENCES is connected. - EXPECT_EQ(configurer_.connected_types(), ModelTypeSet(PREFERENCES)); + EXPECT_EQ(configurer_.connected_types(), ModelTypeSet({PREFERENCES})); EXPECT_EQ(DataTypeController::MODEL_STARTING, GetController(BOOKMARKS)->state()); FinishDownload(ModelTypeSet(), ModelTypeSet()); // control types - FinishDownload(ModelTypeSet(PREFERENCES), ModelTypeSet(BOOKMARKS)); + FinishDownload({PREFERENCES}, {BOOKMARKS}); // BOOKMARKS is skipped and signalled to stop. EXPECT_EQ(DataTypeController::STOPPING, GetController(BOOKMARKS)->state()); // DataTypeManager will be notified for reconfiguration. EXPECT_EQ(DataTypeManager::CONFIGURING, dtm_->state()); FinishDownload(ModelTypeSet(), ModelTypeSet()); // control types - FinishDownload(ModelTypeSet(PREFERENCES), ModelTypeSet()); + FinishDownload({PREFERENCES}, ModelTypeSet()); // DataTypeManager finishes configuration. EXPECT_EQ(DataTypeManager::CONFIGURED, dtm_->state()); }
diff --git a/components/sync/driver/glue/sync_engine_impl_unittest.cc b/components/sync/driver/glue/sync_engine_impl_unittest.cc index a5c007c4..df95651b 100644 --- a/components/sync/driver/glue/sync_engine_impl_unittest.cc +++ b/components/sync/driver/glue/sync_engine_impl_unittest.cc
@@ -387,7 +387,7 @@ ModelTypeSet ready_types = ConfigureDataTypes(); // Nigori is always downloaded so won't be ready. - EXPECT_EQ(Difference(ControlTypes(), ModelTypeSet(NIGORI)), ready_types); + EXPECT_EQ(Difference(ControlTypes(), {NIGORI}), ready_types); EXPECT_TRUE(fake_manager_->GetAndResetDownloadedTypes().HasAll( Difference(enabled_types_, ControlTypes()))); EXPECT_EQ(enabled_types_, fake_manager_->InitialSyncEndedTypes()); @@ -413,12 +413,12 @@ InitializeBackend(); ModelTypeSet ready_types = ConfigureDataTypes(); // Nigori is always downloaded so won't be ready. - EXPECT_EQ(Difference(ControlTypes(), ModelTypeSet(NIGORI)), ready_types); + EXPECT_EQ(Difference(ControlTypes(), {NIGORI}), ready_types); EXPECT_EQ(enabled_types_, fake_manager_->GetAndResetDownloadedTypes()); EXPECT_EQ(enabled_types_, fake_manager_->InitialSyncEndedTypes()); // Then disable two datatypes. - ModelTypeSet disabled_types(BOOKMARKS, SEARCH_ENGINES); + ModelTypeSet disabled_types = {BOOKMARKS, SEARCH_ENGINES}; enabled_types_.RemoveAll(disabled_types); ready_types = ConfigureDataTypes(); @@ -433,12 +433,12 @@ InitializeBackend(); ModelTypeSet ready_types = ConfigureDataTypes(); // Nigori is always downloaded so won't be ready. - EXPECT_EQ(Difference(ControlTypes(), ModelTypeSet(NIGORI)), ready_types); + EXPECT_EQ(Difference(ControlTypes(), {NIGORI}), ready_types); EXPECT_EQ(enabled_types_, fake_manager_->GetAndResetDownloadedTypes()); EXPECT_EQ(enabled_types_, fake_manager_->InitialSyncEndedTypes()); // Then add two datatypes. - ModelTypeSet new_types(EXTENSIONS, APPS); + ModelTypeSet new_types = {EXTENSIONS, APPS}; enabled_types_.PutAll(new_types); ready_types = ConfigureDataTypes(); @@ -456,13 +456,13 @@ InitializeBackend(); ModelTypeSet ready_types = ConfigureDataTypes(); // Nigori is always downloaded so won't be ready. - EXPECT_EQ(Difference(ControlTypes(), ModelTypeSet(NIGORI)), ready_types); + EXPECT_EQ(Difference(ControlTypes(), {NIGORI}), ready_types); EXPECT_EQ(enabled_types_, fake_manager_->GetAndResetDownloadedTypes()); EXPECT_EQ(enabled_types_, fake_manager_->InitialSyncEndedTypes()); // Then add two datatypes. - ModelTypeSet disabled_types(BOOKMARKS, SEARCH_ENGINES); - ModelTypeSet new_types(EXTENSIONS, APPS); + ModelTypeSet disabled_types = {BOOKMARKS, SEARCH_ENGINES}; + ModelTypeSet new_types = {EXTENSIONS, APPS}; enabled_types_.PutAll(new_types); enabled_types_.RemoveAll(disabled_types); ready_types = ConfigureDataTypes(); @@ -482,7 +482,7 @@ ModelTypeSet old_types = enabled_types_; fake_manager_factory_->set_progress_marker_types(old_types); fake_manager_factory_->set_initial_sync_ended_types(old_types); - ModelTypeSet new_types(APP_SETTINGS, EXTENSION_SETTINGS); + ModelTypeSet new_types = {APP_SETTINGS, EXTENSION_SETTINGS}; enabled_types_.PutAll(new_types); // Does nothing. @@ -494,7 +494,7 @@ ModelTypeSet ready_types = ConfigureDataTypes(); new_types.Put(NIGORI); - EXPECT_EQ(Difference(old_types, ModelTypeSet(NIGORI)), ready_types); + EXPECT_EQ(Difference(old_types, {NIGORI}), ready_types); EXPECT_EQ(new_types, fake_manager_->GetAndResetDownloadedTypes()); EXPECT_EQ(enabled_types_, fake_manager_->InitialSyncEndedTypes()); } @@ -505,7 +505,7 @@ // Set sync manager behavior before passing it down. Experiments and device // info are new types without progress markers or initial sync ended, while // all other types have been fully downloaded and applied. - ModelTypeSet new_types(NIGORI); + ModelTypeSet new_types = {NIGORI}; ModelTypeSet old_types = Difference(enabled_types_, new_types); fake_manager_factory_->set_progress_marker_types(old_types); fake_manager_factory_->set_initial_sync_ended_types(old_types); @@ -533,12 +533,12 @@ TEST_F(SyncEngineImplTest, ForwardLocalRefreshRequest) { InitializeBackend(); - ModelTypeSet set1 = ModelTypeSet::All(); + const ModelTypeSet set1 = ModelTypeSet::All(); backend_->TriggerRefresh(set1); fake_manager_->WaitForSyncThread(); EXPECT_EQ(set1, fake_manager_->GetLastRefreshRequestTypes()); - ModelTypeSet set2 = ModelTypeSet(SESSIONS); + const ModelTypeSet set2 = {SESSIONS}; backend_->TriggerRefresh(set2); fake_manager_->WaitForSyncThread(); EXPECT_EQ(set2, fake_manager_->GetLastRefreshRequestTypes()); @@ -565,7 +565,7 @@ // SyncEngine needs to tell the manager to purge the type, even though // it's already disabled (crbug.com/386778). TEST_F(SyncEngineImplTest, DisableThenPurgeType) { - ModelTypeSet error_types(BOOKMARKS); + const ModelTypeSet error_types = {BOOKMARKS}; InitializeBackend(); @@ -573,7 +573,7 @@ ModelTypeSet ready_types = ConfigureDataTypes(); // Nigori is always downloaded so won't be ready. - EXPECT_EQ(Difference(ControlTypes(), ModelTypeSet(NIGORI)), ready_types); + EXPECT_EQ(Difference(ControlTypes(), {NIGORI}), ready_types); // Then mark the error types as unready (disables without purging). ready_types = ConfigureDataTypesWithUnready(error_types);
diff --git a/components/sync/driver/model_load_manager_unittest.cc b/components/sync/driver/model_load_manager_unittest.cc index 5bb0552..e0215cb 100644 --- a/components/sync/driver/model_load_manager_unittest.cc +++ b/components/sync/driver/model_load_manager_unittest.cc
@@ -68,7 +68,7 @@ controllers_[BOOKMARKS] = std::make_unique<FakeDataTypeController>(BOOKMARKS); controllers_[APPS] = std::make_unique<FakeDataTypeController>(APPS); ModelLoadManager model_load_manager(&controllers_, &delegate_); - ModelTypeSet types(BOOKMARKS, APPS); + ModelTypeSet types = {BOOKMARKS, APPS}; EXPECT_CALL(delegate_, OnAllDataTypesReadyForConfigure()); EXPECT_EQ(GetController(BOOKMARKS)->state(), DataTypeController::NOT_RUNNING); @@ -151,7 +151,7 @@ GetController(APPS)->model()->EnableManualModelStart(); ModelLoadManager model_load_manager(&controllers_, &delegate_); - ModelTypeSet types(BOOKMARKS, APPS); + ModelTypeSet types = {BOOKMARKS, APPS}; // OnAllDataTypesReadyForConfigure shouldn't be called, APPS data type is not // loaded yet. EXPECT_CALL(delegate_, OnAllDataTypesReadyForConfigure()).Times(0); @@ -185,7 +185,7 @@ EXPECT_CALL(delegate_, OnAllDataTypesReadyForConfigure()); - ModelTypeSet reduced_types(APPS); + ModelTypeSet reduced_types = {APPS}; model_load_manager.Configure( /*preferred_types_without_errors=*/reduced_types, /*preferred_types=*/reduced_types, BuildConfigureContext()); @@ -203,7 +203,7 @@ GetController(APPS)->model()->EnableManualModelStart(); ModelLoadManager model_load_manager(&controllers_, &delegate_); - ModelTypeSet types(APPS); + ModelTypeSet types = {APPS}; // OnAllDataTypesReadyForConfigure shouldn't be called, APPS data type is not // loaded yet. EXPECT_CALL(delegate_, OnAllDataTypesReadyForConfigure()).Times(0); @@ -236,7 +236,7 @@ GetController(APPS)->model()->EnableManualModelStart(); ModelLoadManager model_load_manager(&controllers_, &delegate_); - ModelTypeSet types(BOOKMARKS, APPS); + ModelTypeSet types = {BOOKMARKS, APPS}; // Apps will finish loading but bookmarks won't. // OnAllDataTypesReadyForConfigure shouldn't be called. @@ -278,7 +278,7 @@ ASSERT_EQ(GetController(BOOKMARKS)->state(), DataTypeController::NOT_RUNNING); - ModelTypeSet types(BOOKMARKS); + ModelTypeSet types = {BOOKMARKS}; // Configure() kicks off model loading. model_load_manager.Configure(/*preferred_types_without_errors=*/types, @@ -303,8 +303,8 @@ // Configure() kicks off model loading. model_load_manager.Configure( - /*preferred_types_without_errors=*/ModelTypeSet(BOOKMARKS), - /*preferred_types=*/ModelTypeSet(BOOKMARKS), BuildConfigureContext()); + /*preferred_types_without_errors=*/{BOOKMARKS}, + /*preferred_types=*/{BOOKMARKS}, BuildConfigureContext()); ASSERT_EQ(GetController(BOOKMARKS)->state(), DataTypeController::MODEL_LOADED); @@ -341,7 +341,7 @@ controllers_[BOOKMARKS] = std::make_unique<FakeDataTypeController>(BOOKMARKS); controllers_[APPS] = std::make_unique<FakeDataTypeController>(APPS); ModelLoadManager model_load_manager(&controllers_, &delegate_); - ModelTypeSet preferred_types(BOOKMARKS, APPS); + ModelTypeSet preferred_types = {BOOKMARKS, APPS}; ModelTypeSet desired_types = preferred_types; EXPECT_CALL(delegate_, OnAllDataTypesReadyForConfigure()); @@ -376,7 +376,7 @@ controllers_[BOOKMARKS] = std::make_unique<FakeDataTypeController>(BOOKMARKS); controllers_[APPS] = std::make_unique<FakeDataTypeController>(APPS); ModelLoadManager model_load_manager(&controllers_, &delegate_); - ModelTypeSet preferred_types(BOOKMARKS, APPS); + ModelTypeSet preferred_types = {BOOKMARKS, APPS}; ModelTypeSet desired_types = preferred_types; EXPECT_CALL(delegate_, OnAllDataTypesReadyForConfigure()); @@ -414,7 +414,7 @@ APPS, /*enable_transport_only_model=*/true); ModelLoadManager model_load_manager(&controllers_, &delegate_); - ModelTypeSet preferred_types(BOOKMARKS, APPS); + ModelTypeSet preferred_types = {BOOKMARKS, APPS}; ConfigureContext configure_context; configure_context.sync_mode = SyncMode::kFull; @@ -464,7 +464,7 @@ APPS, /*enable_transport_only_model=*/true); ModelLoadManager model_load_manager(&controllers_, &delegate_); - ModelTypeSet preferred_types(BOOKMARKS, APPS); + ModelTypeSet preferred_types = {BOOKMARKS, APPS}; ModelTypeSet desired_types = preferred_types; ConfigureContext configure_context; @@ -577,7 +577,7 @@ GetController(BOOKMARKS)->model()->EnableManualModelStart(); ModelLoadManager model_load_manager(&controllers_, &delegate_); - ModelTypeSet preferred_types(APPS, BOOKMARKS); + ModelTypeSet preferred_types = {APPS, BOOKMARKS}; model_load_manager.Configure( /*preferred_types_without_errors=*/preferred_types, preferred_types, @@ -628,7 +628,7 @@ GetController(BOOKMARKS)->model()->EnableManualModelStart(); ModelLoadManager model_load_manager(&controllers_, &delegate_); - ModelTypeSet preferred_types(APPS, BOOKMARKS); + ModelTypeSet preferred_types = {APPS, BOOKMARKS}; ModelTypeSet preferred_types_without_errors = preferred_types; model_load_manager.Configure(preferred_types_without_errors, preferred_types, @@ -668,7 +668,7 @@ EXPECT_CALL(delegate_, OnAllDataTypesReadyForConfigure).Times(0); ModelLoadManager model_load_manager(&controllers_, &delegate_); - ModelTypeSet types(BOOKMARKS, APPS); + ModelTypeSet types = {BOOKMARKS, APPS}; model_load_manager.Configure(/*preferred_types_without_errors=*/types, /*preferred_types=*/types,
diff --git a/components/sync/driver/model_type_controller.cc b/components/sync/driver/model_type_controller.cc index e9024c09..ff6da2b 100644 --- a/components/sync/driver/model_type_controller.cc +++ b/components/sync/driver/model_type_controller.cc
@@ -110,16 +110,40 @@ // OS_PRIORITY_PREFERENCES, WORKSPACE_DESK, PRINTERS_AUTHORIZATION_SERVERS). // // All other data types listed here will likely have to be migrated. - static constexpr ModelTypeSet kLegacyTypes( - BOOKMARKS, PREFERENCES, PASSWORDS, AUTOFILL_PROFILE, AUTOFILL, - AUTOFILL_WALLET_DATA, AUTOFILL_WALLET_METADATA, AUTOFILL_WALLET_OFFER, - AUTOFILL_WALLET_USAGE, THEMES, TYPED_URLS, EXTENSIONS, SEARCH_ENGINES, - SESSIONS, APPS, APP_SETTINGS, EXTENSION_SETTINGS, - HISTORY_DELETE_DIRECTIVES, DICTIONARY, PRIORITY_PREFERENCES, PRINTERS, - READING_LIST, USER_EVENTS, WIFI_CONFIGURATIONS, WEB_APPS, - OS_PREFERENCES, OS_PRIORITY_PREFERENCES, WORKSPACE_DESK, HISTORY, - PRINTERS_AUTHORIZATION_SERVERS, SAVED_TAB_GROUP, POWER_BOOKMARK, - NIGORI); + static constexpr ModelTypeSet kLegacyTypes = { + BOOKMARKS, + PREFERENCES, + PASSWORDS, + AUTOFILL_PROFILE, + AUTOFILL, + AUTOFILL_WALLET_DATA, + AUTOFILL_WALLET_METADATA, + AUTOFILL_WALLET_OFFER, + AUTOFILL_WALLET_USAGE, + THEMES, + TYPED_URLS, + EXTENSIONS, + SEARCH_ENGINES, + SESSIONS, + APPS, + APP_SETTINGS, + EXTENSION_SETTINGS, + HISTORY_DELETE_DIRECTIVES, + DICTIONARY, + PRIORITY_PREFERENCES, + PRINTERS, + READING_LIST, + USER_EVENTS, + WIFI_CONFIGURATIONS, + WEB_APPS, + OS_PREFERENCES, + OS_PRIORITY_PREFERENCES, + WORKSPACE_DESK, + HISTORY, + PRINTERS_AUTHORIZATION_SERVERS, + SAVED_TAB_GROUP, + POWER_BOOKMARK, + NIGORI}; CHECK(kLegacyTypes.Has(type())) << ModelTypeToDebugString(type()) << " must support running in transport mode!";
diff --git a/components/sync/driver/sync_internals_util_unittest.cc b/components/sync/driver/sync_internals_util_unittest.cc index 3ff7e18..8037362d 100644 --- a/components/sync/driver/sync_internals_util_unittest.cc +++ b/components/sync/driver/sync_internals_util_unittest.cc
@@ -17,7 +17,7 @@ TEST(SyncUIUtilTestAbout, ConstructAboutInformationWithUnrecoverableErrorTest) { TestSyncService service; service.SetDisableReasons( - syncer::SyncService::DISABLE_REASON_UNRECOVERABLE_ERROR); + {syncer::SyncService::DISABLE_REASON_UNRECOVERABLE_ERROR}); base::Value::Dict strings = ConstructAboutInformation( IncludeSensitiveData(true), &service, std::string());
diff --git a/components/sync/driver/sync_service_impl_startup_unittest.cc b/components/sync/driver/sync_service_impl_startup_unittest.cc index cbb1788c..d379c6e 100644 --- a/components/sync/driver/sync_service_impl_startup_unittest.cc +++ b/components/sync/driver/sync_service_impl_startup_unittest.cc
@@ -55,9 +55,8 @@ ~SyncServiceImplStartupTest() override { sync_service_->Shutdown(); } - void CreateSyncService( - SyncServiceImpl::StartBehavior start_behavior, - ModelTypeSet registered_types = ModelTypeSet(BOOKMARKS)) { + void CreateSyncService(SyncServiceImpl::StartBehavior start_behavior, + ModelTypeSet registered_types = {BOOKMARKS}) { DataTypeController::TypeVector controllers; for (ModelType type : registered_types) { auto controller = std::make_unique<FakeDataTypeController>(type); @@ -178,8 +177,8 @@ // to be enabled. sync_service()->Initialize(); EXPECT_EQ( - SyncService::DisableReasonSet(SyncService::DISABLE_REASON_NOT_SIGNED_IN, - SyncService::DISABLE_REASON_USER_CHOICE), + SyncService::DisableReasonSet({SyncService::DISABLE_REASON_NOT_SIGNED_IN, + SyncService::DISABLE_REASON_USER_CHOICE}), sync_service()->GetDisableReasons()); EXPECT_EQ(SyncService::TransportState::DISABLED, sync_service()->GetTransportState()); @@ -370,7 +369,7 @@ // get out of this. EXPECT_TRUE(sync_service()->HasUnrecoverableError()); EXPECT_EQ(SyncService::DisableReasonSet( - SyncService::DISABLE_REASON_UNRECOVERABLE_ERROR), + {SyncService::DISABLE_REASON_UNRECOVERABLE_ERROR}), sync_service()->GetDisableReasons()); EXPECT_EQ(SyncService::TransportState::DISABLED, sync_service()->GetTransportState()); @@ -503,8 +502,8 @@ // Sync was disabled due to the policy, setting SyncRequested to false and // causing DISABLE_REASON_USER_CHOICE. EXPECT_EQ(SyncService::DisableReasonSet( - SyncService::DISABLE_REASON_ENTERPRISE_POLICY, - SyncService::DISABLE_REASON_USER_CHOICE), + {SyncService::DISABLE_REASON_ENTERPRISE_POLICY, + SyncService::DISABLE_REASON_USER_CHOICE}), sync_service()->GetDisableReasons()); // Service should not be started by Initialize() since it's managed. EXPECT_EQ(nullptr, data_type_manager()); @@ -556,8 +555,8 @@ // Sync was disabled due to the policy, setting SyncRequested to false and // causing DISABLE_REASON_USER_CHOICE. ASSERT_EQ(SyncService::DisableReasonSet( - SyncService::DISABLE_REASON_ENTERPRISE_POLICY, - SyncService::DISABLE_REASON_USER_CHOICE), + {SyncService::DISABLE_REASON_ENTERPRISE_POLICY, + SyncService::DISABLE_REASON_USER_CHOICE}), sync_service()->GetDisableReasons()); EXPECT_FALSE(sync_service()->IsEngineInitialized()); EXPECT_EQ(SyncService::TransportState::DISABLED, @@ -582,16 +581,16 @@ // It can be resolved by invoking SetSyncFeatureRequested(). #if BUILDFLAG(IS_CHROMEOS_ASH) EXPECT_EQ( - SyncService::DisableReasonSet(SyncService::DISABLE_REASON_USER_CHOICE), + SyncService::DisableReasonSet({SyncService::DISABLE_REASON_USER_CHOICE}), sync_service()->GetDisableReasons()); #else if (GetParam()) { EXPECT_EQ(SyncService::DisableReasonSet(), sync_service()->GetDisableReasons()); } else { - EXPECT_EQ( - SyncService::DisableReasonSet(SyncService::DISABLE_REASON_USER_CHOICE), - sync_service()->GetDisableReasons()); + EXPECT_EQ(SyncService::DisableReasonSet( + {SyncService::DISABLE_REASON_USER_CHOICE}), + sync_service()->GetDisableReasons()); } #endif // BUILDFLAG(IS_CHROMEOS_ASH) @@ -624,7 +623,7 @@ sync_service()->GetSetupInProgressHandle(); sync_blocker.reset(); EXPECT_EQ(SyncService::DisableReasonSet( - SyncService::DISABLE_REASON_UNRECOVERABLE_ERROR), + {SyncService::DISABLE_REASON_UNRECOVERABLE_ERROR}), sync_service()->GetDisableReasons()); EXPECT_EQ(SyncService::TransportState::DISABLED, sync_service()->GetTransportState()); @@ -636,15 +635,15 @@ // We've never completed startup. ASSERT_FALSE(sync_prefs()->IsInitialSyncFeatureSetupComplete()); - CreateSyncService(SyncServiceImpl::MANUAL_START, ModelTypeSet(SESSIONS)); + CreateSyncService(SyncServiceImpl::MANUAL_START, {SESSIONS}); sync_service()->Initialize(); ASSERT_FALSE(sync_service()->CanSyncFeatureStart()); // There is no signed-in user, so also nobody has decided that Sync should be // started. EXPECT_EQ( - SyncService::DisableReasonSet(SyncService::DISABLE_REASON_NOT_SIGNED_IN, - SyncService::DISABLE_REASON_USER_CHOICE), + SyncService::DisableReasonSet({SyncService::DISABLE_REASON_NOT_SIGNED_IN, + SyncService::DISABLE_REASON_USER_CHOICE}), sync_service()->GetDisableReasons()); EXPECT_EQ(SyncService::TransportState::DISABLED, sync_service()->GetTransportState()); @@ -656,7 +655,7 @@ SimulateTestUserSigninWithoutSyncFeature(); base::RunLoop().RunUntilIdle(); EXPECT_EQ( - SyncService::DisableReasonSet(SyncService::DISABLE_REASON_USER_CHOICE), + SyncService::DisableReasonSet({SyncService::DISABLE_REASON_USER_CHOICE}), sync_service()->GetDisableReasons()); EXPECT_EQ(SyncService::TransportState::INITIALIZING, sync_service()->GetTransportState()); @@ -723,7 +722,7 @@ sync_prefs()->SetFirstSetupComplete(); sync_prefs()->SetSyncRequested(true); component_factory()->AllowFakeEngineInitCompletion(false); - CreateSyncService(SyncServiceImpl::MANUAL_START, ModelTypeSet(SESSIONS)); + CreateSyncService(SyncServiceImpl::MANUAL_START, {SESSIONS}); get_controller(SESSIONS)->model()->EnableManualModelStart(); // Kick off.
diff --git a/components/sync/driver/sync_service_impl_unittest.cc b/components/sync/driver/sync_service_impl_unittest.cc index 4f14612..b2d7e67 100644 --- a/components/sync/driver/sync_service_impl_unittest.cc +++ b/components/sync/driver/sync_service_impl_unittest.cc
@@ -346,8 +346,8 @@ // Sync was disabled due to the policy, setting SyncRequested to false and // causing DISABLE_REASON_USER_CHOICE. EXPECT_EQ(SyncService::DisableReasonSet( - SyncService::DISABLE_REASON_ENTERPRISE_POLICY, - SyncService::DISABLE_REASON_USER_CHOICE), + {SyncService::DISABLE_REASON_ENTERPRISE_POLICY, + SyncService::DISABLE_REASON_USER_CHOICE}), service()->GetDisableReasons()); EXPECT_EQ(SyncService::TransportState::DISABLED, service()->GetTransportState()); @@ -387,8 +387,8 @@ // Sync was disabled due to the policy, setting SyncRequested to false and // causing DISABLE_REASON_USER_CHOICE. EXPECT_EQ(SyncService::DisableReasonSet( - SyncService::DISABLE_REASON_ENTERPRISE_POLICY, - SyncService::DISABLE_REASON_USER_CHOICE), + {SyncService::DISABLE_REASON_ENTERPRISE_POLICY, + SyncService::DISABLE_REASON_USER_CHOICE}), service()->GetDisableReasons()); EXPECT_EQ(SyncService::TransportState::DISABLED, service()->GetTransportState()); @@ -415,7 +415,7 @@ // because it is indistinguishable from the sync-reset-via-dashboard case. // It can be resolved by invoking SetSyncFeatureRequested(). EXPECT_EQ( - SyncService::DisableReasonSet(SyncService::DISABLE_REASON_USER_CHOICE), + SyncService::DisableReasonSet({SyncService::DISABLE_REASON_USER_CHOICE}), service()->GetDisableReasons()); service()->SetSyncFeatureRequested(); @@ -458,8 +458,8 @@ // Sync was disabled due to the policy, setting SyncRequested to false and // causing DISABLE_REASON_USER_CHOICE. EXPECT_EQ(SyncService::DisableReasonSet( - SyncService::DISABLE_REASON_ENTERPRISE_POLICY, - SyncService::DISABLE_REASON_USER_CHOICE), + {SyncService::DISABLE_REASON_ENTERPRISE_POLICY, + SyncService::DISABLE_REASON_USER_CHOICE}), service()->GetDisableReasons()); EXPECT_EQ(SyncService::TransportState::DISABLED, service()->GetTransportState()); @@ -504,8 +504,8 @@ base::RunLoop().RunUntilIdle(); EXPECT_EQ( - SyncService::DisableReasonSet(SyncService::DISABLE_REASON_NOT_SIGNED_IN, - SyncService::DISABLE_REASON_USER_CHOICE), + SyncService::DisableReasonSet({SyncService::DISABLE_REASON_NOT_SIGNED_IN, + SyncService::DISABLE_REASON_USER_CHOICE}), service()->GetDisableReasons()); EXPECT_EQ(SyncService::TransportState::DISABLED, service()->GetTransportState()); @@ -537,8 +537,8 @@ base::RunLoop().RunUntilIdle(); // SyncRequested was set to false, causing DISABLE_REASON_USER_CHOICE. EXPECT_EQ( - SyncService::DisableReasonSet(SyncService::DISABLE_REASON_NOT_SIGNED_IN, - SyncService::DISABLE_REASON_USER_CHOICE), + SyncService::DisableReasonSet({SyncService::DISABLE_REASON_NOT_SIGNED_IN, + SyncService::DISABLE_REASON_USER_CHOICE}), service()->GetDisableReasons()); EXPECT_EQ(SyncService::TransportState::DISABLED, service()->GetTransportState()); @@ -568,8 +568,8 @@ EXPECT_FALSE( service()->GetUserSettings()->IsInitialSyncFeatureSetupComplete()); EXPECT_EQ( - SyncService::DisableReasonSet(SyncService::DISABLE_REASON_NOT_SIGNED_IN, - SyncService::DISABLE_REASON_USER_CHOICE), + SyncService::DisableReasonSet({SyncService::DISABLE_REASON_NOT_SIGNED_IN, + SyncService::DISABLE_REASON_USER_CHOICE}), service()->GetDisableReasons()); EXPECT_EQ(1, component_factory()->clear_transport_data_call_count()); #if BUILDFLAG(IS_IOS) @@ -1034,7 +1034,7 @@ EXPECT_TRUE( identity_manager()->HasPrimaryAccount(signin::ConsentLevel::kSync)); EXPECT_EQ( - SyncService::DisableReasonSet(SyncService::DISABLE_REASON_USER_CHOICE), + SyncService::DisableReasonSet({SyncService::DISABLE_REASON_USER_CHOICE}), service()->GetDisableReasons()); // Since ChromeOS doesn't support signout and so the account is still there // and available, Sync will restart in standalone transport mode. @@ -1050,8 +1050,8 @@ identity_manager()->HasPrimaryAccount(signin::ConsentLevel::kSignin)); #endif EXPECT_EQ( - SyncService::DisableReasonSet(SyncService::DISABLE_REASON_NOT_SIGNED_IN, - SyncService::DISABLE_REASON_USER_CHOICE), + SyncService::DisableReasonSet({SyncService::DISABLE_REASON_NOT_SIGNED_IN, + SyncService::DISABLE_REASON_USER_CHOICE}), service()->GetDisableReasons()); EXPECT_EQ(SyncService::TransportState::DISABLED, service()->GetTransportState());
diff --git a/components/sync/driver/sync_service_utils_unittest.cc b/components/sync/driver/sync_service_utils_unittest.cc index a63fba96..9e009e1 100644 --- a/components/sync/driver/sync_service_utils_unittest.cc +++ b/components/sync/driver/sync_service_utils_unittest.cc
@@ -17,7 +17,7 @@ // If sync is not allowed, uploading should never be enabled, even if all the // data types are enabled. service.SetDisableReasons( - syncer::SyncService::DISABLE_REASON_ENTERPRISE_POLICY); + {syncer::SyncService::DISABLE_REASON_ENTERPRISE_POLICY}); service.SetTransportState(syncer::SyncService::TransportState::DISABLED); service.GetUserSettings()->SetSelectedTypes( @@ -100,7 +100,7 @@ syncer::UserSelectableType::kPreferences}); // But one of them fails to actually start up! - service.SetFailedDataTypes(ModelTypeSet(syncer::PREFERENCES)); + service.SetFailedDataTypes({syncer::PREFERENCES}); // Sanity check: Upload is ACTIVE for the model type that did start up. ASSERT_EQ(UploadState::ACTIVE,
diff --git a/components/sync/driver/sync_session_durations_metrics_recorder_unittest.cc b/components/sync/driver/sync_session_durations_metrics_recorder_unittest.cc index db9a341..aab61ec 100644 --- a/components/sync/driver/sync_session_durations_metrics_recorder_unittest.cc +++ b/components/sync/driver/sync_session_durations_metrics_recorder_unittest.cc
@@ -26,7 +26,8 @@ SyncSessionDurationsMetricsRecorderTest() : identity_test_env_(&test_url_loader_factory_) { sync_service_.SetHasSyncConsent(false); - sync_service_.SetDisableReasons(SyncService::DISABLE_REASON_NOT_SIGNED_IN); + sync_service_.SetDisableReasons( + {SyncService::DISABLE_REASON_NOT_SIGNED_IN}); } SyncSessionDurationsMetricsRecorderTest( @@ -160,7 +161,7 @@ TEST_F(SyncSessionDurationsMetricsRecorderTest, OptedInToSync_SyncDisabledByUser) { EnableSync(); - sync_service_.SetDisableReasons(SyncService::DISABLE_REASON_USER_CHOICE); + sync_service_.SetDisableReasons({SyncService::DISABLE_REASON_USER_CHOICE}); base::HistogramTester ht; StartAndEndSession(kSessionTime); @@ -194,7 +195,7 @@ SyncDisabled_PrimaryAccountInAuthError) { EnableSync(); SetInvalidCredentialsAuthError(); - sync_service_.SetDisableReasons(SyncService::DISABLE_REASON_USER_CHOICE); + sync_service_.SetDisableReasons({SyncService::DISABLE_REASON_USER_CHOICE}); base::HistogramTester ht; StartAndEndSession(kSessionTime);
diff --git a/components/sync/driver/sync_user_settings_impl_unittest.cc b/components/sync/driver/sync_user_settings_impl_unittest.cc index 3353559..ac4c2cd 100644 --- a/components/sync/driver/sync_user_settings_impl_unittest.cc +++ b/components/sync/driver/sync_user_settings_impl_unittest.cc
@@ -196,7 +196,7 @@ /*types=*/all_registered_types); EXPECT_TRUE(sync_user_settings->GetPreferredDataTypes().Has(DEVICE_INFO)); - sync_user_settings = MakeSyncUserSettings(ModelTypeSet(DEVICE_INFO)); + sync_user_settings = MakeSyncUserSettings({DEVICE_INFO}); sync_user_settings->SetSelectedTypes( /*sync_everything=*/false, /*types=*/UserSelectableTypeSet()); @@ -221,7 +221,7 @@ /*types=*/all_registered_types); EXPECT_TRUE(sync_user_settings->GetPreferredDataTypes().Has(USER_CONSENTS)); - sync_user_settings = MakeSyncUserSettings(ModelTypeSet(USER_CONSENTS)); + sync_user_settings = MakeSyncUserSettings({USER_CONSENTS}); sync_user_settings->SetSelectedTypes( /*sync_everything=*/false, /*types=*/UserSelectableTypeSet()); @@ -355,8 +355,8 @@ /*types=*/{UserSelectableType::kHistory, UserSelectableType::kTabs}); EXPECT_EQ(GetPreferredUserTypes(*sync_user_settings), Union(AlwaysPreferredUserTypes(), - ModelTypeSet(TYPED_URLS, HISTORY, HISTORY_DELETE_DIRECTIVES, - SESSIONS, PROXY_TABS, USER_EVENTS))); + {TYPED_URLS, HISTORY, HISTORY_DELETE_DIRECTIVES, SESSIONS, + PROXY_TABS, USER_EVENTS})); // History only: PROXY_TABS is gone, but SESSIONS is still enabled since it's // needed for history. @@ -365,17 +365,16 @@ /*types=*/{UserSelectableType::kHistory}); EXPECT_EQ(GetPreferredUserTypes(*sync_user_settings), Union(AlwaysPreferredUserTypes(), - ModelTypeSet(TYPED_URLS, HISTORY, HISTORY_DELETE_DIRECTIVES, - SESSIONS, USER_EVENTS))); + {TYPED_URLS, HISTORY, HISTORY_DELETE_DIRECTIVES, SESSIONS, + USER_EVENTS})); // OpenTabs only: SESSIONS (the actual data) and PROXY_TABS (as a "flag" // indicating OpenTabs is enabled). sync_user_settings->SetSelectedTypes( /*sync_everything=*/false, /*types=*/{UserSelectableType::kTabs}); - EXPECT_EQ( - GetPreferredUserTypes(*sync_user_settings), - Union(AlwaysPreferredUserTypes(), ModelTypeSet(SESSIONS, PROXY_TABS))); + EXPECT_EQ(GetPreferredUserTypes(*sync_user_settings), + Union(AlwaysPreferredUserTypes(), {SESSIONS, PROXY_TABS})); } TEST_F(SyncUserSettingsImplTest, @@ -409,26 +408,25 @@ /*types=*/{UserSelectableType::kHistory, UserSelectableType::kTabs}); EXPECT_EQ(GetPreferredUserTypes(*sync_user_settings), Union(AlwaysPreferredUserTypes(), - ModelTypeSet(TYPED_URLS, HISTORY, HISTORY_DELETE_DIRECTIVES, - SESSIONS, PROXY_TABS, USER_EVENTS))); + {TYPED_URLS, HISTORY, HISTORY_DELETE_DIRECTIVES, SESSIONS, + PROXY_TABS, USER_EVENTS})); // History only: PROXY_TABS and SESSIONS are gone. sync_user_settings->SetSelectedTypes( /*sync_everything=*/false, /*types=*/{UserSelectableType::kHistory}); - EXPECT_EQ(GetPreferredUserTypes(*sync_user_settings), - Union(AlwaysPreferredUserTypes(), - ModelTypeSet(TYPED_URLS, HISTORY, HISTORY_DELETE_DIRECTIVES, - USER_EVENTS))); + EXPECT_EQ( + GetPreferredUserTypes(*sync_user_settings), + Union(AlwaysPreferredUserTypes(), + {TYPED_URLS, HISTORY, HISTORY_DELETE_DIRECTIVES, USER_EVENTS})); // OpenTabs only: SESSIONS (the actual data) and PROXY_TABS (as a "flag" // indicating OpenTabs is enabled). sync_user_settings->SetSelectedTypes( /*sync_everything=*/false, /*types=*/{UserSelectableType::kTabs}); - EXPECT_EQ( - GetPreferredUserTypes(*sync_user_settings), - Union(AlwaysPreferredUserTypes(), ModelTypeSet(SESSIONS, PROXY_TABS))); + EXPECT_EQ(GetPreferredUserTypes(*sync_user_settings), + Union(AlwaysPreferredUserTypes(), {SESSIONS, PROXY_TABS})); } TEST_F(SyncUserSettingsImplTest, ShouldMutePassphrasePrompt) {
diff --git a/components/sync/engine/commit_processor.cc b/components/sync/engine/commit_processor.cc index 547c8ee..5b49a26 100644 --- a/components/sync/engine/commit_processor.cc +++ b/components/sync/engine/commit_processor.cc
@@ -91,7 +91,7 @@ case GatheringPhase::kRegular: return Difference(commit_types_, Union(Union(HighPriorityUserTypes(), LowPriorityUserTypes()), - ModelTypeSet(NIGORI))); + {NIGORI})); case GatheringPhase::kLowPriority: return Intersection(commit_types_, LowPriorityUserTypes()); case GatheringPhase::kDone:
diff --git a/components/sync/engine/commit_processor_unittest.cc b/components/sync/engine/commit_processor_unittest.cc index 0fd30715..0023051 100644 --- a/components/sync/engine/commit_processor_unittest.cc +++ b/components/sync/engine/commit_processor_unittest.cc
@@ -71,8 +71,8 @@ {PREFERENCES, &preference_contributor_}, {HISTORY, &history_contributor_}}, processor_( - /*commit_types=*/ModelTypeSet{NIGORI, SHARING_MESSAGE, BOOKMARKS, - PREFERENCES, HISTORY}, + /*commit_types=*/{NIGORI, SHARING_MESSAGE, BOOKMARKS, PREFERENCES, + HISTORY}, &contributor_map_) { EXPECT_TRUE(HighPriorityUserTypes().Has(SHARING_MESSAGE)); EXPECT_FALSE(HighPriorityUserTypes().Has(BOOKMARKS));
diff --git a/components/sync/engine/cycle/nudge_tracker_unittest.cc b/components/sync/engine/cycle/nudge_tracker_unittest.cc index c078604..36db8ed6 100644 --- a/components/sync/engine/cycle/nudge_tracker_unittest.cc +++ b/components/sync/engine/cycle/nudge_tracker_unittest.cc
@@ -116,7 +116,7 @@ EXPECT_EQ(sync_pb::SyncEnums::GU_TRIGGER, nudge_tracker_.GetOrigin()); // A refresh request will override it. - nudge_tracker_.RecordLocalRefreshRequest(ModelTypeSet(TYPED_URLS)); + nudge_tracker_.RecordLocalRefreshRequest({TYPED_URLS}); EXPECT_EQ(sync_pb::SyncEnums::GU_TRIGGER, nudge_tracker_.GetOrigin()); // Another local nudge will not be enough to change it. @@ -130,7 +130,7 @@ // Neither local nudges nor refresh requests will override it. nudge_tracker_.RecordLocalChange(BOOKMARKS); EXPECT_EQ(sync_pb::SyncEnums::GU_TRIGGER, nudge_tracker_.GetOrigin()); - nudge_tracker_.RecordLocalRefreshRequest(ModelTypeSet(TYPED_URLS)); + nudge_tracker_.RecordLocalRefreshRequest({TYPED_URLS}); EXPECT_EQ(sync_pb::SyncEnums::GU_TRIGGER, nudge_tracker_.GetOrigin()); } @@ -191,7 +191,7 @@ EXPECT_EQ(0, ProtoRefreshRequestedCount(SESSIONS)); // Record a local refresh request. Verify it was registered correctly. - nudge_tracker_.RecordLocalRefreshRequest(ModelTypeSet(SESSIONS)); + nudge_tracker_.RecordLocalRefreshRequest({SESSIONS}); EXPECT_EQ(1, ProtoRefreshRequestedCount(SESSIONS)); // Record a successful sync cycle. Verify the count is cleared. @@ -236,7 +236,7 @@ EXPECT_FALSE(nudge_tracker_.IsSyncRequired(ModelTypeSet::All())); // Refresh requests. - nudge_tracker_.RecordLocalRefreshRequest(ModelTypeSet(SESSIONS)); + nudge_tracker_.RecordLocalRefreshRequest({SESSIONS}); EXPECT_TRUE(nudge_tracker_.IsSyncRequired(ModelTypeSet::All())); nudge_tracker_.RecordSuccessfulSyncCycleIfNotBlocked(ModelTypeSet::All()); EXPECT_FALSE(nudge_tracker_.IsSyncRequired(ModelTypeSet::All())); @@ -273,7 +273,7 @@ EXPECT_FALSE(nudge_tracker_.IsGetUpdatesRequired(ModelTypeSet::All())); // Refresh requests. - nudge_tracker_.RecordLocalRefreshRequest(ModelTypeSet(SESSIONS)); + nudge_tracker_.RecordLocalRefreshRequest({SESSIONS}); EXPECT_TRUE(nudge_tracker_.IsGetUpdatesRequired(ModelTypeSet::All())); nudge_tracker_.RecordSuccessfulSyncCycleIfNotBlocked(ModelTypeSet::All()); EXPECT_FALSE(nudge_tracker_.IsGetUpdatesRequired(ModelTypeSet::All())); @@ -302,13 +302,12 @@ EXPECT_TRUE(nudge_tracker_.IsSyncRequired(ModelTypeSet::All())); // But the throttling of sessions unsets it. - nudge_tracker_.SetTypesThrottledUntil(ModelTypeSet(SESSIONS), throttle_length, - now); + nudge_tracker_.SetTypesThrottledUntil({SESSIONS}, throttle_length, now); EXPECT_TRUE(IsTypeThrottled(SESSIONS)); EXPECT_FALSE(nudge_tracker_.IsSyncRequired(ModelTypeSet::All())); // A refresh request for bookmarks means we have reason to sync again. - nudge_tracker_.RecordLocalRefreshRequest(ModelTypeSet(BOOKMARKS)); + nudge_tracker_.RecordLocalRefreshRequest({BOOKMARKS}); EXPECT_TRUE(nudge_tracker_.IsSyncRequired(ModelTypeSet::All())); // But the backoff of bookmarks unsets it. @@ -318,7 +317,7 @@ EXPECT_FALSE(nudge_tracker_.IsSyncRequired(ModelTypeSet::All())); // A refresh request for preferences means we have reason to sync again. - nudge_tracker_.RecordLocalRefreshRequest(ModelTypeSet(PREFERENCES)); + nudge_tracker_.RecordLocalRefreshRequest({PREFERENCES}); EXPECT_TRUE(nudge_tracker_.IsSyncRequired(ModelTypeSet::All())); // A successful sync cycle means we took care of preferences. @@ -343,16 +342,15 @@ EXPECT_FALSE(nudge_tracker_.IsGetUpdatesRequired(ModelTypeSet::All())); // A refresh request to sessions enables the flag. - nudge_tracker_.RecordLocalRefreshRequest(ModelTypeSet(SESSIONS)); + nudge_tracker_.RecordLocalRefreshRequest({SESSIONS}); EXPECT_TRUE(nudge_tracker_.IsGetUpdatesRequired(ModelTypeSet::All())); // But the throttling of sessions unsets it. - nudge_tracker_.SetTypesThrottledUntil(ModelTypeSet(SESSIONS), throttle_length, - now); + nudge_tracker_.SetTypesThrottledUntil({SESSIONS}, throttle_length, now); EXPECT_FALSE(nudge_tracker_.IsGetUpdatesRequired(ModelTypeSet::All())); // A refresh request for bookmarks means we have reason to sync again. - nudge_tracker_.RecordLocalRefreshRequest(ModelTypeSet(BOOKMARKS)); + nudge_tracker_.RecordLocalRefreshRequest({BOOKMARKS}); EXPECT_TRUE(nudge_tracker_.IsGetUpdatesRequired(ModelTypeSet::All())); // But the backoff of bookmarks unsets it. @@ -362,7 +360,7 @@ EXPECT_FALSE(nudge_tracker_.IsGetUpdatesRequired(ModelTypeSet::All())); // A refresh request for preferences means we have reason to sync again. - nudge_tracker_.RecordLocalRefreshRequest(ModelTypeSet(PREFERENCES)); + nudge_tracker_.RecordLocalRefreshRequest({PREFERENCES}); EXPECT_TRUE(nudge_tracker_.IsGetUpdatesRequired(ModelTypeSet::All())); // A successful sync cycle means we took care of preferences. @@ -390,7 +388,7 @@ const base::TimeTicks now = base::TimeTicks::Now(); const base::TimeDelta throttle_length = base::Minutes(0); - nudge_tracker_.SetTypesThrottledUntil(ModelTypeSet(SESSIONS, PREFERENCES), + nudge_tracker_.SetTypesThrottledUntil({SESSIONS, PREFERENCES}, throttle_length, now); EXPECT_TRUE(nudge_tracker_.IsAnyTypeBlocked()); @@ -433,18 +431,18 @@ const base::TimeDelta throttle2_length = base::Minutes(20); // Setup the longer of two intervals. - nudge_tracker_.SetTypesThrottledUntil(ModelTypeSet(SESSIONS, PREFERENCES), + nudge_tracker_.SetTypesThrottledUntil({SESSIONS, PREFERENCES}, throttle2_length, now); - EXPECT_TRUE(ModelTypeSetEquals(ModelTypeSet(SESSIONS, PREFERENCES), + EXPECT_TRUE(ModelTypeSetEquals({SESSIONS, PREFERENCES}, nudge_tracker_.GetBlockedTypes())); EXPECT_TRUE(IsTypeThrottled(SESSIONS)); EXPECT_TRUE(IsTypeThrottled(PREFERENCES)); EXPECT_GE(throttle2_length, nudge_tracker_.GetTimeUntilNextUnblock()); // Setup the shorter interval. - nudge_tracker_.SetTypesThrottledUntil(ModelTypeSet(SESSIONS, BOOKMARKS), - throttle1_length, now); - EXPECT_TRUE(ModelTypeSetEquals(ModelTypeSet(SESSIONS, PREFERENCES, BOOKMARKS), + nudge_tracker_.SetTypesThrottledUntil({SESSIONS, BOOKMARKS}, throttle1_length, + now); + EXPECT_TRUE(ModelTypeSetEquals({SESSIONS, PREFERENCES, BOOKMARKS}, nudge_tracker_.GetBlockedTypes())); EXPECT_TRUE(IsTypeThrottled(SESSIONS)); EXPECT_TRUE(IsTypeThrottled(PREFERENCES)); @@ -456,7 +454,7 @@ // SESSIONS appeared in both intervals. We expect it will be throttled for // the longer of the two, so it's still throttled at time t1. - EXPECT_TRUE(ModelTypeSetEquals(ModelTypeSet(SESSIONS, PREFERENCES), + EXPECT_TRUE(ModelTypeSetEquals({SESSIONS, PREFERENCES}, nudge_tracker_.GetBlockedTypes())); EXPECT_TRUE(IsTypeThrottled(SESSIONS)); EXPECT_TRUE(IsTypeThrottled(PREFERENCES)); @@ -473,7 +471,7 @@ // Setup the longer of two intervals. nudge_tracker_.SetTypeBackedOff(SESSIONS, backoff2_length, now); nudge_tracker_.SetTypeBackedOff(PREFERENCES, backoff2_length, now); - EXPECT_TRUE(ModelTypeSetEquals(ModelTypeSet(SESSIONS, PREFERENCES), + EXPECT_TRUE(ModelTypeSetEquals({SESSIONS, PREFERENCES}, nudge_tracker_.GetBlockedTypes())); EXPECT_TRUE(IsTypeBackedOff(SESSIONS)); EXPECT_TRUE(IsTypeBackedOff(PREFERENCES)); @@ -482,7 +480,7 @@ // Setup the shorter interval. nudge_tracker_.SetTypeBackedOff(SESSIONS, backoff1_length, now); nudge_tracker_.SetTypeBackedOff(BOOKMARKS, backoff1_length, now); - EXPECT_TRUE(ModelTypeSetEquals(ModelTypeSet(SESSIONS, PREFERENCES, BOOKMARKS), + EXPECT_TRUE(ModelTypeSetEquals({SESSIONS, PREFERENCES, BOOKMARKS}, nudge_tracker_.GetBlockedTypes())); EXPECT_TRUE(IsTypeBackedOff(SESSIONS)); EXPECT_TRUE(IsTypeBackedOff(PREFERENCES)); @@ -494,7 +492,7 @@ // SESSIONS appeared in both intervals. We expect it will be backed off for // the longer of the two, so it's still backed off at time t1. - EXPECT_TRUE(ModelTypeSetEquals(ModelTypeSet(SESSIONS, PREFERENCES), + EXPECT_TRUE(ModelTypeSetEquals({SESSIONS, PREFERENCES}, nudge_tracker_.GetBlockedTypes())); EXPECT_TRUE(IsTypeBackedOff(SESSIONS)); EXPECT_TRUE(IsTypeBackedOff(PREFERENCES));
diff --git a/components/sync/engine/get_updates_processor_unittest.cc b/components/sync/engine/get_updates_processor_unittest.cc index a064b98..9cd18ad 100644 --- a/components/sync/engine/get_updates_processor_unittest.cc +++ b/components/sync/engine/get_updates_processor_unittest.cc
@@ -220,7 +220,7 @@ nudge_tracker.RecordInitialSyncRequired(AUTOFILL); nudge_tracker.RecordInitialSyncRequired(PREFERENCES); - ModelTypeSet initial_sync_types = ModelTypeSet(AUTOFILL, PREFERENCES); + const ModelTypeSet initial_sync_types = {AUTOFILL, PREFERENCES}; sync_pb::ClientToServerMessage message; NormalGetUpdatesDelegate normal_delegate(nudge_tracker); @@ -417,7 +417,7 @@ autofill_handler_ = AddUpdateHandler(AUTOFILL); } - ModelTypeSet GetGuTypes() { return ModelTypeSet(AUTOFILL); } + ModelTypeSet GetGuTypes() { return {AUTOFILL}; } MockUpdateHandler* GetNonAppliedHandler() { return bookmarks_handler_; }
diff --git a/components/sync/engine/loopback_server/loopback_server.cc b/components/sync/engine/loopback_server/loopback_server.cc index afd74635..1a228e4b 100644 --- a/components/sync/engine/loopback_server/loopback_server.cc +++ b/components/sync/engine/loopback_server/loopback_server.cc
@@ -296,8 +296,8 @@ bool LoopbackServer::CreateDefaultPermanentItems() { // Permanent folders are always required for Bookmarks (hierarchical // structure) and Nigori (data stored in permanent root folder). - ModelTypeSet permanent_folder_types = - ModelTypeSet(syncer::BOOKMARKS, syncer::NIGORI); + const ModelTypeSet permanent_folder_types = {syncer::BOOKMARKS, + syncer::NIGORI}; for (ModelType model_type : permanent_folder_types) { std::unique_ptr<LoopbackServerEntity> top_level_entity =
diff --git a/components/sync/engine/model_type_registry_unittest.cc b/components/sync/engine/model_type_registry_unittest.cc index 4a3250f..5004869 100644 --- a/components/sync/engine/model_type_registry_unittest.cc +++ b/components/sync/engine/model_type_registry_unittest.cc
@@ -63,15 +63,15 @@ registry()->ConnectDataType(THEMES, MakeDataTypeActivationResponse( MakeInitialModelTypeState(THEMES))); - EXPECT_EQ(ModelTypeSet(THEMES), registry()->GetConnectedTypes()); + EXPECT_EQ(ModelTypeSet({THEMES}), registry()->GetConnectedTypes()); registry()->ConnectDataType( SESSIONS, MakeDataTypeActivationResponse(MakeInitialModelTypeState(SESSIONS))); - EXPECT_EQ(ModelTypeSet(THEMES, SESSIONS), registry()->GetConnectedTypes()); + EXPECT_EQ(ModelTypeSet({THEMES, SESSIONS}), registry()->GetConnectedTypes()); registry()->DisconnectDataType(THEMES); - EXPECT_EQ(ModelTypeSet(SESSIONS), registry()->GetConnectedTypes()); + EXPECT_EQ(ModelTypeSet({SESSIONS}), registry()->GetConnectedTypes()); // Allow ModelTypeRegistry destruction to delete the // Sessions' ModelTypeSyncWorker. @@ -91,7 +91,7 @@ SESSIONS, MakeDataTypeActivationResponse(MakeInitialModelTypeState(SESSIONS))); - EXPECT_EQ(ModelTypeSet(THEMES), registry()->GetInitialSyncEndedTypes()); + EXPECT_EQ(ModelTypeSet({THEMES}), registry()->GetInitialSyncEndedTypes()); } } // namespace
diff --git a/components/sync/engine/model_type_worker_unittest.cc b/components/sync/engine/model_type_worker_unittest.cc index 9a30065..8ce984ce 100644 --- a/components/sync/engine/model_type_worker_unittest.cc +++ b/components/sync/engine/model_type_worker_unittest.cc
@@ -726,7 +726,7 @@ TriggerUpdateFromServer(10, kTag1, kValue1); EXPECT_EQ(status_controller()->get_updated_types(), - ModelTypeSet{worker()->GetModelType()}); + ModelTypeSet({worker()->GetModelType()})); ASSERT_EQ(1U, processor()->GetNumUpdateResponses()); std::vector<const UpdateResponseData*> updates_list =
diff --git a/components/sync/engine/sync_manager_impl_unittest.cc b/components/sync/engine/sync_manager_impl_unittest.cc index 6170067..08e48df 100644 --- a/components/sync/engine/sync_manager_impl_unittest.cc +++ b/components/sync/engine/sync_manager_impl_unittest.cc
@@ -225,7 +225,7 @@ // Test that the configuration params are properly created and sent to // ScheduleConfigure. No callback should be invoked. TEST_F(SyncManagerImplTest, BasicConfiguration) { - ModelTypeSet types_to_download(BOOKMARKS, PREFERENCES); + const ModelTypeSet types_to_download = {BOOKMARKS, PREFERENCES}; base::MockOnceClosure ready_task; EXPECT_CALL(*scheduler(), Start(SyncScheduler::CONFIGURATION_MODE, _)); EXPECT_CALL(*scheduler(),
diff --git a/components/sync/engine/sync_scheduler_impl_unittest.cc b/components/sync/engine/sync_scheduler_impl_unittest.cc index 80dbabb2..1e86540 100644 --- a/components/sync/engine/sync_scheduler_impl_unittest.cc +++ b/components/sync/engine/sync_scheduler_impl_unittest.cc
@@ -78,14 +78,14 @@ SyncCycle* cycle = arg0; cycle->mutable_status_controller()->set_commit_result( SyncerError(SyncerError::SYNCER_OK)); - cycle->delegate()->OnTypesThrottled(ModelTypeSet(type), throttle); + cycle->delegate()->OnTypesThrottled({type}, throttle); } ACTION_P(SimulatePartialFailure, type) { SyncCycle* cycle = arg0; cycle->mutable_status_controller()->set_commit_result( SyncerError(SyncerError::SYNCER_OK)); - cycle->delegate()->OnTypesBackedOff(ModelTypeSet(type)); + cycle->delegate()->OnTypesBackedOff({type}); } ACTION_P(SimulatePollIntervalUpdate, new_poll) { @@ -553,7 +553,7 @@ base::MockOnceClosure ready_task; EXPECT_CALL(ready_task, Run).Times(1); scheduler()->ScheduleConfiguration(sync_pb::SyncEnums::RECONFIGURATION, - ModelTypeSet(THEMES), ready_task.Get()); + {THEMES}, ready_task.Get()); PumpLoop(); } @@ -575,7 +575,7 @@ base::MockOnceClosure ready_task; EXPECT_CALL(ready_task, Run).Times(1); scheduler()->ScheduleConfiguration(sync_pb::SyncEnums::RECONFIGURATION, - ModelTypeSet(THEMES), ready_task.Get()); + {THEMES}, ready_task.Get()); RunLoop(); // RunLoop() will trigger TryCanaryJob which will retry configuration. @@ -610,7 +610,7 @@ base::MockOnceClosure ready_task; EXPECT_CALL(ready_task, Run).Times(0); scheduler()->ScheduleConfiguration(sync_pb::SyncEnums::RECONFIGURATION, - ModelTypeSet(THEMES), ready_task.Get()); + {THEMES}, ready_task.Get()); PumpLoop(); } @@ -623,7 +623,7 @@ base::MockOnceClosure ready_task; EXPECT_CALL(ready_task, Run).Times(0); scheduler()->ScheduleConfiguration(sync_pb::SyncEnums::RECONFIGURATION, - ModelTypeSet(THEMES), ready_task.Get()); + {THEMES}, ready_task.Get()); PumpLoop(); } @@ -643,7 +643,7 @@ base::MockOnceClosure ready_task; EXPECT_CALL(ready_task, Run).Times(1); scheduler()->ScheduleConfiguration(sync_pb::SyncEnums::RECONFIGURATION, - ModelTypeSet(THEMES), ready_task.Get()); + {THEMES}, ready_task.Get()); PumpLoop(); } @@ -665,8 +665,7 @@ EXPECT_CALL(ready_task, Run).Times(0); const ModelType model_type = THEMES; scheduler()->ScheduleConfiguration(sync_pb::SyncEnums::RECONFIGURATION, - ModelTypeSet(model_type), - ready_task.Get()); + {model_type}, ready_task.Get()); RunLoop(); Mock::VerifyAndClearExpectations(syncer()); Mock::VerifyAndClearExpectations(&ready_task); @@ -935,7 +934,7 @@ base::MockOnceClosure ready_task; EXPECT_CALL(ready_task, Run).Times(0); scheduler()->ScheduleConfiguration(sync_pb::SyncEnums::RECONFIGURATION, - ModelTypeSet(type), ready_task.Get()); + {type}, ready_task.Get()); PumpLoop(); } @@ -1005,7 +1004,7 @@ base::MockOnceClosure ready_task; EXPECT_CALL(ready_task, Run).Times(0); scheduler()->ScheduleConfiguration(sync_pb::SyncEnums::RECONFIGURATION, - ModelTypeSet(THEMES), ready_task.Get()); + {THEMES}, ready_task.Get()); PumpLoop(); Mock::VerifyAndClearExpectations(&ready_task); EXPECT_TRUE(scheduler()->IsGlobalThrottle()); @@ -1239,7 +1238,7 @@ PumpLoop(); // Ignore refresh requests for throttled types. - scheduler()->ScheduleLocalRefreshRequest(ModelTypeSet(throttled_type)); + scheduler()->ScheduleLocalRefreshRequest({throttled_type}); PumpLoop(); Mock::VerifyAndClearExpectations(syncer()); @@ -1284,7 +1283,7 @@ PumpLoop(); // Ignore refresh requests for backed off types. - scheduler()->ScheduleLocalRefreshRequest(ModelTypeSet(backed_off_type)); + scheduler()->ScheduleLocalRefreshRequest({backed_off_type}); PumpLoop(); Mock::VerifyAndClearExpectations(syncer()); @@ -1318,7 +1317,7 @@ base::MockOnceClosure ready_task; EXPECT_CALL(ready_task, Run).Times(1); scheduler()->ScheduleConfiguration(sync_pb::SyncEnums::RECONFIGURATION, - ModelTypeSet(THEMES), ready_task.Get()); + {THEMES}, ready_task.Get()); RunLoop(); Mock::VerifyAndClearExpectations(syncer()); @@ -1398,7 +1397,7 @@ base::MockOnceClosure ready_task; EXPECT_CALL(ready_task, Run).Times(0); scheduler()->ScheduleConfiguration(sync_pb::SyncEnums::RECONFIGURATION, - ModelTypeSet(THEMES), ready_task.Get()); + {THEMES}, ready_task.Get()); RunLoop(); EXPECT_TRUE(scheduler()->IsGlobalBackoff()); @@ -1443,7 +1442,7 @@ base::MockOnceClosure ready_task; EXPECT_CALL(ready_task, Run).Times(0); scheduler()->ScheduleConfiguration(sync_pb::SyncEnums::RECONFIGURATION, - ModelTypeSet(type), ready_task.Get()); + {type}, ready_task.Get()); PumpLoop(); } @@ -1685,7 +1684,7 @@ connection()->UpdateConnectionStatus(); scheduler()->ScheduleConfiguration(sync_pb::SyncEnums::RECONFIGURATION, - ModelTypeSet(THEMES), base::DoNothing()); + {THEMES}, base::DoNothing()); scheduler()->OnConnectionStatusChange( network::mojom::ConnectionType::CONNECTION_WIFI);
diff --git a/components/sync/engine/syncer_proto_util_unittest.cc b/components/sync/engine/syncer_proto_util_unittest.cc index 543de62..074fa18 100644 --- a/components/sync/engine/syncer_proto_util_unittest.cc +++ b/components/sync/engine/syncer_proto_util_unittest.cc
@@ -77,7 +77,7 @@ response.add_migrated_data_type_id( GetSpecificsFieldNumberFromModelType(HISTORY_DELETE_DIRECTIVES)); response.add_migrated_data_type_id(-1); - EXPECT_EQ(ModelTypeSet(BOOKMARKS, HISTORY_DELETE_DIRECTIVES), + EXPECT_EQ(ModelTypeSet({BOOKMARKS, HISTORY_DELETE_DIRECTIVES}), GetTypesToMigrate(response)); } @@ -93,7 +93,7 @@ GetSpecificsFieldNumberFromModelType(HISTORY_DELETE_DIRECTIVES)); error_pb.add_error_data_type_ids(-1); SyncProtocolError error = ConvertErrorPBToSyncProtocolError(error_pb); - EXPECT_EQ(ModelTypeSet(BOOKMARKS, HISTORY_DELETE_DIRECTIVES), + EXPECT_EQ(ModelTypeSet({BOOKMARKS, HISTORY_DELETE_DIRECTIVES}), error.error_data_types); }
diff --git a/components/sync/engine/syncer_unittest.cc b/components/sync/engine/syncer_unittest.cc index 373f2bf..c131176 100644 --- a/components/sync/engine/syncer_unittest.cc +++ b/components/sync/engine/syncer_unittest.cc
@@ -270,7 +270,7 @@ }; TEST_F(SyncerTest, CommitFiltersThrottledEntries) { - const ModelTypeSet throttled_types(BOOKMARKS); + const ModelTypeSet throttled_types = {BOOKMARKS}; GetProcessor(BOOKMARKS)->AppendCommitRequest( ClientTagHash::FromHashed("tag1"), MakeBookmarkSpecificsToCommit(), @@ -315,7 +315,7 @@ // Set BOOKMARKS throttled but PREFERENCES not, // then BOOKMARKS should not get synced but PREFERENCES should. - ModelTypeSet throttled_types(BOOKMARKS); + ModelTypeSet throttled_types = {BOOKMARKS}; mock_server_->set_throttling(true); mock_server_->SetPartialFailureTypes(throttled_types); @@ -370,7 +370,7 @@ // Set BOOKMARKS failure but PREFERENCES not, // then BOOKMARKS should not get synced but PREFERENCES should. - ModelTypeSet failed_types(BOOKMARKS); + ModelTypeSet failed_types = {BOOKMARKS}; mock_server_->set_partial_failure(true); mock_server_->SetPartialFailureTypes(failed_types); @@ -1131,7 +1131,7 @@ TEST_F(SyncerTest, ConfigureFailedUnregisteredType) { // Simulate type being unregistered before configuration by including type // that isn't registered with ModelTypeRegistry. - SyncShareConfigureTypes(ModelTypeSet(APPS)); + SyncShareConfigureTypes({APPS}); // No explicit verification, DCHECK shouldn't have been triggered. } @@ -1164,7 +1164,7 @@ // are correctly removed before commit. TEST_F(SyncerTest, CommitOnlyTypes) { mock_server_->set_partial_failure(true); - mock_server_->SetPartialFailureTypes(ModelTypeSet(PREFERENCES)); + mock_server_->SetPartialFailureTypes({PREFERENCES}); EnableDatatype(USER_EVENTS);
diff --git a/components/sync/invalidations/sync_invalidations_service_impl_unittest.cc b/components/sync/invalidations/sync_invalidations_service_impl_unittest.cc index 9ba7ab40..ca82c6f5 100644 --- a/components/sync/invalidations/sync_invalidations_service_impl_unittest.cc +++ b/components/sync/invalidations/sync_invalidations_service_impl_unittest.cc
@@ -45,19 +45,19 @@ TEST_F(SyncInvalidationsServiceImplTest, ShouldReturnGivenDataTypes) { sync_invalidations_service_impl_.SetInterestedDataTypes( - ModelTypeSet(BOOKMARKS, PREFERENCES)); - EXPECT_EQ(ModelTypeSet(BOOKMARKS, PREFERENCES), + {BOOKMARKS, PREFERENCES}); + EXPECT_EQ(ModelTypeSet({BOOKMARKS, PREFERENCES}), sync_invalidations_service_impl_.GetInterestedDataTypes()); sync_invalidations_service_impl_.SetInterestedDataTypes( - ModelTypeSet(PREFERENCES, PASSWORDS)); - EXPECT_EQ(ModelTypeSet(PREFERENCES, PASSWORDS), + {PREFERENCES, PASSWORDS}); + EXPECT_EQ(ModelTypeSet({PREFERENCES, PASSWORDS}), sync_invalidations_service_impl_.GetInterestedDataTypes()); } TEST_F(SyncInvalidationsServiceImplTest, ShouldNotifyOnChange) { EXPECT_CALL(handler_, OnInterestedDataTypesChanged); sync_invalidations_service_impl_.SetInterestedDataTypes( - ModelTypeSet(PASSWORDS, AUTOFILL)); + {PASSWORDS, AUTOFILL}); } TEST_F(SyncInvalidationsServiceImplTest, @@ -65,11 +65,11 @@ EXPECT_FALSE( sync_invalidations_service_impl_.GetInterestedDataTypes().has_value()); sync_invalidations_service_impl_.SetInterestedDataTypes( - ModelTypeSet(BOOKMARKS, PREFERENCES)); + {BOOKMARKS, PREFERENCES}); EXPECT_TRUE( sync_invalidations_service_impl_.GetInterestedDataTypes().has_value()); sync_invalidations_service_impl_.SetInterestedDataTypes( - ModelTypeSet(BOOKMARKS, PREFERENCES, NIGORI)); + {BOOKMARKS, PREFERENCES, NIGORI}); EXPECT_TRUE( sync_invalidations_service_impl_.GetInterestedDataTypes().has_value()); }
diff --git a/components/sync/test/fake_sync_service.cc b/components/sync/test/fake_sync_service.cc index 27bddef..e4fa55cb2 100644 --- a/components/sync/test/fake_sync_service.cc +++ b/components/sync/test/fake_sync_service.cc
@@ -32,7 +32,7 @@ syncer::SyncService::DisableReasonSet FakeSyncService::GetDisableReasons() const { - return DISABLE_REASON_NOT_SIGNED_IN; + return {DISABLE_REASON_NOT_SIGNED_IN}; } syncer::SyncService::TransportState FakeSyncService::GetTransportState() const {
diff --git a/components/sync/test/test_sync_user_settings.cc b/components/sync/test/test_sync_user_settings.cc index daf4093..9e10c90 100644 --- a/components/sync/test/test_sync_user_settings.cc +++ b/components/sync/test/test_sync_user_settings.cc
@@ -167,7 +167,7 @@ ModelTypeSet TestSyncUserSettings::GetEncryptedDataTypes() const { if (!IsUsingExplicitPassphrase()) { // PASSWORDS and WIFI_CONFIGURATIONS are always encrypted. - return ModelTypeSet(PASSWORDS, WIFI_CONFIGURATIONS); + return {PASSWORDS, WIFI_CONFIGURATIONS}; } // Some types can never be encrypted, e.g. DEVICE_INFO and // AUTOFILL_WALLET_DATA, so make sure we don't report them as encrypted.
diff --git a/components/sync_device_info/device_info_sync_bridge_unittest.cc b/components/sync_device_info/device_info_sync_bridge_unittest.cc index 4cafffe..92439477 100644 --- a/components/sync_device_info/device_info_sync_bridge_unittest.cc +++ b/components/sync_device_info/device_info_sync_bridge_unittest.cc
@@ -263,7 +263,7 @@ } ModelTypeSet SyncInvalidationsInterestedDataTypes() { - return ModelTypeSet(BOOKMARKS); + return {BOOKMARKS}; } DataTypeActivationRequest TestDataTypeActivationRequest(SyncMode sync_mode) { @@ -1480,7 +1480,7 @@ const std::string guid = local_device()->GetLocalDeviceInfo()->guid(); EXPECT_CALL(*processor(), IsEntityUnsynced(guid)).WillOnce(Return(false)); - EXPECT_CALL(callback, Run(ModelTypeSet(syncer::SESSIONS))); + EXPECT_CALL(callback, Run(ModelTypeSet({syncer::SESSIONS}))); bridge()->ApplyIncrementalSyncChanges(bridge()->CreateMetadataChangeList(), EntityChangeList()); }
diff --git a/components/sync_device_info/local_device_info_provider_impl_unittest.cc b/components/sync_device_info/local_device_info_provider_impl_unittest.cc index d1abfd3..6d1dbf6 100644 --- a/components/sync_device_info/local_device_info_provider_impl_unittest.cc +++ b/components/sync_device_info/local_device_info_provider_impl_unittest.cc
@@ -255,7 +255,7 @@ ASSERT_THAT(provider_->GetLocalDeviceInfo(), NotNull()); EXPECT_TRUE(provider_->GetLocalDeviceInfo()->interested_data_types().Empty()); - const ModelTypeSet kTypes = ModelTypeSet(BOOKMARKS); + const ModelTypeSet kTypes = {BOOKMARKS}; EXPECT_CALL(device_info_sync_client_, GetInterestedDataTypes()) .WillRepeatedly(Return(kTypes)); @@ -264,7 +264,7 @@ TEST_F(LocalDeviceInfoProviderImplTest, ShouldKeepStoredInvalidationFields) { const std::string kFCMRegistrationToken = "fcm_token"; - const ModelTypeSet kInterestedDataTypes(BOOKMARKS); + const ModelTypeSet kInterestedDataTypes = {BOOKMARKS}; DeviceInfo::PhoneAsASecurityKeyInfo paask_info = SamplePhoneAsASecurityKeyInfo();
diff --git a/components/translate/ios/browser/js_translate_web_frame_manager.mm b/components/translate/ios/browser/js_translate_web_frame_manager.mm index 7598a9b..9797d5a 100644 --- a/components/translate/ios/browser/js_translate_web_frame_manager.mm +++ b/components/translate/ios/browser/js_translate_web_frame_manager.mm
@@ -6,9 +6,9 @@ #import <Foundation/Foundation.h> +#include "base/apple/bundle_locations.h" #include "base/check.h" #import "base/logging.h" -#include "base/mac/bundle_locations.h" #include "base/strings/stringprintf.h" #import "base/strings/sys_string_conversions.h" #import "base/strings/utf_string_conversions.h" @@ -25,8 +25,8 @@ NSString* GetPageScript(NSString* script_file_name) { DCHECK(script_file_name); NSString* path = - [base::mac::FrameworkBundle() pathForResource:script_file_name - ofType:@"js"]; + [base::apple::FrameworkBundle() pathForResource:script_file_name + ofType:@"js"]; DCHECK(path) << "Script file not found: " << base::SysNSStringToUTF8(script_file_name) << ".js"; NSError* error = nil;
diff --git a/components/viz/service/display/resolved_frame_data.cc b/components/viz/service/display/resolved_frame_data.cc index 12ad7cf..cc45d1ee 100644 --- a/components/viz/service/display/resolved_frame_data.cc +++ b/components/viz/service/display/resolved_frame_data.cc
@@ -262,17 +262,6 @@ DCHECK(valid_); DCHECK(used_in_aggregation_); - // The |damage_rect| set in |SurfaceAnimationManager| is the |output_rect|. - // However, we dont use |damage_rect| because when we transition from - // interpolated frame we would end up using the |damage_rect| from the - // original non interpolated frame. - // TODO(vmpstr): This damage may be too large, but I think it's hard to figure - // out a small bounds on the damage given an animation that happens in - // SurfaceAnimationManager. - if (surface_->HasSurfaceAnimationDamage()) { - return FrameDamageType::kFull; - } - if (previous_frame_index_ == frame_index_) { // This is the same frame as the one used last aggregation. return FrameDamageType::kNone;
diff --git a/components/viz/service/display/surface_aggregator.cc b/components/viz/service/display/surface_aggregator.cc index 807eff5..924ff1f 100644 --- a/components/viz/service/display/surface_aggregator.cc +++ b/components/viz/service/display/surface_aggregator.cc
@@ -408,12 +408,6 @@ const gfx::Transform& parent_target_transform, const Surface* surface, size_t* overlay_damage_index) { - // If we have damage from a surface animation, then we shouldn't have an - // overlay candidate from the root render pass, since that's an interpolated - // pass with "artificial" damage. - if (surface->HasSurfaceAnimationDamage()) - return nullptr; - // Only process the damage rect at the root render pass, once per surface. const CompositorFrame& frame = surface->GetActiveFrame(); bool is_last_pass_on_src_surface = @@ -572,8 +566,7 @@ // If there is a new CompositorFrame for `surface` compute resolved frame // data for the new resolved CompositorFrame. if (resolved_frame.previous_frame_index() != - surface->GetActiveFrameIndex() || - surface->HasSurfaceAnimationDamage()) { + surface->GetActiveFrameIndex()) { base::ElapsedTimer timer; ProcessResolvedFrame(resolved_frame); stats_->declare_resources_time += timer.Elapsed(); @@ -931,7 +924,6 @@ } referenced_surfaces_.erase(surface_id); - surface->DidAggregate(); } void SurfaceAggregator::EmitDefaultBackgroundColorQuad(
diff --git a/components/viz/service/surfaces/surface.cc b/components/viz/service/surfaces/surface.cc index 1e477e96..54ac755 100644 --- a/components/viz/service/surfaces/surface.cc +++ b/components/viz/service/surfaces/surface.cc
@@ -732,23 +732,10 @@ return active_frame_data_->frame.metadata; } -void Surface::ResetInterpolatedFrame() { - interpolated_frame_.reset(); - has_damage_from_interpolated_frame_ = true; -} - void Surface::SetInterpolatedFrame(CompositorFrame frame) { interpolated_frame_.emplace(std::move(frame)); } -bool Surface::HasSurfaceAnimationDamage() const { - return interpolated_frame_.has_value() || has_damage_from_interpolated_frame_; -} - -void Surface::DidAggregate() { - has_damage_from_interpolated_frame_ = false; -} - const CompositorFrame& Surface::GetPendingFrame() { DCHECK(pending_frame_data_); return pending_frame_data_->frame;
diff --git a/components/viz/service/surfaces/surface.h b/components/viz/service/surfaces/surface.h index 16ed8468..d7630fa8 100644 --- a/components/viz/service/surfaces/surface.h +++ b/components/viz/service/surfaces/surface.h
@@ -202,7 +202,6 @@ const CompositorFrame& GetActiveFrame() const; const CompositorFrameMetadata& GetActiveFrameMetadata() const; - void ResetInterpolatedFrame(); void SetInterpolatedFrame(CompositorFrame frame); const CompositorFrame& GetActiveOrInterpolatedFrame() const; bool HasInterpolatedFrame() const; @@ -311,8 +310,6 @@ std::unique_ptr<CopyOutputRequest> copy_request, CompositorRenderPassId render_pass_id); - void DidAggregate(); - // Returns frame id of the oldest uncommitted frame if any, absl::optional<BeginFrameId> GetFirstUncommitedFrameId(); @@ -440,8 +437,6 @@ const raw_ptr<SurfaceAllocationGroup> allocation_group_; - bool has_damage_from_interpolated_frame_ = false; - const size_t max_uncommitted_frames_; base::WeakPtrFactory<Surface> weak_factory_{this};
diff --git a/components/viz/service/transitions/surface_animation_manager.cc b/components/viz/service/transitions/surface_animation_manager.cc index d0033142..688cad4 100644 --- a/components/viz/service/transitions/surface_animation_manager.cc +++ b/components/viz/service/transitions/surface_animation_manager.cc
@@ -68,6 +68,11 @@ shared_element_quad.rect, shared_pass_output_rect); copied_quad_state->quad_to_target_transform.PreConcat(transform); + shared_element_content_pass->transform_to_root_target = + copied_quad_state->quad_to_target_transform; + shared_element_content_pass->transform_to_root_target.PostConcat( + target_render_pass->transform_to_root_target); + auto* render_pass_quad = target_render_pass ->CreateAndAppendDrawQuad<CompositorRenderPassDrawQuad>();
diff --git a/content/browser/child_process_security_policy_impl.cc b/content/browser/child_process_security_policy_impl.cc index 6460cf6..38f318f 100644 --- a/content/browser/child_process_security_policy_impl.cc +++ b/content/browser/child_process_security_policy_impl.cc
@@ -2446,6 +2446,14 @@ return nullptr; } +OriginAgentClusterIsolationState* +ChildProcessSecurityPolicyImpl::LookupOriginIsolationStateForTesting( + const BrowsingInstanceId& browsing_instance_id, + const url::Origin& origin) { + base::AutoLock lock(origins_isolation_opt_in_lock_); + return LookupOriginIsolationState(browsing_instance_id, origin); +} + void ChildProcessSecurityPolicyImpl::AddDefaultIsolatedOriginIfNeeded( const IsolationContext& isolation_context, const url::Origin& origin, @@ -2484,8 +2492,9 @@ // walks (when the origin won't be in this list yet), but it matters during // frame removal (when we don't want to add an opted-in origin to the // list as non-isolated when its frame is removed). - if (LookupOriginIsolationState(browsing_instance_id, origin)) + if (LookupOriginIsolationState(browsing_instance_id, origin)) { return; + } // Since there was no prior record for this BrowsingInstance, track that this // origin should use the default isolation model in use by the
diff --git a/content/browser/child_process_security_policy_impl.h b/content/browser/child_process_security_policy_impl.h index b2251d1..8cff343 100644 --- a/content/browser/child_process_security_policy_impl.h +++ b/content/browser/child_process_security_policy_impl.h
@@ -549,6 +549,11 @@ void ClearRegisteredSchemeForTesting(const std::string& scheme); + // Exposes LookupOriginIsolationState() for tests. + OriginAgentClusterIsolationState* LookupOriginIsolationStateForTesting( + const BrowsingInstanceId& browsing_instance_id, + const url::Origin& origin); + private: friend class ChildProcessSecurityPolicyInProcessBrowserTest; friend class ChildProcessSecurityPolicyTest;
diff --git a/content/browser/isolated_origin_browsertest.cc b/content/browser/isolated_origin_browsertest.cc index 90ed084..2b88269 100644 --- a/content/browser/isolated_origin_browsertest.cc +++ b/content/browser/isolated_origin_browsertest.cc
@@ -138,13 +138,15 @@ ProcessLock ProcessLockFromUrl(const std::string& url) { BrowserContext* browser_context = web_contents()->GetBrowserContext(); return ProcessLock::FromSiteInfo(SiteInfo( - GURL(url), GURL(url), false /* requires_origin_keyed_process */, - false /* is_sandboxed */, UrlInfo::kInvalidUniqueSandboxId, + GURL(url), GURL(url), + /*requires_origin_keyed_process=*/false, + /*requires_origin_keyed_process_by_default=*/false, + /*is_sandboxed=*/false, UrlInfo::kInvalidUniqueSandboxId, StoragePartitionConfig::CreateDefault(browser_context), - WebExposedIsolationInfo::CreateNonIsolated(), false /* is_guest */, - false /* does_site_request_dedicated_process_for_coop */, - false /* is_jit_disabled */, false /* is_pdf */, - false /* is_fenced */)); + WebExposedIsolationInfo::CreateNonIsolated(), /*is_guest=*/false, + /*does_site_request_dedicated_process_for_coop=*/false, + /*is_jit_disabled=*/false, /*is_pdf=*/false, + /*is_fenced=*/false)); } WebContentsImpl* web_contents() const { @@ -162,13 +164,15 @@ BrowserContext* browser_context = web_contents()->GetBrowserContext(); GURL origin_url = url::Origin::Create(url).GetURL(); return ProcessLock::FromSiteInfo(SiteInfo( - origin_url, origin_url, false /* requires_origin_keyed_process */, - false /* is_sandboxed */, UrlInfo::kInvalidUniqueSandboxId, + origin_url, origin_url, + /*requires_origin_keyed_process=*/false, + /*requires_origin_keyed_process_by_default=*/false, + /*is_sandboxed=*/false, UrlInfo::kInvalidUniqueSandboxId, StoragePartitionConfig::CreateDefault(browser_context), - WebExposedIsolationInfo::CreateNonIsolated(), false /* is_guest */, - false /* does_site_request_dedicated_process_for_coop */, - false /* is_jit_disabled */, false /* is_pdf */, - false /* is_fenced */)); + WebExposedIsolationInfo::CreateNonIsolated(), /*is_guest=*/false, + /*does_site_request_dedicated_process_for_coop=*/false, + /*is_jit_disabled=*/false, /*is_pdf=*/false, + /*is_fenced=*/false)); } protected: @@ -716,10 +720,8 @@ EXPECT_TRUE(isolation_state.is_origin_agent_cluster()); EXPECT_TRUE(isolation_state.requires_origin_keyed_process()); EXPECT_TRUE(site_instance->GetSiteInfo().requires_origin_keyed_process()); - // TODO(wjmaclean): Enable the following in the next CL when we plumb through - // the flag to avoid tracking default-isolated SiteInstance origins. - // EXPECT_TRUE(site_instance->GetSiteInfo() - // .requires_origin_keyed_process_by_default()); + EXPECT_TRUE( + site_instance->GetSiteInfo().requires_origin_keyed_process_by_default()); } // The same as for DefaultOptInIsIsolated, but testing on a subframe. @@ -755,10 +757,98 @@ EXPECT_TRUE(child_isolation_state.requires_origin_keyed_process()); EXPECT_TRUE( child_site_instance->GetSiteInfo().requires_origin_keyed_process()); - // TODO(wjmaclean): Enable the following in the next CL when we plumb through - // the flag to avoid tracking default-isolated SiteInstance origins. - // EXPECT_TRUE(child_site_instance->GetSiteInfo() - // .requires_origin_keyed_process_by_default()); + EXPECT_TRUE(child_site_instance->GetSiteInfo() + .requires_origin_keyed_process_by_default()); + + auto* policy = ChildProcessSecurityPolicyImpl::GetInstance(); + IsolationContext isolation_context = + root_site_instance->GetIsolationContext(); + // Verify that we're not explicitly tracking the origin for + // `default_isolated_url`. + EXPECT_EQ(static_cast<OriginAgentClusterIsolationState*>(nullptr), + policy->LookupOriginIsolationStateForTesting( + isolation_context.browsing_instance_id(), + url::Origin::Create(default_isolated_url))); + + // Now trigger a global walk by attempting to create a non-isolated version of + // the same origin. + GURL attempted_non_isolated_url( + https_server()->GetURL("isolated.foo.com", "/isolate_origin")); + SetHeaderValue("?0"); + EXPECT_TRUE( + NavigateToURLFromRenderer(child_frame_node, attempted_non_isolated_url)); + // Now the origin should be explicitly tracked, even though it continues to + // have the default isolation state as defined for the current + // BrowsingInstance. + OriginAgentClusterIsolationState* isolation_state2 = + policy->LookupOriginIsolationStateForTesting( + isolation_context.browsing_instance_id(), + url::Origin::Create(default_isolated_url)); + ASSERT_NE(static_cast<OriginAgentClusterIsolationState*>(nullptr), + isolation_state2); + EXPECT_TRUE(isolation_state2->is_origin_agent_cluster()); + EXPECT_TRUE(isolation_state2->requires_origin_keyed_process()); +} + +// Using origin-keyed processes by default faces a challenge for speculative +// RenderFrameHosts, which are created before any OAC headers arrive. +// Note: the origin is tracked even though the SiteInfo still says it is an +// origin-keyed process by default. +IN_PROC_BROWSER_TEST_F(OriginKeyedProcessByDefaultTest, + ExplicitOptInRespected) { + GURL test_url(https_server()->GetURL("foo.com", + "/cross_site_iframe_factory.html?" + "foo.com(foo.com)")); + EXPECT_TRUE(NavigateToURL(shell(), test_url)); + EXPECT_EQ(2u, CollectAllRenderFrameHosts(shell()->web_contents()).size()); + FrameTreeNode* root = web_contents()->GetPrimaryFrameTree().root(); + FrameTreeNode* child_frame_node = root->child_at(0); + + // This request explicitly opts-in to OAC, and should get process isolation. + // Note the use of the "isolate_origin" relative path below to force + // processing of the (non-empty) OAC header. + SetHeaderValue("?1"); + GURL explicit_isolated_url( + https_server()->GetURL("isolated.foo.com", "/isolate_origin")); + EXPECT_TRUE( + NavigateToURLFromRenderer(child_frame_node, explicit_isolated_url)); + + auto* site_instance = + child_frame_node->current_frame_host()->GetSiteInstance(); + OriginAgentClusterIsolationState isolation_state = + DetermineOriginAgentClusterIsolation(site_instance, + explicit_isolated_url); + EXPECT_TRUE(isolation_state.is_origin_agent_cluster()); + EXPECT_TRUE(isolation_state.requires_origin_keyed_process()); + EXPECT_TRUE(site_instance->GetSiteInfo().requires_origin_keyed_process()); + // In this scenario, the explicit opt-in ends up using a SiteInstance that was + // created for the speculative RFH, and with requires_origin_keyed_process on + // by default. Since we don't want to alter the underlying SiteInfo after + // it's been used to create a ProcessLock, we leave this case as "by_default" + // in the SiteInfo since the isolation behavior is the same. + // + // Note that if the speculative RFH had been created after a previous instance + // of the origin had been explicitly opted-in, then + // `requires_origin_keyed_process_by_default()` would return false in that + // case. This can happen in a cross-origin redirect from A to B, where B has + // an opt-in header. We would create a speculative RFH for A, throw it away + // when the redirect happens, and wait to create the RFH for B until headers + // have arrived. + EXPECT_TRUE( + site_instance->GetSiteInfo().requires_origin_keyed_process_by_default()); + + // Verify the explicit opt-in is being tracked. + auto* policy = ChildProcessSecurityPolicyImpl::GetInstance(); + IsolationContext isolation_context = + root->current_frame_host()->GetSiteInstance()->GetIsolationContext(); + OriginAgentClusterIsolationState* isolation_state2 = + policy->LookupOriginIsolationStateForTesting( + isolation_context.browsing_instance_id(), + url::Origin::Create(explicit_isolated_url)); + ASSERT_NE(static_cast<OriginAgentClusterIsolationState*>(nullptr), + isolation_state2); + EXPECT_TRUE(isolation_state2->is_origin_agent_cluster()); + EXPECT_TRUE(isolation_state2->requires_origin_keyed_process()); } // Process-isolated OAC-by-default should not process isolate a navigation that @@ -783,30 +873,29 @@ EXPECT_TRUE( NavigateToURLFromRenderer(child_frame_node, default_not_isolated_url)); - // TODO(wjmaclean): At this point in the test we would like to be able to test - // expectations saying that the child frame's isolation state is (i) - // is_origin_agent_cluster() = false, (ii) requires_origin_keyed_process() = - // false, and (iii) requires_origin_keyed_process() = false. - // However, due to the fact that we haven't yet excluded - // OriginKeyedProcessByDefault origins from having their isolation state - // tracked, the default-isolation of the speculative RFH means that we didn't - // get the opt-out we asked for, because it opted-in the origin before we - // ever saw the header. - // - // In the next CL, when we stop tracking OriginKeyedProcessByDefault origins, - // change the EXPECT_TRUE calls to EXPECT_FALSE. auto* site_instance = child_frame_node->current_frame_host()->GetSiteInstance(); OriginAgentClusterIsolationState isolation_state = DetermineOriginAgentClusterIsolation(site_instance, default_not_isolated_url); - EXPECT_TRUE(isolation_state.is_origin_agent_cluster()); - EXPECT_TRUE(isolation_state.requires_origin_keyed_process()); - EXPECT_TRUE(site_instance->GetSiteInfo().requires_origin_keyed_process()); - // TODO(wjmaclean): Enable the following in the next CL when we stop tracking - // OriginKeyedProcessByDefault origins. - // EXPECT_FALSE( - // site_instance->GetSiteInfo().requires_origin_keyed_process_by_default()); + EXPECT_FALSE(isolation_state.is_origin_agent_cluster()); + EXPECT_FALSE(isolation_state.requires_origin_keyed_process()); + EXPECT_FALSE(site_instance->GetSiteInfo().requires_origin_keyed_process()); + EXPECT_FALSE( + site_instance->GetSiteInfo().requires_origin_keyed_process_by_default()); + + // Verify the explicit opt-out is being tracked. + auto* policy = ChildProcessSecurityPolicyImpl::GetInstance(); + IsolationContext isolation_context = + root->current_frame_host()->GetSiteInstance()->GetIsolationContext(); + OriginAgentClusterIsolationState* isolation_state2 = + policy->LookupOriginIsolationStateForTesting( + isolation_context.browsing_instance_id(), + url::Origin::Create(default_not_isolated_url)); + ASSERT_NE(static_cast<OriginAgentClusterIsolationState*>(nullptr), + isolation_state2); + EXPECT_FALSE(isolation_state2->is_origin_agent_cluster()); + EXPECT_FALSE(isolation_state2->requires_origin_keyed_process()); } IN_PROC_BROWSER_TEST_F(OriginIsolationDefaultOACTest, Basic) { @@ -1194,13 +1283,16 @@ https_server()->GetURL("isolated.foo.com", "/isolate_origin")); GURL origin_url = url::Origin::Create(isolated_suborigin_url).GetURL(); BrowserContext* browser_context = web_contents()->GetBrowserContext(); - auto expected_isolated_suborigin_lock = ProcessLock::FromSiteInfo(SiteInfo( - origin_url, origin_url, true /* requires_origin_keyed_process */, - false /* is_sandboxed */, UrlInfo::kInvalidUniqueSandboxId, - StoragePartitionConfig::CreateDefault(browser_context), - WebExposedIsolationInfo::CreateNonIsolated(), false /* is_guest */, - false /* does_site_request_dedicated_process_for_coop */, - false /* is_jit_disabled */, false /* is_pdf */, false /* is_fenced */)); + auto expected_isolated_suborigin_lock = ProcessLock::FromSiteInfo( + SiteInfo(origin_url, origin_url, + /*requires_origin_keyed_process=*/true, + /*requires_origin_keyed_process_by_default=*/false, + /*is_sandboxed=*/false, UrlInfo::kInvalidUniqueSandboxId, + StoragePartitionConfig::CreateDefault(browser_context), + WebExposedIsolationInfo::CreateNonIsolated(), /*is_guest=*/false, + /*does_site_request_dedicated_process_for_coop=*/false, + /*is_jit_disabled=*/false, /*is_pdf=*/false, + /*is_fenced=*/false)); EXPECT_TRUE(NavigateToURL(shell(), test_url)); EXPECT_EQ(2u, CollectAllRenderFrameHosts(shell()->web_contents()).size());
diff --git a/content/browser/media/session/media_session_impl.cc b/content/browser/media/session/media_session_impl.cc index 5bc07e6d..3440f79c 100644 --- a/content/browser/media/session/media_session_impl.cc +++ b/content/browser/media/session/media_session_impl.cc
@@ -24,7 +24,6 @@ #include "content/browser/renderer_host/back_forward_cache_disable.h" #include "content/browser/renderer_host/back_forward_cache_impl.h" #include "content/browser/web_contents/web_contents_impl.h" -#include "content/common/media/constants.h" #include "content/public/browser/browser_context.h" #include "content/public/browser/media_session.h" #include "content/public/browser/navigation_handle.h" @@ -435,12 +434,7 @@ if (player.observer->render_frame_host() != host) continue; hidden_players_.erase(player); - - // We directly call `AddPlayerInternal()` to avoid the - // `CanRequestSystemAudioFocus()` check, since we can add the players - // back regardless. - AddPlayerInternal(player.observer, player.player_id); - + AddPlayer(player.observer, player.player_id); added_players = true; } @@ -455,15 +449,6 @@ bool MediaSessionImpl::AddPlayer(MediaSessionPlayerObserver* observer, int player_id) { - if (!CanRequestSystemAudioFocus()) { - return false; - } - - return AddPlayerInternal(observer, player_id); -} - -bool MediaSessionImpl::AddPlayerInternal(MediaSessionPlayerObserver* observer, - int player_id) { media::MediaContentType media_content_type = observer->GetMediaContentType(); if (media_content_type == media::MediaContentType::OneShot) @@ -683,8 +668,7 @@ // When the resume requests comes from another source than system, audio focus // must be requested. - if (suspend_type != SuspendType::kSystem && - CanRequestSystemAudioFocus(suspend_type)) { + if (suspend_type != SuspendType::kSystem) { // Request audio focus again in case we lost it because another app started // playing while the playback was paused. If the audio focus request is // delayed we will resume the player when the request completes. @@ -1921,38 +1905,6 @@ guarding_player_id_.reset(); } -bool MediaSessionImpl::CanRequestSystemAudioFocus() const { - // If we already have audio focus, we're able to continue adding players. - if (audio_focus_state_ == State::ACTIVE) { - return true; - } - - // If we don't allow background playback and the widget is hidden, then we - // should not request audio focus as playback will fail to start. - if (kIsBackgroundMediaSuspendEnabled) { - if (web_contents()->GetRenderWidgetHostView() && - web_contents()->GetRenderWidgetHostView()->GetRenderWidgetHost()) { - return !static_cast<RenderWidgetHostImpl*>(web_contents() - ->GetRenderWidgetHostView() - ->GetRenderWidgetHost()) - ->is_hidden(); - } - } - - return true; -} - -bool MediaSessionImpl::CanRequestSystemAudioFocus( - SuspendType suspend_type) const { - // When the resume request comes from UI, then we always allow it to resume - // playback. - if (suspend_type == SuspendType::kUI) { - return true; - } - - return CanRequestSystemAudioFocus(); -} - void MediaSessionImpl::SetShouldThrottleDurationUpdateForTest( bool should_throttle) { should_throttle_duration_update_ = should_throttle;
diff --git a/content/browser/media/session/media_session_impl.h b/content/browser/media/session/media_session_impl.h index 7cb1c245..e6e5b5fa 100644 --- a/content/browser/media/session/media_session_impl.h +++ b/content/browser/media/session/media_session_impl.h
@@ -357,8 +357,6 @@ friend class MediaSessionImplDurationThrottleTest; friend class MediaInternalsAudioFocusTest; - bool AddPlayerInternal(MediaSessionPlayerObserver* observer, int player_id); - CONTENT_EXPORT void RemoveAllPlayersForTest(); CONTENT_EXPORT MediaSessionUmaHelper* uma_helper_for_test(); @@ -487,14 +485,6 @@ void ResetDurationUpdateGuard(); - // Returns true if MediaSessionImpl should request system audio focus when - // playback occurs. - bool CanRequestSystemAudioFocus() const; - - // Same as |CanRequestSystemAudioFocus()|, except taking into account the - // source of the playback request was received. - bool CanRequestSystemAudioFocus(SuspendType suspend_type) const; - CONTENT_EXPORT void SetShouldThrottleDurationUpdateForTest( bool should_throttle);
diff --git a/content/browser/media/session/media_session_impl_unittest.cc b/content/browser/media/session/media_session_impl_unittest.cc index c57478a..ec5de0a 100644 --- a/content/browser/media/session/media_session_impl_unittest.cc +++ b/content/browser/media/session/media_session_impl_unittest.cc
@@ -13,7 +13,6 @@ #include "content/browser/media/session/media_session_player_observer.h" #include "content/browser/media/session/mock_media_session_player_observer.h" #include "content/browser/media/session/mock_media_session_service_impl.h" -#include "content/common/media/constants.h" #include "content/public/browser/browser_context.h" #include "content/public/browser/media_session_service.h" #include "content/public/browser/web_contents_delegate.h" @@ -202,11 +201,6 @@ return default_actions_; } - void HideRenderWidgetHost() { - auto* rwh = RenderWidgetHostImpl::From(rvh()->GetWidget()); - rwh->WasHidden(); - } - private: std::set<media_session::mojom::MediaSessionAction> default_actions_; @@ -793,22 +787,6 @@ GetMediaSession()->Raise(); } -TEST_F(MediaSessionImplTest, - HiddenTabsCantRequestFocusWhenBackgroundSuspendIsEnabled) { - MockAudioFocusDelegate* delegate = new MockAudioFocusDelegate(); - SetDelegateForTests(GetMediaSession(), delegate); - - EXPECT_EQ(0, delegate->request_audio_focus_count()); - HideRenderWidgetHost(); - StartNewPlayer(); - - if (kIsBackgroundMediaSuspendEnabled) { - EXPECT_EQ(0, delegate->request_audio_focus_count()); - } else { - EXPECT_EQ(1, delegate->request_audio_focus_count()); - } -} - // Tests for throttling duration updates. // TODO (jazzhsu): Remove these tests once media session supports livestream. class MediaSessionImplDurationThrottleTest : public MediaSessionImplTest {
diff --git a/content/browser/preloading/preloading_data_impl.cc b/content/browser/preloading/preloading_data_impl.cc index b341c357..28ba117 100644 --- a/content/browser/preloading/preloading_data_impl.cc +++ b/content/browser/preloading/preloading_data_impl.cc
@@ -148,6 +148,9 @@ void PreloadingDataImpl::SetIsNavigationInDomainCallback( PreloadingPredictor predictor, PredictorDomainCallback is_navigation_in_domain_callback) { + if (is_navigation_in_predictor_domain_callbacks_.contains(predictor)) { + return; + } is_navigation_in_predictor_domain_callbacks_[predictor] = std::move(is_navigation_in_domain_callback); } @@ -287,16 +290,19 @@ : PredictorConfusionMatrix::kFalseNegative); for (const auto& preloading_type : kPreloadingTypes) { - const auto uma_attempt_recall = + const auto uma_attemp_recall = base::StrCat({"Preloading.", PreloadingTypeToString(preloading_type), ".Attempt.", predictor_type.name(), ".Recall"}); base::UmaHistogramEnumeration( - uma_attempt_recall, preloading_attempt_recall_stats_.contains( - {predictor_type, preloading_type}) - ? PredictorConfusionMatrix::kTruePositive - : PredictorConfusionMatrix::kFalseNegative); + uma_attemp_recall, preloading_attempt_recall_stats_.contains( + {predictor_type, preloading_type}) + ? PredictorConfusionMatrix::kTruePositive + : PredictorConfusionMatrix::kFalseNegative); } } + // Clear registered predictor domain callbacks and get ready for the next + // navigation. + is_navigation_in_predictor_domain_callbacks_.clear(); } void PreloadingDataImpl::SetIsAccurateTriggeringAndPrediction(
diff --git a/content/browser/preloading/preloading_data_impl.h b/content/browser/preloading/preloading_data_impl.h index 6fdecc1..d19c48b3 100644 --- a/content/browser/preloading/preloading_data_impl.h +++ b/content/browser/preloading/preloading_data_impl.h
@@ -78,6 +78,10 @@ void SetIsNavigationInDomainCallback( PreloadingPredictor predictor, PredictorDomainCallback is_navigation_in_domain_callback) override; + bool CheckNavigationInDomainCallbackForTesting( + PreloadingPredictor predictor) { + return is_navigation_in_predictor_domain_callbacks_.count(predictor); + } // WebContentsObserver override. void DidStartNavigation(NavigationHandle* navigation_handle) override;
diff --git a/content/browser/preloading/preloading_decider.cc b/content/browser/preloading/preloading_decider.cc index 47071f6..ac104b0 100644 --- a/content/browser/preloading/preloading_decider.cc +++ b/content/browser/preloading/preloading_decider.cc
@@ -9,6 +9,7 @@ #include "content/browser/preloading/preloading.h" #include "content/browser/preloading/prerenderer_impl.h" #include "content/browser/renderer_host/render_frame_host_impl.h" +#include "content/public/browser/navigation_handle.h" #include "content/public/browser/preloading.h" #include "content/public/browser/web_contents.h" #include "third_party/blink/public/common/features.h" @@ -168,6 +169,41 @@ observer_for_testing_->UpdateSpeculationCandidates(candidates); } + WebContents* web_contents = + WebContents::FromRenderFrameHost(&render_frame_host()); + auto* preloading_data = + PreloadingData::GetOrCreateForWebContents(web_contents); + preloading_data->SetIsNavigationInDomainCallback( + content_preloading_predictor::kSpeculationRules, + base::BindRepeating([](NavigationHandle* navigation_handle) -> bool { + return ui::PageTransitionIsWebTriggerable( + navigation_handle->GetPageTransition()); + })); + if (base::FeatureList::IsEnabled( + blink::features::kSpeculationRulesPointerDownHeuristics)) { + preloading_data->SetIsNavigationInDomainCallback( + preloading_predictor::kUrlPointerDownOnAnchor, + base::BindRepeating([](NavigationHandle* navigation_handle) -> bool { + return ui::PageTransitionCoreTypeIs( + navigation_handle->GetPageTransition(), + ui::PageTransition::PAGE_TRANSITION_LINK) && + ui::PageTransitionIsNewNavigation( + navigation_handle->GetPageTransition()); + })); + } + if (base::FeatureList::IsEnabled( + blink::features::kSpeculationRulesPointerHoverHeuristics)) { + preloading_data->SetIsNavigationInDomainCallback( + preloading_predictor::kUrlPointerHoverOnAnchor, + base::BindRepeating([](NavigationHandle* navigation_handle) -> bool { + return ui::PageTransitionCoreTypeIs( + navigation_handle->GetPageTransition(), + ui::PageTransition::PAGE_TRANSITION_LINK) && + ui::PageTransitionIsNewNavigation( + navigation_handle->GetPageTransition()); + })); + } + // Here we look for all preloading candidates that are safe to perform, but // their eagerness level is not high enough to perform without the trigger // form link selection heuristics logic. We then remove them from the
diff --git a/content/browser/preloading/preloading_decider_browsertest.cc b/content/browser/preloading/preloading_decider_browsertest.cc new file mode 100644 index 0000000..bfc6f1f --- /dev/null +++ b/content/browser/preloading/preloading_decider_browsertest.cc
@@ -0,0 +1,97 @@ +// Copyright 2023 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/preloading/preloading_decider.h" + +#include "base/test/scoped_feature_list.h" +#include "components/ukm/test_ukm_recorder.h" +#include "content/public/test/browser_test.h" +#include "content/public/test/browser_test_utils.h" +#include "content/public/test/content_browser_test.h" +#include "content/public/test/content_browser_test_utils.h" +#include "content/shell/browser/shell.h" +#include "net/dns/mock_host_resolver.h" +#include "testing/gtest/include/gtest/gtest.h" +#include "third_party/blink/public/common/features.h" + +namespace content { + +class PreloadingDeciderBrowserTest : public ContentBrowserTest { + public: + PreloadingDeciderBrowserTest() = default; + ~PreloadingDeciderBrowserTest() override = default; + + void SetUp() override { + feature_list_.InitWithFeaturesAndParameters( + { + {blink::features::kSpeculationRulesPointerDownHeuristics, {}}, + {blink::features::kSpeculationRulesPointerHoverHeuristics, {}}, + }, + {}); + + ContentBrowserTest::SetUp(); + } + + void SetUpOnMainThread() override { + ContentBrowserTest::SetUpOnMainThread(); + host_resolver()->AddRule("*", "127.0.0.1"); + https_server_ = std::make_unique<net::EmbeddedTestServer>( + net::EmbeddedTestServer::TYPE_HTTPS); + https_server_->AddDefaultHandlers(GetTestDataFilePath()); + + ASSERT_TRUE(https_server_->Start()); + ResetUKM(); + } + + WebContents* web_contents() { return shell()->web_contents(); } + void ResetUKM() { + ukm_recorder_ = std::make_unique<ukm::TestAutoSetUkmRecorder>(); + } + + const GURL GetTestURL(const char* file) const { + return https_server_->GetURL(file); + } + void NavigateTo(const GURL& url) { + ASSERT_TRUE(NavigateToURL(shell(), url)); + base::RunLoop().RunUntilIdle(); + } + + void NavigateAway() { + ASSERT_TRUE(NavigateToURL(shell(), GURL(url::kAboutBlankURL))); + base::RunLoop().RunUntilIdle(); + } + + private: + base::test::ScopedFeatureList feature_list_; + std::unique_ptr<net::EmbeddedTestServer> https_server_; + std::unique_ptr<ukm::TestAutoSetUkmRecorder> ukm_recorder_; +}; + +IN_PROC_BROWSER_TEST_F(PreloadingDeciderBrowserTest, + SetIsNavigationInDomainCallback) { + base::HistogramTester histogram_tester; + NavigateTo(GetTestURL("/preloading/preloading_decider.html")); + EXPECT_EQ(true, EvalJs(web_contents(), + "HTMLScriptElement.supports('speculationrules')")); + base::RunLoop().RunUntilIdle(); + + // Now navigate to another page + EXPECT_TRUE(ExecJs(web_contents(), + R"( + let bar = document.getElementById("bar"); + bar.click(); + )")); + base::RunLoop().RunUntilIdle(); + histogram_tester.ExpectBucketCount( + "Preloading.Predictor.SpeculationRules.Recall", + /*content::PredictorConfusionMatrix::kFalseNegative*/ 3, 1); + histogram_tester.ExpectBucketCount( + "Preloading.Predictor.UrlPointerDownOnAnchor.Recall", + /*content::PredictorConfusionMatrix::kFalseNegative*/ 3, 1); + histogram_tester.ExpectBucketCount( + "Preloading.Predictor.UrlPointerHoverOnAnchor.Recall", + /*content::PredictorConfusionMatrix::kFalseNegative*/ 3, 1); +} + +} // namespace content
diff --git a/content/browser/preloading/preloading_decider_unittest.cc b/content/browser/preloading/preloading_decider_unittest.cc index b3c2d8f..aad13661 100644 --- a/content/browser/preloading/preloading_decider_unittest.cc +++ b/content/browser/preloading/preloading_decider_unittest.cc
@@ -6,11 +6,13 @@ #include <vector> +#include "base/strings/strcat.h" #include "base/test/scoped_feature_list.h" #include "content/browser/preloading/prefetch/prefetch_document_manager.h" #include "content/browser/preloading/prefetch/prefetch_features.h" #include "content/browser/preloading/prefetch/prefetch_service.h" #include "content/browser/preloading/prefetcher.h" +#include "content/browser/preloading/preloading_data_impl.h" #include "content/browser/preloading/prerenderer.h" #include "content/public/browser/anchor_element_preconnect_delegate.h" #include "content/public/common/content_client.h" @@ -475,5 +477,44 @@ EXPECT_EQ(1u, GetPrefetchService()->prefetches_.size()); } +TEST_F(PreloadingDeciderTest, UmaRecallStats) { + base::HistogramTester histogram_tester; + auto* preloading_decider = + PreloadingDecider::GetOrCreateForCurrentDocument(&GetPrimaryMainFrame()); + ASSERT_TRUE(preloading_decider != nullptr); + + std::vector<blink::mojom::SpeculationCandidatePtr> candidates; + auto candidate = blink::mojom::SpeculationCandidate::New(); + candidate->action = blink::mojom::SpeculationAction::kPrefetch; + candidate->url = GetCrossOriginUrl("/candidate1.html"); + candidate->referrer = blink::mojom::Referrer::New(); + candidate->eagerness = blink::mojom::SpeculationEagerness::kEager; + candidates.push_back(std::move(candidate)); + + preloading_decider->UpdateSpeculationCandidates(candidates); + + PreloadingPredictor pointer_down_predictor{ + preloading_predictor::kUrlPointerDownOnAnchor}; + // PreloadingPredictor on_hover_predictor{ + // preloading_predictor::kUrlPointerHoverOnAnchor}; + // Check recall UKM records. + auto uma_predictor_recall = [](const PreloadingPredictor& predictor) { + return base::StrCat({"Preloading.Predictor.", predictor.name(), ".Recall"}); + }; + + WebContents* web_contents = + WebContents::FromRenderFrameHost(&GetPrimaryMainFrame()); + web_contents->GetController().LoadURL( + GURL("https://www.google.com"), {}, + ui::PageTransition::PAGE_TRANSITION_LINK, {}); + + histogram_tester.ExpectBucketCount( + uma_predictor_recall(pointer_down_predictor), + PredictorConfusionMatrix::kTruePositive, 0); + histogram_tester.ExpectBucketCount( + uma_predictor_recall(pointer_down_predictor), + PredictorConfusionMatrix::kFalseNegative, 0); +} + } // namespace } // namespace content
diff --git a/content/browser/private_aggregation/private_aggregation_host.h b/content/browser/private_aggregation/private_aggregation_host.h index 86a2463b..625615d 100644 --- a/content/browser/private_aggregation/private_aggregation_host.h +++ b/content/browser/private_aggregation/private_aggregation_host.h
@@ -55,8 +55,8 @@ static constexpr char kApiReportVersion[] = "0.1"; // The maximum number of contributions that can go in an `AggregatableReport`. - // Aligns with `blink::kMaxAttributionAggregationKeysPerSourceOrTrigger`. - static constexpr int kMaxNumberOfContributions = 50; + // Aligns with `attribution_reporting::kMaxAggregationKeysPerSourceOrTrigger`. + static constexpr int kMaxNumberOfContributions = 20; // The maximum allowed context_id string length. static constexpr int kMaxContextIdLength = 64;
diff --git a/content/browser/process_lock.cc b/content/browser/process_lock.cc index 1d364e6..167c7f68 100644 --- a/content/browser/process_lock.cc +++ b/content/browser/process_lock.cc
@@ -14,11 +14,13 @@ const StoragePartitionConfig& storage_partition_config, const WebExposedIsolationInfo& web_exposed_isolation_info) { return ProcessLock(SiteInfo( - GURL(), GURL(), false, false /* is_sandboxed */, - UrlInfo::kInvalidUniqueSandboxId, storage_partition_config, - web_exposed_isolation_info, /* is_guest */ false, - /* does_site_request_dedicated_process_for_coop */ false, - /* is_jit_disabled */ false, /* is_pdf */ false, /* is_fenced */ false)); + GURL(), GURL(), /*requires_origin_keyed_process=*/false, + /*requires_origin_keyed_process_by_default=*/false, + /*is_sandboxed=*/false, UrlInfo::kInvalidUniqueSandboxId, + storage_partition_config, web_exposed_isolation_info, + /*is_guest=*/false, + /*does_site_request_dedicated_process_for_coop=*/false, + /*is_jit_disabled=*/false, /*is_pdf=*/false, /*is_fenced=*/false)); } // static
diff --git a/content/browser/renderer_host/navigation_request.cc b/content/browser/renderer_host/navigation_request.cc index e9beb638..8b054b3 100644 --- a/content/browser/renderer_host/navigation_request.cc +++ b/content/browser/renderer_host/navigation_request.cc
@@ -3411,12 +3411,18 @@ void NavigationRequest::AddOriginAgentClusterStateIfNecessary( const IsolationContext& isolation_context) { - // In this function we only handle opt-in requests for the cases where OAC - // process isolation is not enabled. Otherwise it will be handled when the - // origin's SiteInstance is created. - bool is_opt_in_requested = - IsOriginAgentClusterOptInRequested() && - !SiteIsolationPolicy::IsProcessIsolationForOriginAgentClusterEnabled(); + // Normally for explicit opt-ins the origin is tracked when we create the + // SiteInstance, but there are two cases where that fails. (1) If process- + // isolation for OAC is not enabled we need to track opt-in here (used for + // origin-agent-cluster-by-default), and (2) if origin-keyed processes by + // default is enabled, then it's possible we got here due to using a + // speculative RenderFrameHost. In this latter case, the opt-in header had not + // arrived when the SiteInstance was created, so the origin was not tracked + // earlier. + bool is_opt_in_requested = IsOriginAgentClusterOptInRequested(); + bool explicitly_requests_origin_keyed_process = + is_opt_in_requested && + SiteIsolationPolicy::IsProcessIsolationForOriginAgentClusterEnabled(); // Since opt-outs are asking not to have OAC or requires_origin_keyed_process, // they don't get their own SiteInstance, and so we must register their @@ -3450,7 +3456,7 @@ policy->AddOriginIsolationStateForBrowsingInstance( isolation_context, origin, should_isolate_origin /* is_origin_agent_cluster */, - false /* requires_origin_keyed_process */); + explicitly_requests_origin_keyed_process); } bool NavigationRequest::IsOriginAgentClusterOptInRequested() {
diff --git a/content/browser/renderer_host/navigation_request.h b/content/browser/renderer_host/navigation_request.h index acd66c6..07fa2e2 100644 --- a/content/browser/renderer_host/navigation_request.h +++ b/content/browser/renderer_host/navigation_request.h
@@ -1004,13 +1004,19 @@ // 3) If the origin opts-out of OAC using a header, it will use a site-keyed // SiteInstance. // + // 4)If the origin opts-in to OAC using a header, but it is first placed in a + // speculative RenderFrameHost before the header is received, it creates a + // SiteInfo with default isolation and an origin-keyed process (by default). + // In this case, the origin was not tracked when the SiteInstance was created, + // and needs to be tracked later when the opt-in header is observed. + // // In all of these cases, this function updates the BrowsingInstance to keep // track of the OAC state for this NavigationRequest's origin. // // TODO(wjmaclean): Cases 1 and 2 will not be necessary once we use // origin-keyed SiteInstances within a site-keyed process, via - // SiteInstanceGroup. Case 3 will still be needed at that point, but might - // become simpler. + // SiteInstanceGroup. Cases 3 and 4 will still be needed at that point, but + // might become simpler. void AddOriginAgentClusterStateIfNecessary( const IsolationContext& isolation_context);
diff --git a/content/browser/renderer_host/render_process_host_impl.cc b/content/browser/renderer_host/render_process_host_impl.cc index acd1bee..4c2f58b 100644 --- a/content/browser/renderer_host/render_process_host_impl.cc +++ b/content/browser/renderer_host/render_process_host_impl.cc
@@ -3388,7 +3388,6 @@ switches::kDisableSpeechAPI, switches::kDisableThreadedCompositing, switches::kDisableTouchDragDrop, - switches::kDisableUseMojoVideoDecoderForPepper, switches::kDisableV8IdleTasks, switches::kDisableVideoCaptureUseGpuMemoryBuffer, switches::kDisableWebGLImageChromium,
diff --git a/content/browser/renderer_host/unassigned_site_instance_browsertest.cc b/content/browser/renderer_host/unassigned_site_instance_browsertest.cc index 32763fe..f5c90af 100644 --- a/content/browser/renderer_host/unassigned_site_instance_browsertest.cc +++ b/content/browser/renderer_host/unassigned_site_instance_browsertest.cc
@@ -889,13 +889,14 @@ EXPECT_EQ( ProcessLock::FromSiteInfo(SiteInfo( GURL("https://a.test"), GURL("https://a.test"), - false /* requires_origin_keyed_process */, false /* is_sandboxed */, - UrlInfo::kInvalidUniqueSandboxId, + /*requires_origin_keyed_process=*/false, + /*requires_origin_keyed_process_by_default=*/false, + /*is_sandboxed=*/false, UrlInfo::kInvalidUniqueSandboxId, StoragePartitionConfig::CreateDefault(browser_context), - WebExposedIsolationInfo::CreateNonIsolated(), false /* is_guest */, - false /* does_site_request_dedicated_process_for_coop */, - false /* is_jit_disabled */, false /* is_pdf */, - false /*is_fenced */)), + WebExposedIsolationInfo::CreateNonIsolated(), /*is_guest=*/false, + /*does_site_request_dedicated_process_for_coop=*/false, + /*is_jit_disabled=*/false, /*is_pdf=*/false, + /*is_fenced=*/false)), policy->GetProcessLock(process2->GetID())); // Ensure also that the regular url process didn't change midway through the
diff --git a/content/browser/resources/gpu/info_view.js b/content/browser/resources/gpu/info_view.js index 4e200eb..d73e17e 100644 --- a/content/browser/resources/gpu/info_view.js +++ b/content/browser/resources/gpu/info_view.js
@@ -292,6 +292,7 @@ 'direct_rendering_display_compositor': 'Direct Rendering Display Compositor', 'webgpu': 'WebGPU', + 'skia_graphite': 'Skia Graphite', }; const statusMap = {
diff --git a/content/browser/sandbox_parameters_mac.mm b/content/browser/sandbox_parameters_mac.mm index db062dc..03abc164 100644 --- a/content/browser/sandbox_parameters_mac.mm +++ b/content/browser/sandbox_parameters_mac.mm
@@ -6,11 +6,11 @@ #include <unistd.h> +#include "base/apple/bundle_locations.h" #include "base/check.h" #include "base/command_line.h" #include "base/feature_list.h" #include "base/files/file_util.h" -#include "base/mac/bundle_locations.h" #include "base/mac/foundation_util.h" #include "base/mac/mac_util.h" #include "base/no_destructor.h" @@ -104,11 +104,11 @@ sandbox::policy::kParamDisableSandboxDenialLogging, !enable_logging)); std::string bundle_path = - sandbox::policy::GetCanonicalPath(base::mac::MainBundlePath()).value(); + sandbox::policy::GetCanonicalPath(base::apple::MainBundlePath()).value(); CHECK(compiler->SetParameter(sandbox::policy::kParamBundlePath, bundle_path)); std::string bundle_id = base::mac::BaseBundleID(); - DCHECK(!bundle_id.empty()) << "base::mac::OuterBundle is unset"; + DCHECK(!bundle_id.empty()) << "base::apple::OuterBundle is unset"; CHECK(compiler->SetParameter(sandbox::policy::kParamBundleId, bundle_id)); CHECK(compiler->SetParameter(sandbox::policy::kParamBrowserPid, @@ -124,7 +124,7 @@ #if defined(COMPONENT_BUILD) // For component builds, allow access to one directory level higher, where // the dylibs live. - base::FilePath component_path = base::mac::MainBundlePath().Append(".."); + base::FilePath component_path = base::apple::MainBundlePath().Append(".."); std::string component_path_canonical = sandbox::policy::GetCanonicalPath(component_path).value(); CHECK(compiler->SetParameter(sandbox::policy::kParamComponentPath, @@ -182,7 +182,7 @@ SetupCommonSandboxParameters(compiler, command_line); base::FilePath bundle_path = - sandbox::policy::GetCanonicalPath(base::mac::MainBundlePath()); + sandbox::policy::GetCanonicalPath(base::apple::MainBundlePath()); const std::string param_base_name = "PPAPI_PATH_"; int index = 0;
diff --git a/content/browser/site_info.cc b/content/browser/site_info.cc index 68b2299..076ecea 100644 --- a/content/browser/site_info.cc +++ b/content/browser/site_info.cc
@@ -84,6 +84,7 @@ const WebExposedIsolationInfo& web_exposed_isolation_info) { return SiteInfo(GetErrorPageSiteAndLockURL(), GetErrorPageSiteAndLockURL(), false /* requires_origin_keyed_process */, + false /* requires_origin_keyed_process_by_default */, false /* is_sandboxed */, UrlInfo::kInvalidUniqueSandboxId, storage_partition_config, web_exposed_isolation_info, is_guest, @@ -103,14 +104,16 @@ bool is_jit_disabled = GetContentClient()->browser()->IsJitDisabledForSite( browser_context, GURL()); - return SiteInfo( - SiteInstanceImpl::GetDefaultSiteURL(), - SiteInstanceImpl::GetDefaultSiteURL(), - false /* requires_origin_keyed_process */, false /* is_sandboxed */, - UrlInfo::kInvalidUniqueSandboxId, storage_partition_config, - web_exposed_isolation_info, isolation_context.is_guest(), - false /* does_site_request_dedicated_process_for_coop */, is_jit_disabled, - false /* is_pdf */, isolation_context.is_fenced()); + return SiteInfo(SiteInstanceImpl::GetDefaultSiteURL(), + SiteInstanceImpl::GetDefaultSiteURL(), + /*requires_origin_keyed_process=*/false, + /*requires_origin_keyed_process_by_default=*/false, + /*is_sandboxed=*/false, UrlInfo::kInvalidUniqueSandboxId, + storage_partition_config, web_exposed_isolation_info, + isolation_context.is_guest(), + /*does_site_request_dedicated_process_for_coop=*/false, + is_jit_disabled, /*is_pdf=*/false, + isolation_context.is_fenced()); } // static @@ -125,12 +128,13 @@ // the guest will follow the normal process selection paths and use // SiteInstances with real site and lock URLs. return SiteInfo( - GURL(), GURL(), false /* requires_origin_keyed_process */, - false /* is_sandboxed */, UrlInfo::kInvalidUniqueSandboxId, + GURL(), GURL(), /*requires_origin_keyed_process=*/false, + /*requires_origin_keyed_process_by_default=*/false, + /*is_sandboxed=*/false, UrlInfo::kInvalidUniqueSandboxId, partition_config, WebExposedIsolationInfo::CreateNonIsolated(), - true /* is_guest */, - false /* does_site_request_dedicated_process_for_coop */, - false /* is_jit_disabled */, false /* is_pdf */, false /*is_fenced*/); + /*is_guest=*/true, + /*does_site_request_dedicated_process_for_coop=*/false, + /*is_jit_disabled=*/false, /*is_pdf=*/false, /*is_fenced=*/false); } // static @@ -227,6 +231,15 @@ requested_isolation_state) .requires_origin_keyed_process(); } + // If after the call to `DetermineOriginAgentClusterIsolation` the returned + // isolation state has `requires_origin_keyed_process() == true`, and if the + // requested `url_info` was for default isolation, then we know that + // `requires_origin_keyed_process` is true by default; we track that in + // `requires_origin_keyed_process_by_default` so that later we know not to + // add the isolation state to the per-BrowsingInstance tracking. + bool requires_origin_keyed_process_by_default = + requires_origin_keyed_process && + url_info.requests_default_origin_agent_cluster_isolation(); // If there is a COOP isolation request, propagate it to SiteInfo. // This will be used later when determining a suitable SiteInstance @@ -247,6 +260,7 @@ // appropriate to disregard WebExposedIsolationInfo and override it manually // to what they expect the other value to be. return SiteInfo(site_url, lock_url, requires_origin_keyed_process, + requires_origin_keyed_process_by_default, url_info.is_sandboxed, url_info.unique_sandbox_id, storage_partition_config.value(), url_info.web_exposed_isolation_info.value_or( @@ -265,6 +279,7 @@ SiteInfo::SiteInfo(const GURL& site_url, const GURL& process_lock_url, bool requires_origin_keyed_process, + bool requires_origin_keyed_process_by_default, bool is_sandboxed, int unique_sandbox_id, const StoragePartitionConfig storage_partition_config, @@ -277,6 +292,8 @@ : site_url_(site_url), process_lock_url_(process_lock_url), requires_origin_keyed_process_(requires_origin_keyed_process), + requires_origin_keyed_process_by_default_( + requires_origin_keyed_process_by_default), is_sandboxed_(is_sandboxed), unique_sandbox_id_(unique_sandbox_id), storage_partition_config_(storage_partition_config), @@ -289,6 +306,8 @@ is_fenced_(is_fenced) { DCHECK(is_sandboxed_ || unique_sandbox_id_ == UrlInfo::kInvalidUniqueSandboxId); + DCHECK(!requires_origin_keyed_process_by_default_ || + requires_origin_keyed_process_); } SiteInfo::SiteInfo(const SiteInfo& rhs) = default; @@ -299,6 +318,7 @@ /*site_url=*/GURL(), /*process_lock_url=*/GURL(), /*requires_origin_keyed_process=*/false, + /*requires_origin_keyed_process_by_default=*/false, /*is_sandboxed*/ false, UrlInfo::kInvalidUniqueSandboxId, StoragePartitionConfig::CreateDefault(browser_context),
diff --git a/content/browser/site_info.h b/content/browser/site_info.h index 9710b38..75e6a98 100644 --- a/content/browser/site_info.h +++ b/content/browser/site_info.h
@@ -137,6 +137,7 @@ SiteInfo(const GURL& site_url, const GURL& process_lock_url, bool requires_origin_keyed_process, + bool requires_origin_keyed_process_by_default, bool is_sandboxed, int unique_sandbox_id, const StoragePartitionConfig storage_partition_config, @@ -203,6 +204,13 @@ return requires_origin_keyed_process_; } + // If requires_origin_keyed_process() is true, this function indicates if the + // origin-keyed process is being used by default (e.g., via + // kOriginKeyedProcessesByDefault), rather than due to an opt-in OAC header. + bool requires_origin_keyed_process_by_default() const { + return requires_origin_keyed_process_by_default_; + } + // The following accessor is for the `is_sandboxed` flag, which is true when // this SiteInfo is for an origin-restricted-sandboxed iframe. bool is_sandboxed() const { return is_sandboxed_; } @@ -358,6 +366,15 @@ // do command-line isolated origins. bool requires_origin_keyed_process_ = false; + // When true, indicates that `requires_origin_keyed_process_` is true because + // this SiteInfo was created using origin-keyed processes by default, and not + // due to an opt-in header. + // Note: This is stored as a separate boolean instead of making + // requires_origin_keyed_process_ an enum due to complexity from std::tie + // comparisons, since we want two SiteInfos to be considered equivalent even + // if they differ in this boolean. + bool requires_origin_keyed_process_by_default_ = false; + // When true, indicates this SiteInfo is for a origin-restricted-sandboxed // iframe. bool is_sandboxed_ = false;
diff --git a/content/browser/site_instance_impl.cc b/content/browser/site_instance_impl.cc index 84e6de8..a54616d 100644 --- a/content/browser/site_instance_impl.cc +++ b/content/browser/site_instance_impl.cc
@@ -537,8 +537,10 @@ // BrowsingInstance can script each other. browsing_instance_->RegisterSiteInstance(this); - if (site_info_.requires_origin_keyed_process()) { - // Track this origin's isolation in the current BrowsingInstance. This is + if (site_info_.requires_origin_keyed_process() && + !site_info_.requires_origin_keyed_process_by_default()) { + // Track this origin's isolation in the current BrowsingInstance, if it has + // received an origin-keyed process due to an explicit opt-in. This is // needed to consistently isolate future navigations to this origin in this // BrowsingInstance, even if its opt-in status changes later. ChildProcessSecurityPolicyImpl* policy =
diff --git a/content/browser/site_instance_impl_unittest.cc b/content/browser/site_instance_impl_unittest.cc index bf50e539..e8d9a82 100644 --- a/content/browser/site_instance_impl_unittest.cc +++ b/content/browser/site_instance_impl_unittest.cc
@@ -68,12 +68,13 @@ bool requires_origin_keyed_process) { return SiteInfo( GURL("https://www.foo.com"), process_lock_url, - requires_origin_keyed_process, false /* is_sandboxed */, - UrlInfo::kInvalidUniqueSandboxId, + requires_origin_keyed_process, + /*requires_origin_keyed_process_by_default=*/false, + /*is_sandboxed=*/false, UrlInfo::kInvalidUniqueSandboxId, CreateStoragePartitionConfigForTesting(), - WebExposedIsolationInfo::CreateNonIsolated(), false /* is_guest */, - false /* does_site_request_dedicated_process_for_coop */, - false /* is_jit_disabled */, false /* is_pdf */, false /* is_fenced */); + WebExposedIsolationInfo::CreateNonIsolated(), /*is_guest=*/false, + /*does_site_request_dedicated_process_for_coop=*/false, + /*is_jit_disabled=*/false, /*is_pdf=*/false, /*is_fenced=*/false); } } // namespace @@ -277,51 +278,55 @@ auto site_info_1_with_isolation_request = SiteInfo( GURL("https://www.foo.com") /* site_url */, GURL("https://foo.com") /* process_lock_url */, - false /* requires_origin_keyed_process */, false /* is_sandboxed */, - UrlInfo::kInvalidUniqueSandboxId, + /*requires_origin_keyed_process=*/false, + /*requires_origin_keyed_process_by_default=*/false, + /*is_sandboxed=*/false, UrlInfo::kInvalidUniqueSandboxId, CreateStoragePartitionConfigForTesting(), - WebExposedIsolationInfo::CreateNonIsolated(), false /* is_guest */, - true /* does_site_request_dedicated_process_for_coop */, - false /* is_jit_disabled */, false /* is_pdf */, false /* is_fenced */); + WebExposedIsolationInfo::CreateNonIsolated(), /*is_guest=*/false, + /*does_site_request_dedicated_process_for_coop=*/true, + /*is_jit_disabled=*/false, /*is_pdf=*/false, /*is_fenced=*/false); EXPECT_TRUE( site_info_1.IsSamePrincipalWith(site_info_1_with_isolation_request)); EXPECT_EQ(site_info_1, site_info_1_with_isolation_request); // Check that SiteInfos with differing values of `is_jit_disabled` are not // considered same-principal. - auto site_info_1_with_jit_disabled = SiteInfo( - GURL("https://www.foo.com") /* site_url */, - GURL("https://foo.com") /* process_lock_url */, - false /* requires_origin_keyed_process */, false /* is_sandboxed */, - UrlInfo::kInvalidUniqueSandboxId, - CreateStoragePartitionConfigForTesting(), - WebExposedIsolationInfo::CreateNonIsolated(), false /* is_guest */, - false /* does_site_request_dedicated_process_for_coop */, - true /* is_jit_disabled */, false /* is_pdf */, false /* is_fenced */); + auto site_info_1_with_jit_disabled = + SiteInfo(GURL("https://www.foo.com") /* site_url */, + GURL("https://foo.com") /* process_lock_url */, + /*requires_origin_keyed_process=*/false, + /*requires_origin_keyed_process_by_default=*/false, + /*is_sandboxed=*/false, UrlInfo::kInvalidUniqueSandboxId, + CreateStoragePartitionConfigForTesting(), + WebExposedIsolationInfo::CreateNonIsolated(), /*is_guest=*/false, + /*does_site_request_dedicated_process_for_coop=*/false, + /*is_jit_disabled=*/true, /*is_pdf=*/false, /*is_fenced=*/false); EXPECT_FALSE(site_info_1.IsSamePrincipalWith(site_info_1_with_jit_disabled)); // Check that SiteInfos with differing values of `is_pdf` are not considered // same-principal. - auto site_info_1_with_pdf = SiteInfo( - GURL("https://www.foo.com") /* site_url */, - GURL("https://foo.com") /* process_lock_url */, - false /* requires_origin_keyed_process */, false /* is_sandboxed */, - UrlInfo::kInvalidUniqueSandboxId, - CreateStoragePartitionConfigForTesting(), - WebExposedIsolationInfo::CreateNonIsolated(), false /* is_guest */, - false /* does_site_request_dedicated_process_for_coop */, - false /* is_jit_disabled */, true /* is_pdf */, false /* is_fenced */); + auto site_info_1_with_pdf = + SiteInfo(GURL("https://www.foo.com") /* site_url */, + GURL("https://foo.com") /* process_lock_url */, + /*requires_origin_keyed_process=*/false, + /*requires_origin_keyed_process_by_default=*/false, + /*is_sandboxed=*/false, UrlInfo::kInvalidUniqueSandboxId, + CreateStoragePartitionConfigForTesting(), + WebExposedIsolationInfo::CreateNonIsolated(), /*is_guest=*/false, + /*does_site_request_dedicated_process_for_coop=*/false, + /*is_jit_disabled=*/false, /*is_pdf=*/true, /*is_fenced=*/false); EXPECT_FALSE(site_info_1.IsSamePrincipalWith(site_info_1_with_pdf)); - auto site_info_1_with_is_fenced = SiteInfo( - GURL("https://www.foo.com") /* site_url */, - GURL("https://foo.com") /* process_lock_url */, - false /* requires_origin_keyed_process */, false /* is_sandboxed */, - UrlInfo::kInvalidUniqueSandboxId, - CreateStoragePartitionConfigForTesting(), - WebExposedIsolationInfo::CreateNonIsolated(), false /* is_guest */, - false /* does_site_request_dedicated_process_for_coop */, - false /* is_jit_disabled */, false /* is_pdf */, true /* is_fenced */); + auto site_info_1_with_is_fenced = + SiteInfo(GURL("https://www.foo.com") /* site_url */, + GURL("https://foo.com") /* process_lock_url */, + /*requires_origin_keyed_process=*/false, + /*requires_origin_keyed_process_by_default=*/false, + /*is_sandboxed=*/false, UrlInfo::kInvalidUniqueSandboxId, + CreateStoragePartitionConfigForTesting(), + WebExposedIsolationInfo::CreateNonIsolated(), /*is_guest=*/false, + /*does_site_request_dedicated_process_for_coop=*/false, + /*is_jit_disabled=*/false, /*is_pdf=*/false, /*is_fenced=*/true); EXPECT_FALSE(site_info_1.IsSamePrincipalWith(site_info_1_with_is_fenced)); { @@ -770,12 +775,13 @@ SiteInfo expected_site_info( app_url /* site_url */, nonapp_site_url /* process_lock_url */, - false /* requires_origin_keyed_process */, false /* is_sandboxed */, - UrlInfo::kInvalidUniqueSandboxId, + /*requires_origin_keyed_process=*/false, + /*requires_origin_keyed_process_by_default=*/false, + /*is_sandboxed=*/false, UrlInfo::kInvalidUniqueSandboxId, CreateStoragePartitionConfigForTesting(), - WebExposedIsolationInfo::CreateNonIsolated(), false /* is_guest */, - false /* does_site_request_dedicated_process_for_coop */, - false /* is_jit_disabled */, false /* is_pdf */, false /* is_fenced */); + WebExposedIsolationInfo::CreateNonIsolated(), /*is_guest=*/false, + /*does_site_request_dedicated_process_for_coop=*/false, + /*is_jit_disabled=*/false, /*is_pdf=*/false, /*is_fenced=*/false); // New SiteInstance in a new BrowsingInstance with a predetermined URL. { @@ -1564,12 +1570,13 @@ SiteInfo expected_site_info( app_url /* site_url */, original_url /* process_lock_url */, - false /* requires_origin_keyed_process */, false /* is_sandboxed */, - UrlInfo::kInvalidUniqueSandboxId, + /*requires_origin_keyed_process=*/false, + /*requires_origin_keyed_process_by_default=*/false, + /*is_sandboxed=*/false, UrlInfo::kInvalidUniqueSandboxId, CreateStoragePartitionConfigForTesting(), - WebExposedIsolationInfo::CreateNonIsolated(), false /* is_guest */, - false /* does_site_request_dedicated_process_for_coop */, - false /* is_jit_disabled */, false /* is_pdf */, false /* is_fenced */); + WebExposedIsolationInfo::CreateNonIsolated(), /*is_guest=*/false, + /*does_site_request_dedicated_process_for_coop=*/false, + /*is_jit_disabled=*/false, /*is_pdf=*/false, /*is_fenced=*/false); // New SiteInstance in a new BrowsingInstance with a predetermined URL. In // this and subsequent cases, the site URL should consist of the effective @@ -1614,12 +1621,14 @@ ProcessLock ProcessLockFromString(const std::string& url) { return ProcessLock::FromSiteInfo(SiteInfo( - GURL(url), GURL(url), false /* requires_origin_keyed_process */, - false /* is_sandboxed */, UrlInfo::kInvalidUniqueSandboxId, + GURL(url), GURL(url), + /*requires_origin_keyed_process=*/false, + /*requires_origin_keyed_process_by_default=*/false, + /*is_sandboxed=*/false, UrlInfo::kInvalidUniqueSandboxId, CreateStoragePartitionConfigForTesting(), - WebExposedIsolationInfo::CreateNonIsolated(), false /* is_guest */, - false /* does_site_request_dedicated_process_for_coop */, - false /* is_jit_disabled */, false /* is_pdf */, false /* is_fenced */)); + WebExposedIsolationInfo::CreateNonIsolated(), /*is_guest=*/false, + /*does_site_request_dedicated_process_for_coop=*/false, + /*is_jit_disabled=*/false, /*is_pdf=*/false, /*is_fenced=*/false)); } } // namespace
diff --git a/content/child/BUILD.gn b/content/child/BUILD.gn index 16492e4..2a07e58 100644 --- a/content/child/BUILD.gn +++ b/content/child/BUILD.gn
@@ -142,10 +142,6 @@ libs = [ "dwrite.lib" ] } - if (is_apple) { - deps += [ "//base:base_arc" ] - } - if (is_mac) { sources += [ "child_process_sandbox_support_impl_mac.cc",
diff --git a/content/common/BUILD.gn b/content/common/BUILD.gn index ea1582c..3221529 100644 --- a/content/common/BUILD.gn +++ b/content/common/BUILD.gn
@@ -136,7 +136,6 @@ "input/web_touch_event_traits.cc", "input/web_touch_event_traits.h", "media/cdm_info.cc", - "media/constants.h", "mojo_core_library_support.cc", "mojo_core_library_support.h", "navigation_gesture.h",
diff --git a/content/common/content_paths.cc b/content/common/content_paths.cc index 50ae46a..673db07 100644 --- a/content/common/content_paths.cc +++ b/content/common/content_paths.cc
@@ -9,7 +9,7 @@ #include "build/build_config.h" #if BUILDFLAG(IS_MAC) -#include "base/mac/bundle_locations.h" +#include "base/apple/bundle_locations.h" #endif namespace content {
diff --git a/content/common/media/constants.h b/content/common/media/constants.h deleted file mode 100644 index 928c565..0000000 --- a/content/common/media/constants.h +++ /dev/null
@@ -1,24 +0,0 @@ -// Copyright 2023 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_COMMON_MEDIA_CONSTANTS_H_ -#define CONTENT_COMMON_MEDIA_CONSTANTS_H_ - -#include "build/build_config.h" - -namespace content { - -// Default value for -// RenderFrameMediaPlaybackOptions::is_background_suspend_enabled is determined -// statically in Chromium, but some content embedders (e.g. Cast) may need to -// change it at runtime. -#if BUILDFLAG(IS_ANDROID) -const bool kIsBackgroundMediaSuspendEnabled = true; -#else -const bool kIsBackgroundMediaSuspendEnabled = false; -#endif - -} // namespace content - -#endif // CONTENT_COMMON_MEDIA_CONSTANTS_H_
diff --git a/content/public/renderer/render_frame_media_playback_options.h b/content/public/renderer/render_frame_media_playback_options.h index b4f000c0..8f22240 100644 --- a/content/public/renderer/render_frame_media_playback_options.h +++ b/content/public/renderer/render_frame_media_playback_options.h
@@ -5,11 +5,20 @@ #ifndef CONTENT_PUBLIC_RENDERER_RENDER_FRAME_MEDIA_PLAYBACK_OPTIONS_H_ #define CONTENT_PUBLIC_RENDERER_RENDER_FRAME_MEDIA_PLAYBACK_OPTIONS_H_ -#include "content/common/media/constants.h" +#include "build/build_config.h" #include "content/public/common/media_playback_renderer_type.mojom.h" namespace content { +// Default value for is_background_suspend_enabled is determined statically in +// Chromium, but some content embedders (e.g. Cast) may need to change it at +// runtime. +#if BUILDFLAG(IS_ANDROID) +const bool kIsBackgroundMediaSuspendEnabled = true; +#else +const bool kIsBackgroundMediaSuspendEnabled = false; +#endif + struct RenderFrameMediaPlaybackOptions { // Whether the renderer should automatically suspend media playback on // background tabs for given |render_frame|.
diff --git a/content/public/test/README.md b/content/public/test/README.md index e6bbaf1..bbee390 100644 --- a/content/public/test/README.md +++ b/content/public/test/README.md
@@ -194,7 +194,6 @@ } ``` - ## Simulating a slow load Navigates to a page that takes 60 seconds to load. @@ -207,6 +206,20 @@ The embedded test server also registers [other default handlers][test-server-default-handlers] that may be useful. +## Simulating a failed navigation + +Note that this is distinct from a navigation that results in an HTTP error, +since those navigations still load arbitrary HTML from the server-supplied error +page; a failed navigation is one that results in committing a Chrome-supplied +error page, i.e. `RenderFrameHost::IsErrorDocument()` returns `true`. + +```c++ + GURL url = embedded_test_server()->GetURL("/title1.html"); + std::unique_ptr<URLLoaderInterceptor> url_interceptor = + URLLoaderInterceptor::SetupRequestFailForURL(url, net::ERR_DNS_TIMED_OUT); + EXPECT_FALSE(NavigateToURLFromRenderer(web_contents, url)); +``` + [host-resolver-config]: README.md#Cross_origin-navigations [cross-site-iframe-factory]: https://source.chromium.org/chromium/chromium/src/+/main:content/test/data/cross_site_iframe_factory.html [test-server-default-handlers]: https://source.chromium.org/chromium/chromium/src/+/main:net/test/embedded_test_server/default_handlers.cc
diff --git a/content/public/test/android/BUILD.gn b/content/public/test/android/BUILD.gn index 23b3e99..c901125 100644 --- a/content/public/test/android/BUILD.gn +++ b/content/public/test/android/BUILD.gn
@@ -28,6 +28,7 @@ "//content/public/android:content_java", "//mojo/public/java:bindings_java", "//net/android:net_java", + "//net/android:net_java_test_support", "//services/service_manager/public/java:service_manager_java", "//third_party/androidx:androidx_annotation_annotation_java", "//third_party/androidx:androidx_test_monitor_java",
diff --git a/content/public/test/android/javatests/src/org/chromium/content_public/browser/test/ContentJUnit4ClassRunner.java b/content/public/test/android/javatests/src/org/chromium/content_public/browser/test/ContentJUnit4ClassRunner.java index 6c3d062e..5e50ae8b 100644 --- a/content/public/test/android/javatests/src/org/chromium/content_public/browser/test/ContentJUnit4ClassRunner.java +++ b/content/public/test/android/javatests/src/org/chromium/content_public/browser/test/ContentJUnit4ClassRunner.java
@@ -10,6 +10,7 @@ import org.chromium.base.test.BaseJUnit4ClassRunner; import org.chromium.base.test.util.SkipCheck; +import org.chromium.net.test.EmbeddedTestServer; import org.chromium.ui.test.util.DeviceRestrictionSkipCheck; import org.chromium.ui.test.util.UiDisableIfSkipCheck; import org.chromium.ui.test.util.UiRestrictionSkipCheck; @@ -44,4 +45,9 @@ protected List<TestHook> getPreTestHooks() { return addToList(super.getPreTestHooks(), new ChildProcessAllocatorSettingsHook()); } + + @Override + protected List<ClassHook> getPreClassHooks() { + return addToList(super.getPreClassHooks(), EmbeddedTestServer.getPreClassHook()); + } }
diff --git a/content/renderer/pepper/pepper_video_decoder_host.cc b/content/renderer/pepper/pepper_video_decoder_host.cc index e676c55..af0cbf31 100644 --- a/content/renderer/pepper/pepper_video_decoder_host.cc +++ b/content/renderer/pepper/pepper_video_decoder_host.cc
@@ -23,7 +23,6 @@ #include "content/renderer/pepper/video_decoder_shim.h" #include "gpu/ipc/client/command_buffer_proxy_impl.h" #include "media/base/limits.h" -#include "media/base/media_switches.h" #include "media/base/media_util.h" #include "media/gpu/ipc/client/gpu_video_decode_accelerator_host.h" #include "media/video/video_decode_accelerator.h" @@ -110,20 +109,6 @@ } // namespace -bool ShouldUseMojoVideoDecoderForPepper() { - if (base::CommandLine::ForCurrentProcess()->HasSwitch( - switches::kDisableUseMojoVideoDecoderForPepper)) { - LOG(WARNING) << "UseMojoVideoDecoderForPepper: Disabled by policy"; - return false; - } - - auto enabled = - base::FeatureList::IsEnabled(media::kUseMojoVideoDecoderForPepper); - LOG(WARNING) << "UseMojoVideoDecoderForPepper: feature controlled: " - << enabled; - return enabled; -} - PepperVideoDecoderHost::PendingDecode::PendingDecode( int32_t decode_id, uint32_t shm_id, @@ -154,31 +139,17 @@ renderer_ppapi_host_(host) {} PepperVideoDecoderHost::~PepperVideoDecoderHost() { - DCHECK(!(legacy_hardware_video_decoder_path_initialized_ && - mojo_video_decoder_path_initialized_)); - auto hw_behavior = HardwareAccelerationBehavior::kOther; if (software_fallback_used_) { - if (!legacy_hardware_video_decoder_path_initialized_ && - !mojo_video_decoder_path_initialized_) { - hw_behavior = HardwareAccelerationBehavior::kSoftwareDecoderOnly; - } else if (legacy_hardware_video_decoder_path_initialized_) { - hw_behavior = HardwareAccelerationBehavior:: - kHardwareDecoderWithoutMojoVideoDecoderAndThenSoftwareDecoder; - } else if (mojo_video_decoder_path_initialized_) { + if (mojo_video_decoder_path_initialized_) { hw_behavior = HardwareAccelerationBehavior:: kHardwareDecoderWithMojoVideoDecoderAndThenSoftwareDecoder; } else { - NOTREACHED(); + hw_behavior = HardwareAccelerationBehavior::kSoftwareDecoderOnly; } - } else { - if (legacy_hardware_video_decoder_path_initialized_) { - hw_behavior = HardwareAccelerationBehavior:: - kHardwareDecoderOnlyWithoutMojoVideoDecoder; - } else if (mojo_video_decoder_path_initialized_) { - hw_behavior = HardwareAccelerationBehavior:: - kHardwareDecoderOnlyWithMojoVideoDecoder; - } + } else if (mojo_video_decoder_path_initialized_) { + hw_behavior = + HardwareAccelerationBehavior::kHardwareDecoderOnlyWithMojoVideoDecoder; } base::UmaHistogramEnumeration( @@ -236,36 +207,20 @@ min_picture_count_ = min_picture_count; if (acceleration != PP_HARDWAREACCELERATION_NONE) { - if (!ShouldUseMojoVideoDecoderForPepper()) { - // This is not synchronous, but subsequent IPC messages will be buffered, - // so it is okay to immediately send IPC messages. - if (command_buffer->channel()) { - decoder_ = base::WrapUnique<media::VideoDecodeAccelerator>( - new media::GpuVideoDecodeAcceleratorHost(command_buffer)); - media::VideoDecodeAccelerator::Config vda_config(profile_); - vda_config.supported_output_formats.assign( - {media::PIXEL_FORMAT_XRGB, media::PIXEL_FORMAT_ARGB}); - if (decoder_->Initialize(vda_config, this)) { - initialized_ = true; - legacy_hardware_video_decoder_path_initialized_ = true; - return PP_OK; - } - } - } else { - uint32_t shim_texture_pool_size = media::limits::kMaxVideoFrames + 1; - shim_texture_pool_size = - std::max(shim_texture_pool_size, min_picture_count_); - auto new_decoder = VideoDecoderShim::Create(this, shim_texture_pool_size, - /*use_hw_decoder=*/true); - if (new_decoder && - new_decoder->Initialize( - media::VideoDecodeAccelerator::Config(profile_), this)) { - decoder_.reset(new_decoder.release()); - initialized_ = true; - mojo_video_decoder_path_initialized_ = true; - return PP_OK; - } + uint32_t shim_texture_pool_size = media::limits::kMaxVideoFrames + 1; + shim_texture_pool_size = + std::max(shim_texture_pool_size, min_picture_count_); + auto new_decoder = VideoDecoderShim::Create(this, shim_texture_pool_size, + /*use_hw_decoder=*/true); + if (new_decoder && + new_decoder->Initialize(media::VideoDecodeAccelerator::Config(profile_), + this)) { + decoder_.reset(new_decoder.release()); + initialized_ = true; + mojo_video_decoder_path_initialized_ = true; + return PP_OK; } + decoder_.reset(); if (acceleration == PP_HARDWAREACCELERATION_ONLY) return PP_ERROR_NOTSUPPORTED;
diff --git a/content/renderer/pepper/pepper_video_decoder_host.h b/content/renderer/pepper/pepper_video_decoder_host.h index efdb05c6..79b1c7b 100644 --- a/content/renderer/pepper/pepper_video_decoder_host.h +++ b/content/renderer/pepper/pepper_video_decoder_host.h
@@ -135,7 +135,6 @@ bool software_fallback_used_ = false; // Used to record UMA values. - bool legacy_hardware_video_decoder_path_initialized_ = false; bool mojo_video_decoder_path_initialized_ = false; // Used for UMA stats; not frame-accurate.
diff --git a/content/renderer/pepper/video_decoder_shim.cc b/content/renderer/pepper/video_decoder_shim.cc index 7a63199f..834dba8 100644 --- a/content/renderer/pepper/video_decoder_shim.cc +++ b/content/renderer/pepper/video_decoder_shim.cc
@@ -219,7 +219,6 @@ media::VideoDecoderConfig config, media::GpuVideoAcceleratorFactories* gpu_factories) { DCHECK(use_hw_decoder_); - CHECK(ShouldUseMojoVideoDecoderForPepper()); DCHECK(gpu_factories->GetTaskRunner()->RunsTasksInCurrentSequence()); if (!gpu_factories->IsGpuVideoDecodeAcceleratorEnabled()) { @@ -289,14 +288,6 @@ } void VideoDecoderShim::DecoderImpl::Stop() { - // This DCHECK was not valid even before introducing the - // media::kUseMojoVideoDecoderForPepper path. However we keep it here because - // we don't want to change anything about the previous codepath as part of - // introducing the new flag-guarded codepath. - if (!ShouldUseMojoVideoDecoderForPepper()) { - DCHECK(decoder_); - } - // Clear pending decodes now. We don't want OnDecodeComplete to call DoDecode // again. while (!pending_decodes_.empty()) @@ -416,8 +407,7 @@ scoped_refptr<viz::ContextProviderCommandBuffer> shared_main_thread_context_provider = RenderThreadImpl::current()->SharedMainThreadContextProvider(); - if (ShouldUseMojoVideoDecoderForPepper() && - !shared_main_thread_context_provider) { + if (!shared_main_thread_context_provider) { return nullptr; } @@ -455,7 +445,6 @@ texture_pool_size_(texture_pool_size), num_pending_decodes_(0), use_hw_decoder_(use_hw_decoder) { - CHECK(!use_hw_decoder_ || ShouldUseMojoVideoDecoderForPepper()); DCHECK(host_); DCHECK(media_task_runner_.get()); DCHECK(shared_main_thread_context_provider_.get());
diff --git a/content/renderer/sandbox_mac_v2_unittest.mm b/content/renderer/sandbox_mac_v2_unittest.mm index 3290f30..e73e0dc4 100644 --- a/content/renderer/sandbox_mac_v2_unittest.mm +++ b/content/renderer/sandbox_mac_v2_unittest.mm
@@ -13,9 +13,9 @@ #include <sys/types.h> #include <unistd.h> +#include "base/apple/bundle_locations.h" #include "base/files/file_util.h" #include "base/files/scoped_temp_dir.h" -#include "base/mac/bundle_locations.h" #include "base/mac/mac_util.h" #include "base/process/kill.h" #include "base/system/sys_info.h" @@ -57,7 +57,7 @@ base::NumberToString(os_version))); std::string bundle_path = - sandbox::policy::GetCanonicalPath(base::mac::MainBundlePath()).value(); + sandbox::policy::GetCanonicalPath(base::apple::MainBundlePath()).value(); CHECK(compiler->SetParameter(sandbox::policy::kParamBundlePath, bundle_path)); CHECK(compiler->SetParameter(sandbox::policy::kParamBundleId, @@ -139,7 +139,7 @@ CHECK_NE(BOOTSTRAP_SUCCESS, status); // Read bundle contents. - base::FilePath bundle_path = base::mac::MainBundlePath(); + base::FilePath bundle_path = base::apple::MainBundlePath(); struct stat st; CHECK_NE(-1, stat(bundle_path.value().c_str(), &st));
diff --git a/content/shell/app/paths_mac.h b/content/shell/app/paths_mac.h index d2d1783..7c210fe 100644 --- a/content/shell/app/paths_mac.h +++ b/content/shell/app/paths_mac.h
@@ -9,10 +9,10 @@ class FilePath; } -// Sets up base::mac::FrameworkBundle. +// Sets up base::apple::FrameworkBundle. void OverrideFrameworkBundlePath(); -// Set up base::mac::OuterBundle. +// Set up base::apple::OuterBundle. void OverrideOuterBundlePath(); // Sets up the CHILD_PROCESS_EXE path to properly point to the helper app.
diff --git a/content/shell/app/paths_mac.mm b/content/shell/app/paths_mac.mm index 949e921..61668c7 100644 --- a/content/shell/app/paths_mac.mm +++ b/content/shell/app/paths_mac.mm
@@ -4,8 +4,8 @@ #include "content/shell/app/paths_mac.h" +#include "base/apple/bundle_locations.h" #include "base/base_paths.h" -#include "base/mac/bundle_locations.h" #include "base/mac/foundation_util.h" #include "base/path_service.h" #include "content/public/common/content_paths.h" @@ -52,17 +52,17 @@ base::FilePath helper_path = GetFrameworksPath().Append("Content Shell Framework.framework"); - base::mac::SetOverrideFrameworkBundlePath(helper_path); + base::apple::SetOverrideFrameworkBundlePath(helper_path); } void OverrideOuterBundlePath() { base::FilePath path = GetContentsPath().DirName(); - base::mac::SetOverrideOuterBundlePath(path); + base::apple::SetOverrideOuterBundlePath(path); } void OverrideChildProcessPath() { - base::FilePath helper_path = base::mac::FrameworkBundlePath() + base::FilePath helper_path = base::apple::FrameworkBundlePath() .Append("Helpers") .Append("Content Shell Helper.app") .Append("Contents") @@ -85,8 +85,8 @@ base::FilePath GetResourcesPakFilePath() { NSString* pak_path = - [base::mac::FrameworkBundle() pathForResource:@"content_shell" - ofType:@"pak"]; + [base::apple::FrameworkBundle() pathForResource:@"content_shell" + ofType:@"pak"]; return base::FilePath([pak_path fileSystemRepresentation]); }
diff --git a/content/shell/app/shell_main_delegate_mac.mm b/content/shell/app/shell_main_delegate_mac.mm index 9e41081a..17241d65 100644 --- a/content/shell/app/shell_main_delegate_mac.mm +++ b/content/shell/app/shell_main_delegate_mac.mm
@@ -6,10 +6,10 @@ #include <unistd.h> +#include "base/apple/bundle_locations.h" #include "base/check.h" #include "base/command_line.h" #include "base/files/file_path.h" -#include "base/mac/bundle_locations.h" #include "base/mac/foundation_util.h" #include "base/strings/sys_string_conversions.h" #include "content/public/common/content_switches.h" @@ -62,7 +62,7 @@ } void OverrideBundleID() { - NSBundle* bundle = base::mac::OuterBundle(); + NSBundle* bundle = base::apple::OuterBundle(); base::mac::SetBaseBundleID( base::SysNSStringToUTF8([bundle bundleIdentifier]).c_str()); }
diff --git a/content/shell/browser/shell_browser_main_parts_mac.mm b/content/shell/browser/shell_browser_main_parts_mac.mm index 644c1d0..4571366 100644 --- a/content/shell/browser/shell_browser_main_parts_mac.mm +++ b/content/shell/browser/shell_browser_main_parts_mac.mm
@@ -6,7 +6,7 @@ #import <Cocoa/Cocoa.h> -#include "base/mac/bundle_locations.h" +#include "base/apple/bundle_locations.h" #if !defined(__has_feature) || !__has_feature(objc_arc) #error "This file requires ARC support."
diff --git a/content/test/BUILD.gn b/content/test/BUILD.gn index 7a7ead5..29333e0b 100644 --- a/content/test/BUILD.gn +++ b/content/test/BUILD.gn
@@ -1411,6 +1411,7 @@ "../browser/portal/portal_navigation_throttle_browsertest.cc", "../browser/power_monitor_browsertest.cc", "../browser/preloading/anchor_element_interaction_browsertest.cc", + "../browser/preloading/preloading_decider_browsertest.cc", "../browser/preloading/prerender/prerender_browsertest.cc", "../browser/process_internals/process_internals_browsertest.cc", "../browser/quota/quota_browsertest.cc",
diff --git a/content/test/content_test_bundle_data.filelist b/content/test/content_test_bundle_data.filelist index da5d465..8599d8a 100644 --- a/content/test/content_test_bundle_data.filelist +++ b/content/test/content_test_bundle_data.filelist
@@ -3774,6 +3774,9 @@ data/accessibility/html/link-inside-heading-expected-uia-win.txt data/accessibility/html/link-inside-heading-expected-win.txt data/accessibility/html/link-inside-heading.html +data/accessibility/html/link-target-expected-auralinux.txt +data/accessibility/html/link-target-expected-win.txt +data/accessibility/html/link-target.html data/accessibility/html/link.html data/accessibility/html/list-expected-android-external.txt data/accessibility/html/list-expected-android.txt @@ -6398,6 +6401,7 @@ data/portals/touch-input-transfer-across-reactivation.html data/post_message.html data/post_message2.html +data/preloading/preloading_decider.html data/prerender/cross_origin_prerender.html data/prerender/doc-with-display-none-iframe.html data/prerender/duplicate_prerenders.html
diff --git a/content/test/data/accessibility/html/link-target-expected-auralinux.txt b/content/test/data/accessibility/html/link-target-expected-auralinux.txt new file mode 100644 index 0000000..e69de29 --- /dev/null +++ b/content/test/data/accessibility/html/link-target-expected-auralinux.txt
diff --git a/content/test/data/accessibility/html/link-target-expected-win.txt b/content/test/data/accessibility/html/link-target-expected-win.txt new file mode 100644 index 0000000..e69de29 --- /dev/null +++ b/content/test/data/accessibility/html/link-target-expected-win.txt
diff --git a/content/test/data/accessibility/html/link-target.html b/content/test/data/accessibility/html/link-target.html new file mode 100644 index 0000000..05e8154 --- /dev/null +++ b/content/test/data/accessibility/html/link-target.html
@@ -0,0 +1,31 @@ +<!DOCTYPE html> +<!-- + @AURALINUX-ALLOW:*link-target* + @WIN-ALLOW:*link-target* +--> +<html> + <head> + <base target="top"> + </head> + <body> + <p>Top context.</p> + <iframe name="iframeContext" srcdoc=" + <p>First context.</p> + <a href='http://example.com/' target='self'> + Self target. Opens in this iframe. + </a> + <a href='http://example.com/' target='parent'> + Parent target. Opens in the body of the whole page. + </a> + "></iframe> + <a href="http://example.com/"> + Base target. Open in blank. + </a> + <a href="http://example.com/" target="top"> + Top target. Opens in current context. + </a> + <a href="http://example.com/" target="iframeContext"> + Opens in iframe. + </a> + </body> +</html> \ No newline at end of file
diff --git a/content/test/data/preloading/preloading_decider.html b/content/test/data/preloading/preloading_decider.html new file mode 100644 index 0000000..d314b38 --- /dev/null +++ b/content/test/data/preloading/preloading_decider.html
@@ -0,0 +1,20 @@ +<!DOCTYPE html> +<html lang="en"> +<head> + <meta charset="UTF-8"> + <meta http-equiv="X-UA-Compatible" content="IE=edge"> + <meta name="viewport" content="width=device-width, initial-scale=1.0"> + <title>Preloading Decider Browser Test</title> +</head> +<body> + <script type="speculationrules"> + { + "prefetch":[ + {"source":"list", "urls":["/preloading/preloading_decider.html?foo"]} + ] + } + </script> + <a href="/preloading/preloading_decider.html?foo" id="foo"><div style="width:100vw;height:50vh;">Foo<div></a> + <a href="/preloading/preloading_decider.html?bar" id="bar"><div style="width:100vw;height:50vh;">Bar<div></a> +</body> +</html> \ No newline at end of file
diff --git a/content/web_test/renderer/blink_test_helpers.cc b/content/web_test/renderer/blink_test_helpers.cc index 762daa72..d49608eb 100644 --- a/content/web_test/renderer/blink_test_helpers.cc +++ b/content/web_test/renderer/blink_test_helpers.cc
@@ -19,7 +19,7 @@ #include "ui/display/display.h" #if BUILDFLAG(IS_MAC) -#include "base/mac/bundle_locations.h" +#include "base/apple/bundle_locations.h" #include "base/mac/foundation_util.h" #endif @@ -113,7 +113,7 @@ if (base::mac::AmIBundled()) { // If this is a bundled Content Shell.app, go up one from the outer bundle // directory. - return base::mac::OuterBundlePath().DirName(); + return base::apple::OuterBundlePath().DirName(); } #endif
diff --git a/extensions/browser/api/content_settings/content_settings_store.cc b/extensions/browser/api/content_settings/content_settings_store.cc index 6faade45..9f9f0409 100644 --- a/extensions/browser/api/content_settings/content_settings_store.cc +++ b/extensions/browser/api/content_settings/content_settings_store.cc
@@ -70,10 +70,7 @@ bool incognito) const { std::vector<std::unique_ptr<RuleIterator>> iterators; - // The individual |RuleIterators| shouldn't lock; pass |lock_| to the - // |ConcatenationIterator| in a locked state. - std::unique_ptr<base::AutoLock> auto_lock = - std::make_unique<base::AutoLock>(lock_); + base::AutoLock auto_lock(lock_); // Iterate the extensions based on install time (most-recently installed // items first). @@ -83,16 +80,14 @@ std::unique_ptr<RuleIterator> rule_it; if (incognito) { - rule_it = - entry->incognito_session_only_settings.GetRuleIterator(type, nullptr); + rule_it = entry->incognito_session_only_settings.GetRuleIterator(type); if (rule_it) iterators.push_back(std::move(rule_it)); - rule_it = - entry->incognito_persistent_settings.GetRuleIterator(type, nullptr); + rule_it = entry->incognito_persistent_settings.GetRuleIterator(type); if (rule_it) iterators.push_back(std::move(rule_it)); } else { - rule_it = entry->settings.GetRuleIterator(type, nullptr); + rule_it = entry->settings.GetRuleIterator(type); if (rule_it) iterators.push_back(std::move(rule_it)); } @@ -100,8 +95,7 @@ if (iterators.empty()) return nullptr; - return std::make_unique<ConcatenationIterator>(std::move(iterators), - auto_lock.release()); + return std::make_unique<ConcatenationIterator>(std::move(iterators)); } void ContentSettingsStore::SetExtensionContentSetting( @@ -114,6 +108,7 @@ { base::AutoLock lock(lock_); OriginIdentifierValueMap* map = GetValueMap(ext_id, scope); + base::AutoLock map_lock(map->GetLock()); if (setting == CONTENT_SETTING_DEFAULT) { map->DeleteValue(primary_pattern, secondary_pattern, type); } else { @@ -167,10 +162,8 @@ auto i = FindIterator(ext_id); if (i == entries_.end()) return; - notify = !(*i)->settings.empty(); - notify_incognito = !(*i)->incognito_persistent_settings.empty() || - !(*i)->incognito_session_only_settings.empty(); + ShouldNotifyForEntry(**i, ¬ify, ¬ify_incognito); entries_.erase(i); } if (notify) @@ -179,6 +172,23 @@ NotifyOfContentSettingChanged(ext_id, true); } +void ContentSettingsStore::ShouldNotifyForEntry(const ExtensionEntry& entry, + bool* notify, + bool* notify_incognito) { + { + base::AutoLock map_lock(entry.settings.GetLock()); + *notify = !entry.settings.empty(); + } + { + base::AutoLock map_lock(entry.incognito_persistent_settings.GetLock()); + *notify_incognito = !entry.incognito_persistent_settings.empty(); + } + if (!*notify_incognito) { + base::AutoLock map_lock(entry.incognito_session_only_settings.GetLock()); + *notify_incognito = !entry.incognito_session_only_settings.empty(); + } +} + void ContentSettingsStore::SetExtensionState( const std::string& ext_id, bool is_enabled) { bool notify = false; @@ -189,10 +199,7 @@ if (!entry) return; - notify = !entry->settings.empty(); - notify_incognito = !entry->incognito_persistent_settings.empty() || - !entry->incognito_session_only_settings.empty(); - + ShouldNotifyForEntry(*entry, ¬ify, ¬ify_incognito); entry->enabled = is_enabled; } if (notify) @@ -242,6 +249,7 @@ base::AutoLock lock(lock_); OriginIdentifierValueMap* map = GetValueMap(ext_id, scope); DCHECK(map); + base::AutoLock map_lock(map->GetLock()); notify = !map->empty(); map->clear(); } @@ -259,6 +267,7 @@ OriginIdentifierValueMap* map = GetValueMap(ext_id, scope); DCHECK(map); + base::AutoLock map_lock(map->GetLock()); if (map->find(content_type) == map->end()) return; @@ -274,13 +283,21 @@ const OriginIdentifierValueMap* map = GetValueMap(extension_id, scope); if (!map) return {}; - + std::vector<ContentSettingsType> keys; + { + // Grab the set of keys first as OriginIdentifierValueMap::GetRuleIterator + // requires that the lock isn't already held. + base::AutoLock map_lock(map->GetLock()); + // Range-based for loops break locking annotations. + // https://github.com/llvm/llvm-project/issues/62497 + // NOLINTNEXTLINE(modernize-loop-convert) + for (auto it = map->begin(); it != map->end(); it++) { + keys.push_back(it->first); + } + } base::Value::List settings; - for (const auto& it : *map) { - const auto& key = it.first; - std::unique_ptr<RuleIterator> rule_iterator( - map->GetRuleIterator(key, - nullptr)); // We already hold the lock. + for (ContentSettingsType key : keys) { + std::unique_ptr<RuleIterator> rule_iterator(map->GetRuleIterator(key)); if (!rule_iterator) continue;
diff --git a/extensions/browser/api/content_settings/content_settings_store.h b/extensions/browser/api/content_settings/content_settings_store.h index 063a36d4..29a1898 100644 --- a/extensions/browser/api/content_settings/content_settings_store.h +++ b/extensions/browser/api/content_settings/content_settings_store.h
@@ -130,22 +130,28 @@ content_settings::OriginIdentifierValueMap* GetValueMap( const std::string& ext_id, - ExtensionPrefsScope scope); + ExtensionPrefsScope scope) EXCLUSIVE_LOCKS_REQUIRED(lock_); const content_settings::OriginIdentifierValueMap* GetValueMap( const std::string& ext_id, - ExtensionPrefsScope scope) const; + ExtensionPrefsScope scope) const EXCLUSIVE_LOCKS_REQUIRED(lock_); void NotifyOfContentSettingChanged(const std::string& extension_id, bool incognito); bool OnCorrectThread(); - ExtensionEntry* FindEntry(const std::string& ext_id) const; - ExtensionEntries::iterator FindIterator(const std::string& ext_id); + ExtensionEntry* FindEntry(const std::string& ext_id) const + EXCLUSIVE_LOCKS_REQUIRED(lock_); + ExtensionEntries::iterator FindIterator(const std::string& ext_id) + EXCLUSIVE_LOCKS_REQUIRED(lock_); + + void ShouldNotifyForEntry(const ExtensionEntry& entry, + bool* notify, + bool* notify_incognito); // The entries. - ExtensionEntries entries_; + ExtensionEntries entries_ GUARDED_BY(lock_); base::ObserverList<Observer, false>::Unchecked observers_;
diff --git a/google_apis/google_api_keys_mac.mm b/google_apis/google_api_keys_mac.mm index 8b98a00..6d9d0c2 100644 --- a/google_apis/google_api_keys_mac.mm +++ b/google_apis/google_api_keys_mac.mm
@@ -6,7 +6,7 @@ #import <Foundation/Foundation.h> -#include "base/mac/bundle_locations.h" +#include "base/apple/bundle_locations.h" #include "base/mac/foundation_util.h" #include "base/strings/sys_string_conversions.h" @@ -19,7 +19,7 @@ std::string GetAPIKeyFromInfoPlist(const std::string& key_name) { NSString* keyName = base::SysUTF8ToNSString(key_name); NSString* keyValue = base::mac::ObjCCast<NSString>( - [base::mac::FrameworkBundle() objectForInfoDictionaryKey:keyName]); + [base::apple::FrameworkBundle() objectForInfoDictionaryKey:keyName]); return base::SysNSStringToUTF8(keyValue); }
diff --git a/google_apis/google_api_keys_mac_unittest.mm b/google_apis/google_api_keys_mac_unittest.mm index 903620d..74b54a2 100644 --- a/google_apis/google_api_keys_mac_unittest.mm +++ b/google_apis/google_api_keys_mac_unittest.mm
@@ -12,7 +12,7 @@ #include "google_apis/google_api_keys_unittest.h" -#include "base/mac/bundle_locations.h" +#include "base/apple/bundle_locations.h" #include "build/branding_buildflags.h" #include "build/build_config.h" #include "google_apis/gaia/gaia_switches.h" @@ -89,13 +89,13 @@ [[[mock_bundle stub] andReturn:@"plist-ID_MAIN"] objectForInfoDictionaryKey:@"GOOGLE_CLIENT_ID_MAIN"]; [[[mock_bundle stub] andReturn:nil] objectForInfoDictionaryKey:[OCMArg any]]; - base::mac::SetOverrideFrameworkBundle(mock_bundle); + base::apple::SetOverrideFrameworkBundle(mock_bundle); EXPECT_TRUE(testcase::HasAPIKeyConfigured()); EXPECT_TRUE(testcase::HasOAuthClientConfigured()); // Once the keys have been configured, the bundle isn't used anymore. - base::mac::SetOverrideFrameworkBundle(nil); + base::apple::SetOverrideFrameworkBundle(nil); std::string api_key = testcase::g_api_key_cache.Get().api_key(); std::string id_main =
diff --git a/gpu/command_buffer/service/dawn_instance.cc b/gpu/command_buffer/service/dawn_instance.cc index dd787666..fb2b451bf 100644 --- a/gpu/command_buffer/service/dawn_instance.cc +++ b/gpu/command_buffer/service/dawn_instance.cc
@@ -13,7 +13,7 @@ #include "gpu/config/gpu_preferences.h" #if BUILDFLAG(IS_MAC) -#include "base/mac/bundle_locations.h" +#include "base/apple/bundle_locations.h" #include "base/mac/foundation_util.h" #endif @@ -27,7 +27,7 @@ base::FilePath module_path; #if BUILDFLAG(IS_MAC) if (base::mac::AmIBundled()) { - dawn_search_path = base::mac::FrameworkBundlePath() + dawn_search_path = base::apple::FrameworkBundlePath() .Append("Libraries") .AsEndingWithSeparator() .MaybeAsASCII();
diff --git a/gpu/command_buffer/service/service_utils.cc b/gpu/command_buffer/service/service_utils.cc index 01436ea..886d5734 100644 --- a/gpu/command_buffer/service/service_utils.cc +++ b/gpu/command_buffer/service/service_utils.cc
@@ -269,8 +269,8 @@ auto value = command_line->GetSwitchValueASCII(switches::kUseWebGPUAdapter); if (value.empty()) { return WebGPUAdapterName::kDefault; - } else if (value == "compat") { - return WebGPUAdapterName::kCompat; + } else if (value == "opengles") { + return WebGPUAdapterName::kOpenGLES; } else if (value == "swiftshader") { return WebGPUAdapterName::kSwiftShader; } else if (value == "default") {
diff --git a/gpu/command_buffer/service/shared_image/egl_image_backing_factory.cc b/gpu/command_buffer/service/shared_image/egl_image_backing_factory.cc index c8e9f01..783b136 100644 --- a/gpu/command_buffer/service/shared_image/egl_image_backing_factory.cc +++ b/gpu/command_buffer/service/shared_image/egl_image_backing_factory.cc
@@ -128,7 +128,7 @@ } if ((usage & SHARED_IMAGE_USAGE_WEBGPU) && - (use_webgpu_adapter_ != WebGPUAdapterName::kCompat)) { + (use_webgpu_adapter_ != WebGPUAdapterName::kOpenGLES)) { return false; }
diff --git a/gpu/command_buffer/service/webgpu_decoder_impl.cc b/gpu/command_buffer/service/webgpu_decoder_impl.cc index 86534a6..73d0cae 100644 --- a/gpu/command_buffer/service/webgpu_decoder_impl.cc +++ b/gpu/command_buffer/service/webgpu_decoder_impl.cc
@@ -1238,7 +1238,7 @@ } if (gr_context_type_ != GrContextType::kVulkan && - use_webgpu_adapter_ != WebGPUAdapterName::kCompat) { + use_webgpu_adapter_ != WebGPUAdapterName::kOpenGLES) { #if BUILDFLAG(IS_LINUX) callback(WGPURequestAdapterStatus_Unavailable, nullptr, "WebGPU on Linux requires command-line flag " @@ -1534,8 +1534,8 @@ swiftShaderOptions.forceSwiftShader = true; dawn_instance_->DiscoverAdapters(&swiftShaderOptions); #endif // BUILDFLAG(ENABLE_VULKAN) - if (use_webgpu_adapter_ == WebGPUAdapterName::kCompat) { - // On compat, discover default adapters to also discover the compat adapter. + if (use_webgpu_adapter_ == WebGPUAdapterName::kOpenGLES) { + // Discover default adapters to also discover the OpenGLES adapter. // TODO(senorblanco): This may incorrectly discover a compat adapter that // does not match the one ANGLE is using. dawn_instance_->DiscoverDefaultAdapters(); @@ -1574,7 +1574,7 @@ continue; } - if (use_webgpu_adapter_ == WebGPUAdapterName::kCompat) { + if (use_webgpu_adapter_ == WebGPUAdapterName::kOpenGLES) { if (adapterProperties.backendType == WGPUBackendType_OpenGLES) { adapters.push_back(adapter); }
diff --git a/gpu/config/gpu_info_collector.cc b/gpu/config/gpu_info_collector.cc index 3628f6b1c..4dacad0 100644 --- a/gpu/config/gpu_info_collector.cc +++ b/gpu/config/gpu_info_collector.cc
@@ -42,7 +42,7 @@ #include "ui/gl/init/gl_factory.h" #if BUILDFLAG(IS_MAC) -#include "base/mac/bundle_locations.h" +#include "base/apple/bundle_locations.h" #include "base/mac/foundation_util.h" #endif @@ -654,7 +654,7 @@ base::FilePath module_path; #if BUILDFLAG(IS_MAC) if (base::mac::AmIBundled()) { - dawn_search_path = base::mac::FrameworkBundlePath() + dawn_search_path = base::apple::FrameworkBundlePath() .Append("Libraries") .AsEndingWithSeparator() .MaybeAsASCII();
diff --git a/gpu/config/gpu_preferences.h b/gpu/config/gpu_preferences.h index b0c86f3..dfbf1e9db 100644 --- a/gpu/config/gpu_preferences.h +++ b/gpu/config/gpu_preferences.h
@@ -41,7 +41,7 @@ enum class WebGPUAdapterName : uint32_t { kDefault = 0, - kCompat = 1, + kOpenGLES = 1, kSwiftShader = 2, };
diff --git a/gpu/ipc/common/gpu_preferences.mojom b/gpu/ipc/common/gpu_preferences.mojom index 469895db..97f485e 100644 --- a/gpu/ipc/common/gpu_preferences.mojom +++ b/gpu/ipc/common/gpu_preferences.mojom
@@ -22,7 +22,7 @@ // Corresponds to gpu::WebGPUAdapterName. enum WebGPUAdapterName { kDefault = 0, - kCompat = 1, + kOpenGLES = 1, kSwiftShader = 2, };
diff --git a/gpu/ipc/common/gpu_preferences_mojom_traits.h b/gpu/ipc/common/gpu_preferences_mojom_traits.h index c3265f53..1fca060 100644 --- a/gpu/ipc/common/gpu_preferences_mojom_traits.h +++ b/gpu/ipc/common/gpu_preferences_mojom_traits.h
@@ -103,8 +103,8 @@ switch (input) { case gpu::WebGPUAdapterName::kDefault: return gpu::mojom::WebGPUAdapterName::kDefault; - case gpu::WebGPUAdapterName::kCompat: - return gpu::mojom::WebGPUAdapterName::kCompat; + case gpu::WebGPUAdapterName::kOpenGLES: + return gpu::mojom::WebGPUAdapterName::kOpenGLES; case gpu::WebGPUAdapterName::kSwiftShader: return gpu::mojom::WebGPUAdapterName::kSwiftShader; } @@ -117,8 +117,8 @@ case gpu::mojom::WebGPUAdapterName::kDefault: *out = gpu::WebGPUAdapterName::kDefault; return true; - case gpu::mojom::WebGPUAdapterName::kCompat: - *out = gpu::WebGPUAdapterName::kCompat; + case gpu::mojom::WebGPUAdapterName::kOpenGLES: + *out = gpu::WebGPUAdapterName::kOpenGLES; return true; case gpu::mojom::WebGPUAdapterName::kSwiftShader: *out = gpu::WebGPUAdapterName::kSwiftShader;
diff --git a/infra/config/generated/builders/try/chromeos-js-code-coverage/properties.json b/infra/config/generated/builders/try/chromeos-js-code-coverage/properties.json index e107e28..daa2880 100644 --- a/infra/config/generated/builders/try/chromeos-js-code-coverage/properties.json +++ b/infra/config/generated/builders/try/chromeos-js-code-coverage/properties.json
@@ -41,6 +41,9 @@ ] } }, + "$build/code_coverage": { + "use_javascript_coverage": true + }, "$build/reclient": { "instance": "rbe-chromium-untrusted", "metrics_project": "chromium-reclient-metrics"
diff --git a/infra/config/generated/builders/try/linux-js-code-coverage/properties.json b/infra/config/generated/builders/try/linux-js-code-coverage/properties.json index 1d9d225..8dc0d3304 100644 --- a/infra/config/generated/builders/try/linux-js-code-coverage/properties.json +++ b/infra/config/generated/builders/try/linux-js-code-coverage/properties.json
@@ -38,6 +38,9 @@ ] } }, + "$build/code_coverage": { + "use_javascript_coverage": true + }, "$build/reclient": { "instance": "rbe-chromium-untrusted", "metrics_project": "chromium-reclient-metrics"
diff --git a/infra/config/generated/luci/cr-buildbucket.cfg b/infra/config/generated/luci/cr-buildbucket.cfg index c7f3f9a1..d605a4a 100644 --- a/infra/config/generated/luci/cr-buildbucket.cfg +++ b/infra/config/generated/luci/cr-buildbucket.cfg
@@ -72643,12 +72643,11 @@ builders { name: "linux-chromeos-clang-tidy-rel" swarming_host: "chromium-swarm.appspot.com" - dimensions: "builderless:1" + dimensions: "builder:linux-chromeos-clang-tidy-rel" dimensions: "cores:8" dimensions: "cpu:x86-64" dimensions: "os:Ubuntu-18.04" dimensions: "pool:luci.chromium.try" - dimensions: "ssd:0" exe { cipd_package: "infra/recipe_bundles/chromium.googlesource.com/chromium/tools/build" cipd_version: "refs/heads/main" @@ -73365,12 +73364,11 @@ builders { name: "linux-clang-tidy-rel" swarming_host: "chromium-swarm.appspot.com" - dimensions: "builderless:1" + dimensions: "builder:linux-clang-tidy-rel" dimensions: "cores:8" dimensions: "cpu:x86-64" dimensions: "os:Ubuntu-18.04" dimensions: "pool:luci.chromium.try" - dimensions: "ssd:0" exe { cipd_package: "infra/recipe_bundles/chromium.googlesource.com/chromium/tools/build" cipd_version: "refs/heads/main"
diff --git a/infra/config/subprojects/chromium/try/tryserver.chromium.linux.star b/infra/config/subprojects/chromium/try/tryserver.chromium.linux.star index dac2ea4f..5c743e1 100644 --- a/infra/config/subprojects/chromium/try/tryserver.chromium.linux.star +++ b/infra/config/subprojects/chromium/try/tryserver.chromium.linux.star
@@ -729,12 +729,14 @@ name = "linux-js-code-coverage", mirrors = ["ci/linux-js-code-coverage"], execution_timeout = 20 * time.hour, + use_javascript_coverage = True, ) try_.builder( name = "chromeos-js-code-coverage", mirrors = ["ci/chromeos-js-code-coverage"], execution_timeout = 20 * time.hour, + use_javascript_coverage = True, ) # ML experimental builder, modifies RTS itself to use a ml model
diff --git a/infra/config/subprojects/chromium/try/tryserver.chromium.tricium.star b/infra/config/subprojects/chromium/try/tryserver.chromium.tricium.star index bfd0212c..778db10f 100644 --- a/infra/config/subprojects/chromium/try/tryserver.chromium.tricium.star +++ b/infra/config/subprojects/chromium/try/tryserver.chromium.tricium.star
@@ -62,6 +62,7 @@ try_.builder( name = "linux-chromeos-clang-tidy-rel", executable = "recipe:tricium_clang_tidy_wrapper", + builderless = False, os = os.LINUX_DEFAULT, reclient_jobs = reclient.jobs.HIGH_JOBS_FOR_CQ, ) @@ -69,6 +70,7 @@ try_.builder( name = "linux-clang-tidy-rel", executable = "recipe:tricium_clang_tidy_wrapper", + builderless = False, os = os.LINUX_DEFAULT, reclient_jobs = reclient.jobs.HIGH_JOBS_FOR_CQ, )
diff --git a/ios/chrome/app/dump_documents_statistics.mm b/ios/chrome/app/dump_documents_statistics.mm index 828a342b..550c02a 100644 --- a/ios/chrome/app/dump_documents_statistics.mm +++ b/ios/chrome/app/dump_documents_statistics.mm
@@ -4,12 +4,12 @@ #import "ios/chrome/app/dump_documents_statistics.h" +#import "base/apple/backup_util.h" #import "base/files/file.h" #import "base/files/file_enumerator.h" #import "base/files/file_path.h" #import "base/files/file_util.h" #import "base/json/json_writer.h" -#import "base/mac/backup_util.h" #import "base/mac/foundation_util.h" #import "base/strings/stringprintf.h" #import "base/strings/sys_string_conversions.h" @@ -70,7 +70,7 @@ statistics.Set("created", TimeToLocalString(info.creation_time)); statistics.Set("modified", TimeToLocalString(info.last_modified)); - statistics.Set("excludedFromBackups", base::mac::GetBackupExclusion(root)); + statistics.Set("excludedFromBackups", base::apple::GetBackupExclusion(root)); return statistics; }
diff --git a/ios/chrome/app/main_application_delegate.mm b/ios/chrome/app/main_application_delegate.mm index 3aac648..817dd50 100644 --- a/ios/chrome/app/main_application_delegate.mm +++ b/ios/chrome/app/main_application_delegate.mm
@@ -91,8 +91,7 @@ _appState = [[AppState alloc] initWithBrowserLauncher:_browserLauncher startupInformation:_startupInformation applicationDelegate:self]; - _pushNotificationDelegate = - [[PushNotificationDelegate alloc] initWithAppState:_appState]; + _pushNotificationDelegate = [[PushNotificationDelegate alloc] init]; [_mainController setAppState:_appState]; } return self; @@ -150,6 +149,12 @@ name:UIApplicationWillEnterForegroundNotification object:nil]; + [[NSNotificationCenter defaultCenter] + addObserver:self + selector:@selector(applicationDidBecomeActive:) + name:UIApplicationDidBecomeActiveNotification + object:nil]; + return YES; } @@ -364,6 +369,10 @@ memoryHelper:_memoryHelper]; } +- (void)applicationDidBecomeActive:(NSNotification*)notification { + [_pushNotificationDelegate browserDidBecomeReady]; +} + #pragma mark - AppStateObserver methods - (void)appState:(AppState*)appState
diff --git a/ios/chrome/app/main_controller.mm b/ios/chrome/app/main_controller.mm index 5de8d31..d553416 100644 --- a/ios/chrome/app/main_controller.mm +++ b/ios/chrome/app/main_controller.mm
@@ -6,10 +6,10 @@ #import <memory> +#import "base/apple/bundle_locations.h" #import "base/feature_list.h" #import "base/functional/callback.h" #import "base/ios/ios_util.h" -#import "base/mac/bundle_locations.h" #import "base/mac/foundation_util.h" #import "base/metrics/histogram_functions.h" #import "base/metrics/histogram_macros.h" @@ -424,7 +424,7 @@ - (void)startUpBrowserBackgroundInitialization { DCHECK(self.appState.initStage > InitStageSafeMode); - NSBundle* baseBundle = base::mac::OuterBundle(); + NSBundle* baseBundle = base::apple::OuterBundle(); base::mac::SetBaseBundleID( base::SysNSStringToUTF8([baseBundle bundleIdentifier]).c_str()); @@ -433,7 +433,7 @@ [RegisterExperimentalSettings registerExperimentalSettingsWithUserDefaults:[NSUserDefaults standardUserDefaults] - bundle:base::mac:: + bundle:base::apple:: FrameworkBundle()]; // Register all clients before calling any web code.
diff --git a/ios/chrome/app/startup/register_experimental_settings.mm b/ios/chrome/app/startup/register_experimental_settings.mm index 0c7adaf..0de9b59 100644 --- a/ios/chrome/app/startup/register_experimental_settings.mm +++ b/ios/chrome/app/startup/register_experimental_settings.mm
@@ -6,8 +6,8 @@ #import <ostream> +#import "base/apple/bundle_locations.h" #import "base/check.h" -#import "base/mac/bundle_locations.h" #import "base/notreached.h" #import "base/strings/sys_string_conversions.h"
diff --git a/ios/chrome/app/strings/ios_strings.grd b/ios/chrome/app/strings/ios_strings.grd index f95737aa..aa94890a 100644 --- a/ios/chrome/app/strings/ios_strings.grd +++ b/ios/chrome/app/strings/ios_strings.grd
@@ -769,7 +769,7 @@ More </message> <message name="IDS_IOS_CONTENT_SUGGESTIONS_MOST_VISITED_MODULE_TITLE" desc="The Most Visited module title on the new tab page [Length: 10em]"> - Frequently Visited + Most Visisted Sites </message> <message name="IDS_IOS_CONTENT_SUGGESTIONS_READING_LIST" desc="The Reading List title on the new tab page [Length: 10em]"> Reading List
diff --git a/ios/chrome/app/strings/ios_strings_grd/IDS_IOS_CONTENT_SUGGESTIONS_MOST_VISITED_MODULE_TITLE.png.sha1 b/ios/chrome/app/strings/ios_strings_grd/IDS_IOS_CONTENT_SUGGESTIONS_MOST_VISITED_MODULE_TITLE.png.sha1 index 5260b76..99e5595 100644 --- a/ios/chrome/app/strings/ios_strings_grd/IDS_IOS_CONTENT_SUGGESTIONS_MOST_VISITED_MODULE_TITLE.png.sha1 +++ b/ios/chrome/app/strings/ios_strings_grd/IDS_IOS_CONTENT_SUGGESTIONS_MOST_VISITED_MODULE_TITLE.png.sha1
@@ -1 +1 @@ -cc16fc85618789a29ab91b16702d138993e46a4a \ No newline at end of file +1d167d888ef24a35629dcbf6599466ccd9b8fcd6 \ No newline at end of file
diff --git a/ios/chrome/browser/autofill/bottom_sheet/bottom_sheet_tab_helper.h b/ios/chrome/browser/autofill/bottom_sheet/bottom_sheet_tab_helper.h index 7563de7..f05b152 100644 --- a/ios/chrome/browser/autofill/bottom_sheet/bottom_sheet_tab_helper.h +++ b/ios/chrome/browser/autofill/bottom_sheet/bottom_sheet_tab_helper.h
@@ -29,6 +29,10 @@ ~BottomSheetTabHelper() override; + // Returns the maximum number of times the password bottom sheet can be + // dismissed before it gets disabled. + static int PasswordBottomSheetMaxDismissCount(); + // Handler for JavaScript messages. Dispatch to more specific handler. void OnFormMessageReceived(const web::ScriptMessage& message);
diff --git a/ios/chrome/browser/autofill/bottom_sheet/bottom_sheet_tab_helper.mm b/ios/chrome/browser/autofill/bottom_sheet/bottom_sheet_tab_helper.mm index 7b6552bd5..dc9c030 100644 --- a/ios/chrome/browser/autofill/bottom_sheet/bottom_sheet_tab_helper.mm +++ b/ios/chrome/browser/autofill/bottom_sheet/bottom_sheet_tab_helper.mm
@@ -5,6 +5,7 @@ #import "ios/chrome/browser/autofill/bottom_sheet/bottom_sheet_tab_helper.h" #import "base/feature_list.h" +#import "base/metrics/histogram_functions.h" #import "components/autofill/ios/form_util/form_activity_params.h" #import "components/password_manager/core/common/password_manager_features.h" #import "components/password_manager/ios/password_account_storage_notice_handler.h" @@ -21,12 +22,6 @@ #error "This file requires ARC support." #endif -namespace { -// The maximum number of times the password bottom sheet can be dismissed before -// it gets disabled. -constexpr int kIosPasswordBottomSheetMaxDismissCount = 3; -} // namespace - BottomSheetTabHelper::~BottomSheetTabHelper() = default; BottomSheetTabHelper::BottomSheetTabHelper( @@ -42,6 +37,12 @@ // Public methods +int BottomSheetTabHelper::PasswordBottomSheetMaxDismissCount() { + // The maximum number of times the password bottom sheet can be dismissed + // before it gets disabled. + return 3; +} + void BottomSheetTabHelper::SetPasswordBottomSheetHandler( id<PasswordBottomSheetCommands> password_bottom_sheet_commands_handler) { password_bottom_sheet_commands_handler_ = @@ -133,8 +134,12 @@ PrefService* const pref_service = ChromeBrowserState ::FromBrowserState(web_state_->GetBrowserState()) ->GetPrefs(); - return pref_service->GetInteger(prefs::kIosPasswordBottomSheetDismissCount) >= - kIosPasswordBottomSheetMaxDismissCount; + bool dimissLimitReached = + pref_service->GetInteger(prefs::kIosPasswordBottomSheetDismissCount) >= + PasswordBottomSheetMaxDismissCount(); + base::UmaHistogramBoolean("IOS.IsEnabled.Password.BottomSheet", + !dimissLimitReached); + return dimissLimitReached; } WEB_STATE_USER_DATA_KEY_IMPL(BottomSheetTabHelper)
diff --git a/ios/chrome/browser/autofill/form_suggestion_controller.mm b/ios/chrome/browser/autofill/form_suggestion_controller.mm index e85ab70..76f3632 100644 --- a/ios/chrome/browser/autofill/form_suggestion_controller.mm +++ b/ios/chrome/browser/autofill/form_suggestion_controller.mm
@@ -7,6 +7,7 @@ #import <memory> #import "base/mac/foundation_util.h" +#import "base/metrics/histogram_functions.h" #import "base/strings/sys_string_conversions.h" #import "base/strings/utf_string_conversions.h" #import "components/autofill/core/browser/ui/autofill_popup_delegate.h" @@ -381,8 +382,20 @@ ? ChromeBrowserState::FromBrowserState(_webState->GetBrowserState()) : nullptr; if (browserState) { + int dismissCount = browserState->GetPrefs()->GetInteger( + prefs::kIosPasswordBottomSheetDismissCount); browserState->GetPrefs()->SetInteger( prefs::kIosPasswordBottomSheetDismissCount, 0); + if (dismissCount > 0) { + // Log how many times the bottom sheet had been dismissed before being + // re-enabled. + static constexpr int kHistogramMin = 1; + static constexpr int kHistogramMax = 4; + static constexpr size_t kHistogramBuckets = 3; + base::UmaHistogramCustomCounts( + "IOS.ResetDismissCount.Password.BottomSheet", dismissCount, + kHistogramMin, kHistogramMax, kHistogramBuckets); + } } }
diff --git a/ios/chrome/browser/browser_state/chrome_browser_state_impl.mm b/ios/chrome/browser/browser_state/chrome_browser_state_impl.mm index e343a92..bf3d8a5 100644 --- a/ios/chrome/browser/browser_state/chrome_browser_state_impl.mm +++ b/ios/chrome/browser/browser_state/chrome_browser_state_impl.mm
@@ -6,10 +6,10 @@ #import <utility> +#import "base/apple/backup_util.h" #import "base/check.h" #import "base/files/file_path.h" #import "base/files/file_util.h" -#import "base/mac/backup_util.h" #import "base/task/sequenced_task_runner.h" #import "base/threading/thread_restrictions.h" #import "components/bookmarks/browser/bookmark_model.h" @@ -67,7 +67,7 @@ // stash state directory cannot easily be done at that point. if (!base::PathExists(otr_path) && !base::CreateDirectory(otr_path)) return false; - base::mac::SetBackupExclusion(otr_path); + base::apple::SetBackupExclusion(otr_path); if (!base::PathExists(cache_path) && !base::CreateDirectory(cache_path)) return false; return true;
diff --git a/ios/chrome/browser/commerce/push_notification/commerce_push_notification_client.mm b/ios/chrome/browser/commerce/push_notification/commerce_push_notification_client.mm index 7d89ae3..23b52222 100644 --- a/ios/chrome/browser/commerce/push_notification/commerce_push_notification_client.mm +++ b/ios/chrome/browser/commerce/push_notification/commerce_push_notification_client.mm
@@ -118,25 +118,28 @@ BrowserListFactory::GetForBrowserState(GetLastUsedBrowserState()); // Ideally we want a foregrounded active browser, but in the event we can't // find one (e.g. notification was tapped when app was closed and app is - // currently opening), we fallback to the first active browser seen. - Browser* fallback_active_browser = nullptr; + // currently opening), we fallback to the foreground inactive browser. + Browser* fallback_scene_foreground_inactive = nullptr; for (Browser* browser : browser_list->AllRegularBrowsers()) { if (!browser->IsInactive()) { - if (!fallback_active_browser) { - fallback_active_browser = browser; - } SceneStateBrowserAgent* scene_state_browser_agent = SceneStateBrowserAgent::FromBrowser(browser); if (scene_state_browser_agent && - scene_state_browser_agent->GetSceneState() && - scene_state_browser_agent->GetSceneState().activationLevel == - SceneActivationLevelForegroundActive) { - return browser; + scene_state_browser_agent->GetSceneState()) { + if (scene_state_browser_agent->GetSceneState().activationLevel == + SceneActivationLevelForegroundInactive) { + fallback_scene_foreground_inactive = browser; + } + + if (scene_state_browser_agent->GetSceneState().activationLevel == + SceneActivationLevelForegroundActive) { + return browser; + } } } } - if (fallback_active_browser) { - return fallback_active_browser; + if (fallback_scene_foreground_inactive) { + return fallback_scene_foreground_inactive; } return nullptr; }
diff --git a/ios/chrome/browser/commerce/push_notification/commerce_push_notification_client_unittest.mm b/ios/chrome/browser/commerce/push_notification/commerce_push_notification_client_unittest.mm index bfc388e2..d7d8e1bf 100644 --- a/ios/chrome/browser/commerce/push_notification/commerce_push_notification_client_unittest.mm +++ b/ios/chrome/browser/commerce/push_notification/commerce_push_notification_client_unittest.mm
@@ -159,7 +159,7 @@ browser_list_ = BrowserListFactory::GetForBrowserState(chrome_browser_state_.get()); browser_ = std::make_unique<TestBrowser>(chrome_browser_state_.get()); - background_browser_ = + foreground_inactive_browser_ = std::make_unique<TestBrowser>(chrome_browser_state_.get()); browser_list_->AddBrowser(browser_.get()); UrlLoadingNotifierBrowserAgent::CreateForBrowser(browser_.get()); @@ -183,12 +183,13 @@ SceneActivationLevelForegroundActive; SceneStateBrowserAgent::CreateForBrowser(browser_.get(), scene_state_foreground_); - scene_state_background_ = + scene_state_foreground_inactive_ = [[FakeSceneState alloc] initWithAppState:app_state_ browserState:chrome_browser_state_.get()]; - scene_state_background_.activationLevel = SceneActivationLevelBackground; - SceneStateBrowserAgent::CreateForBrowser(background_browser_.get(), - scene_state_background_); + scene_state_foreground_inactive_.activationLevel = + SceneActivationLevelForegroundInactive; + SceneStateBrowserAgent::CreateForBrowser(foreground_inactive_browser_.get(), + scene_state_foreground_inactive_); } CommercePushNotificationClient* GetCommercePushNotificationClient() { @@ -197,7 +198,9 @@ Browser* GetBrowser() { return browser_.get(); } - Browser* GetBackgroundBrowser() { return background_browser_.get(); } + Browser* GetForegroundInactiveBrowser() { + return foreground_inactive_browser_.get(); + } void HandleNotificationInteraction( NSString* action_identifier, @@ -221,13 +224,13 @@ web::WebTaskEnvironment task_environment_; CommercePushNotificationClient commerce_push_notification_client_; std::unique_ptr<Browser> browser_; - std::unique_ptr<Browser> background_browser_; + std::unique_ptr<Browser> foreground_inactive_browser_; std::unique_ptr<TestChromeBrowserState> chrome_browser_state_; BrowserList* browser_list_; bookmarks::BookmarkModel* bookmark_model_; commerce::MockShoppingService* shopping_service_; FakeSceneState* scene_state_foreground_; - FakeSceneState* scene_state_background_; + FakeSceneState* scene_state_foreground_inactive_; AppState* app_state_; }; @@ -334,7 +337,7 @@ TEST_F(CommercePushNotificationClientTest, TestBackgroundBrowserNotUsedWhenForegroundAvailable) { - browser_list_->AddBrowser(GetBackgroundBrowser()); + browser_list_->AddBrowser(GetForegroundInactiveBrowser()); Browser* browser = GetCommercePushClientActiveBrowser(); // When active foregrounded and active backgrounded browser is availalbe, // should choose foregrounded browser. @@ -344,14 +347,14 @@ .activationLevel); } -TEST_F(CommercePushNotificationClientTest, TestBackgroundFallback) { +TEST_F(CommercePushNotificationClientTest, TestForegroundInactiveFallback) { // Remove foregrounded browser browser_list_->RemoveBrowser(GetBrowser()); // Add backgrounded browser - browser_list_->AddBrowser(GetBackgroundBrowser()); + browser_list_->AddBrowser(GetForegroundInactiveBrowser()); Browser* browser = GetCommercePushClientActiveBrowser(); // Only option is backgronuded browser - EXPECT_EQ(SceneActivationLevelBackground, + EXPECT_EQ(SceneActivationLevelForegroundInactive, SceneStateBrowserAgent::FromBrowser(browser) ->GetSceneState() .activationLevel);
diff --git a/ios/chrome/browser/flags/about_flags.mm b/ios/chrome/browser/flags/about_flags.mm index 4108b903..2cc9528 100644 --- a/ios/chrome/browser/flags/about_flags.mm +++ b/ios/chrome/browser/flags/about_flags.mm
@@ -354,6 +354,25 @@ std::size(kStartSurfaceOneHourHideShortcutsReturnToRecentTab), nullptr}, }; +const FeatureEntry::FeatureParam kMagicStackMostVisitedModule[] = { + {kMagicStackMostVisitedModuleParam, "true"}, + {kReducedSpaceParam, "-80"}}; +const FeatureEntry::FeatureParam kMagicStackPushedDown[] = { + {kMagicStackMostVisitedModuleParam, "false"}, + {kReducedSpaceParam, "-30"}}; +const FeatureEntry::FeatureParam kMagicStackReducedNTPTopSpace[] = { + {kMagicStackMostVisitedModuleParam, "false"}, + {kReducedSpaceParam, "20"}}; + +const FeatureEntry::FeatureVariation kMagicStackVariations[]{ + {"Most Visited Tiles in Magic Stack", kMagicStackMostVisitedModule, + std::size(kMagicStackMostVisitedModule), nullptr}, + {"Magic Stack with more NTP Top Space", kMagicStackPushedDown, + std::size(kMagicStackPushedDown), nullptr}, + {"Magic Stack with Reduced NTP Top Space", kMagicStackReducedNTPTopSpace, + std::size(kMagicStackReducedNTPTopSpace), nullptr}, +}; + #if BUILDFLAG(IOS_BACKGROUND_MODE_ENABLED) // Feed Background Refresh Feature Params. const FeatureEntry::FeatureParam kOneHourIntervalOneHourMaxAgeOnce[] = { @@ -1056,7 +1075,9 @@ flags_ui::kOsIos, FEATURE_VALUE_TYPE(kEnableFeedCardMenuSignInPromo)}, {"content-suggestions-magic-stack", flag_descriptions::kMagicStackName, flag_descriptions::kMagicStackDescription, flags_ui::kOsIos, - FEATURE_VALUE_TYPE(kMagicStack)}, + FEATURE_WITH_PARAMS_VALUE_TYPE(kMagicStack, + kMagicStackVariations, + flag_descriptions::kMagicStackName)}, {"default-browser-intents-show-settings", flag_descriptions::kDefaultBrowserIntentsShowSettingsName, flag_descriptions::kDefaultBrowserIntentsShowSettingsDescription,
diff --git a/ios/chrome/browser/history/history_client_impl.cc b/ios/chrome/browser/history/history_client_impl.cc index 75cc1e4..b9cc346 100644 --- a/ios/chrome/browser/history/history_client_impl.cc +++ b/ios/chrome/browser/history/history_client_impl.cc
@@ -16,10 +16,13 @@ #include "ios/chrome/browser/history/history_utils.h" #include "url/gurl.h" -HistoryClientImpl::HistoryClientImpl(bookmarks::BookmarkModel* bookmark_model) - : bookmark_model_(bookmark_model) { - if (bookmark_model_) - bookmark_model_->AddObserver(this); +HistoryClientImpl::HistoryClientImpl( + bookmarks::BookmarkModel* local_or_syncable_bookmark_model, + bookmarks::BookmarkModel* /*account_bookmark_model*/) + : local_or_syncable_bookmark_model_(local_or_syncable_bookmark_model) { + if (local_or_syncable_bookmark_model_) { + local_or_syncable_bookmark_model_->AddObserver(this); + } } HistoryClientImpl::~HistoryClientImpl() { @@ -27,22 +30,23 @@ } void HistoryClientImpl::StopObservingBookmarkModel() { - if (!bookmark_model_) + if (!local_or_syncable_bookmark_model_) { return; - bookmark_model_->RemoveObserver(this); - bookmark_model_ = nullptr; + } + local_or_syncable_bookmark_model_->RemoveObserver(this); + local_or_syncable_bookmark_model_ = nullptr; } void HistoryClientImpl::OnHistoryServiceCreated( history::HistoryService* history_service) { - if (bookmark_model_) { + if (local_or_syncable_bookmark_model_) { on_bookmarks_removed_ = base::BindRepeating(&history::HistoryService::URLsNoLongerBookmarked, base::Unretained(history_service)); favicons_changed_subscription_ = - history_service->AddFaviconsChangedCallback( - base::BindRepeating(&bookmarks::BookmarkModel::OnFaviconsChanged, - base::Unretained(bookmark_model_))); + history_service->AddFaviconsChangedCallback(base::BindRepeating( + &bookmarks::BookmarkModel::OnFaviconsChanged, + base::Unretained(local_or_syncable_bookmark_model_))); } } @@ -62,20 +66,23 @@ std::unique_ptr<history::HistoryBackendClient> HistoryClientImpl::CreateBackendClient() { return std::make_unique<HistoryBackendClientImpl>( - bookmark_model_ ? bookmark_model_->model_loader() : nullptr); + local_or_syncable_bookmark_model_ + ? local_or_syncable_bookmark_model_->model_loader() + : nullptr); } void HistoryClientImpl::UpdateBookmarkLastUsedTime( const base::Uuid& bookmark_node_uuid, base::Time time) { - if (!bookmark_model_) + if (!local_or_syncable_bookmark_model_) { return; - const bookmarks::BookmarkNode* node = - bookmarks::GetBookmarkNodeByUuid(bookmark_model_, bookmark_node_uuid); + } + const bookmarks::BookmarkNode* node = bookmarks::GetBookmarkNodeByUuid( + local_or_syncable_bookmark_model_, bookmark_node_uuid); // This call is async so the BookmarkNode could have already been deleted. if (!node) return; - bookmark_model_->UpdateLastUsedTime(node, time); + local_or_syncable_bookmark_model_->UpdateLastUsedTime(node, time); } void HistoryClientImpl::BookmarkModelChanged() { @@ -83,7 +90,7 @@ void HistoryClientImpl::BookmarkModelBeingDeleted( bookmarks::BookmarkModel* model) { - DCHECK_EQ(model, bookmark_model_); + DCHECK_EQ(model, local_or_syncable_bookmark_model_); StopObservingBookmarkModel(); }
diff --git a/ios/chrome/browser/history/history_client_impl.h b/ios/chrome/browser/history/history_client_impl.h index 392680f..bad85195 100644 --- a/ios/chrome/browser/history/history_client_impl.h +++ b/ios/chrome/browser/history/history_client_impl.h
@@ -24,7 +24,9 @@ class HistoryClientImpl : public history::HistoryClient, public bookmarks::BaseBookmarkModelObserver { public: - explicit HistoryClientImpl(bookmarks::BookmarkModel* bookmark_model); + explicit HistoryClientImpl( + bookmarks::BookmarkModel* local_or_syncable_bookmark_model, + bookmarks::BookmarkModel* account_bookmark_model); HistoryClientImpl(const HistoryClientImpl&) = delete; HistoryClientImpl& operator=(const HistoryClientImpl&) = delete; @@ -58,7 +60,7 @@ // BookmarkModel instance providing access to bookmarks. May be null during // testing, and is null while shutting down. - bookmarks::BookmarkModel* bookmark_model_; + bookmarks::BookmarkModel* local_or_syncable_bookmark_model_; // Callback invoked when URLs are removed from BookmarkModel. base::RepeatingCallback<void(const std::set<GURL>&)> on_bookmarks_removed_;
diff --git a/ios/chrome/browser/history/history_service_factory.cc b/ios/chrome/browser/history/history_service_factory.cc index efb65f5..381c12a 100644 --- a/ios/chrome/browser/history/history_service_factory.cc +++ b/ios/chrome/browser/history/history_service_factory.cc
@@ -15,6 +15,7 @@ #include "components/keyed_service/core/service_access_type.h" #include "components/keyed_service/ios/browser_state_dependency_manager.h" #include "components/prefs/pref_service.h" +#include "ios/chrome/browser/bookmarks/account_bookmark_model_factory.h" #include "ios/chrome/browser/bookmarks/local_or_syncable_bookmark_model_factory.h" #include "ios/chrome/browser/history/history_client_impl.h" #include "ios/chrome/browser/shared/model/browser_state/browser_state_otr_helper.h" @@ -31,8 +32,9 @@ std::unique_ptr<history::HistoryService> history_service( new history::HistoryService( std::make_unique<HistoryClientImpl>( - ios::LocalOrSyncableBookmarkModelFactory::GetForBrowserState( - browser_state)), + LocalOrSyncableBookmarkModelFactory::GetForBrowserState( + browser_state), + AccountBookmarkModelFactory::GetForBrowserState(browser_state)), nullptr)); if (!history_service->Init(history::HistoryDatabaseParamsForPath( browser_state->GetStatePath(), GetChannel()))) { @@ -89,8 +91,8 @@ : BrowserStateKeyedServiceFactory( "HistoryService", BrowserStateDependencyManager::GetInstance()) { - DependsOn(ios::LocalOrSyncableBookmarkModelFactory::GetInstance()); - // TODO(crbug.com/1425458): Add AccountBookmarkModelFactory support. + DependsOn(AccountBookmarkModelFactory::GetInstance()); + DependsOn(LocalOrSyncableBookmarkModelFactory::GetInstance()); } HistoryServiceFactory::~HistoryServiceFactory() {
diff --git a/ios/chrome/browser/optimization_guide/optimization_guide_service.mm b/ios/chrome/browser/optimization_guide/optimization_guide_service.mm index 45eb5a48..278a551e 100644 --- a/ios/chrome/browser/optimization_guide/optimization_guide_service.mm +++ b/ios/chrome/browser/optimization_guide/optimization_guide_service.mm
@@ -82,6 +82,7 @@ DCHECK( !off_the_record_ || prediction_model_and_features_store || !optimization_guide::features::IsOptimizationTargetPredictionEnabled()); + base::FilePath models_dir; if (!off_the_record_) { // Only create a top host provider from the command line if provided. top_host_provider_ = @@ -100,12 +101,20 @@ : nullptr; hint_store = hint_store_ ? hint_store_->AsWeakPtr() : nullptr; if (optimization_guide::features::IsOptimizationTargetPredictionEnabled()) { + // Do not explicitly hand off the model downloads directory to + // off-the-record profiles. Underneath the hood, this variable is only + // used in non off-the-record profiles to know where to download the model + // files to. Off-the-record profiles read the model locations from the + // original profiles they are associated with. + models_dir = profile_path.Append( + optimization_guide::kOptimizationGuidePredictionModelDownloads); prediction_model_and_features_store_ = std::make_unique<optimization_guide::OptimizationGuideStore>( proto_db_provider, profile_path.Append( optimization_guide:: kOptimizationGuidePredictionModelMetadataStore), + models_dir, base::ThreadPool::CreateSequencedTaskRunner( {base::MayBlock(), base::TaskPriority::BEST_EFFORT}), pref_service); @@ -119,16 +128,6 @@ top_host_provider_.get(), tab_url_provider_.get(), url_loader_factory, optimization_guide_logger_.get()); - base::FilePath models_dir; - if (!off_the_record_) { - // Do not explicitly hand off the model downloads directory to - // off-the-record profiles. Underneath the hood, this variable is only used - // in non off-the-record profiles to know where to download the model files - // to. Off-the-record profiles read the model locations from the original - // profiles they are associated with. - models_dir = profile_path.Append( - optimization_guide::kOptimizationGuidePredictionModelDownloads); - } if (optimization_guide::features::IsOptimizationTargetPredictionEnabled()) { // TODO(crbug.com/1284363): Support the new prediction model store. prediction_manager_ =
diff --git a/ios/chrome/browser/policy/browser_dm_token_storage_ios.mm b/ios/chrome/browser/policy/browser_dm_token_storage_ios.mm index c2da119..28bbe53 100644 --- a/ios/chrome/browser/policy/browser_dm_token_storage_ios.mm +++ b/ios/chrome/browser/policy/browser_dm_token_storage_ios.mm
@@ -6,12 +6,12 @@ #import <Foundation/Foundation.h> +#import "base/apple/backup_util.h" #import "base/base64url.h" #import "base/files/file_util.h" #import "base/files/important_file_writer.h" #import "base/hash/sha1.h" #import "base/ios/device_util.h" -#import "base/mac/backup_util.h" #import "base/mac/foundation_util.h" #import "base/path_service.h" #import "base/strings/string_util.h" @@ -65,7 +65,7 @@ return false; } - base::mac::SetBackupExclusion(token_file_path); + base::apple::SetBackupExclusion(token_file_path); return true; }
diff --git a/ios/chrome/browser/policy/policy_watcher_browser_agent.mm b/ios/chrome/browser/policy/policy_watcher_browser_agent.mm index 45bc73c..fbe6b2d 100644 --- a/ios/chrome/browser/policy/policy_watcher_browser_agent.mm +++ b/ios/chrome/browser/policy/policy_watcher_browser_agent.mm
@@ -6,7 +6,7 @@ #import <Foundation/Foundation.h> -#import "base/mac/backup_util.h" +#import "base/apple/backup_util.h" #import "base/mac/foundation_util.h" #import "base/metrics/histogram_functions.h" #import "base/path_service.h" @@ -167,12 +167,12 @@ if (backup_allowed) { base::ThreadPool::PostTask( FROM_HERE, {base::MayBlock(), base::TaskPriority::USER_VISIBLE}, - base::BindOnce(base::IgnoreResult(&base::mac::ClearBackupExclusion), + base::BindOnce(base::IgnoreResult(&base::apple::ClearBackupExclusion), std::move(storage_dir))); } else { base::ThreadPool::PostTask( FROM_HERE, {base::MayBlock(), base::TaskPriority::USER_VISIBLE}, - base::BindOnce(base::IgnoreResult(&base::mac::SetBackupExclusion), + base::BindOnce(base::IgnoreResult(&base::apple::SetBackupExclusion), std::move(storage_dir))); } }
diff --git a/ios/chrome/browser/policy/policy_watcher_browser_agent_unittest.mm b/ios/chrome/browser/policy/policy_watcher_browser_agent_unittest.mm index dec7c7c..691567d 100644 --- a/ios/chrome/browser/policy/policy_watcher_browser_agent_unittest.mm +++ b/ios/chrome/browser/policy/policy_watcher_browser_agent_unittest.mm
@@ -4,7 +4,7 @@ #import "ios/chrome/browser/policy/policy_watcher_browser_agent.h" -#import "base/mac/backup_util.h" +#import "base/apple/backup_util.h" #import "base/mac/foundation_util.h" #import "base/path_service.h" #import "base/test/ios/wait_util.h" @@ -482,19 +482,19 @@ base::FilePath storage_dir = base::mac::GetUserLibraryPath(); // Ensure that backups are allowed initially. - ASSERT_TRUE(base::mac::ClearBackupExclusion(storage_dir)); + ASSERT_TRUE(base::apple::ClearBackupExclusion(storage_dir)); // Disallow backups. browser_->GetBrowserState()->GetPrefs()->SetBoolean( prefs::kAllowChromeDataInBackups, false); task_environment_.RunUntilIdle(); - EXPECT_TRUE(base::mac::GetBackupExclusion(storage_dir)); + EXPECT_TRUE(base::apple::GetBackupExclusion(storage_dir)); // Allow backups. browser_->GetBrowserState()->GetPrefs()->SetBoolean( prefs::kAllowChromeDataInBackups, true); task_environment_.RunUntilIdle(); - EXPECT_FALSE(base::mac::GetBackupExclusion(storage_dir)); + EXPECT_FALSE(base::apple::GetBackupExclusion(storage_dir)); } // Tests that disabling the backup-allowed preference marks the app container @@ -503,7 +503,7 @@ base::FilePath storage_dir = base::mac::GetUserLibraryPath(); // Ensure that backups are allowed initially. - ASSERT_TRUE(base::mac::ClearBackupExclusion(storage_dir)); + ASSERT_TRUE(base::apple::ClearBackupExclusion(storage_dir)); // Disallow backups browser_->GetBrowserState()->GetPrefs()->SetBoolean( @@ -512,7 +512,7 @@ id mockHandler = OCMProtocolMock(@protocol(PolicyChangeCommands)); agent_->Initialize(mockHandler); task_environment_.RunUntilIdle(); - EXPECT_TRUE(base::mac::GetBackupExclusion(storage_dir)); + EXPECT_TRUE(base::apple::GetBackupExclusion(storage_dir)); } // Tests that enabling the backup-allowed preference marks the app container @@ -521,7 +521,7 @@ base::FilePath storage_dir = base::mac::GetUserLibraryPath(); // Ensure that backups are disallowed initially. - ASSERT_TRUE(base::mac::SetBackupExclusion(storage_dir)); + ASSERT_TRUE(base::apple::SetBackupExclusion(storage_dir)); // Allow backups browser_->GetBrowserState()->GetPrefs()->SetBoolean( @@ -530,5 +530,5 @@ id mockHandler = OCMProtocolMock(@protocol(PolicyChangeCommands)); agent_->Initialize(mockHandler); task_environment_.RunUntilIdle(); - EXPECT_FALSE(base::mac::GetBackupExclusion(storage_dir)); + EXPECT_FALSE(base::apple::GetBackupExclusion(storage_dir)); }
diff --git a/ios/chrome/browser/policy/reporting/browser_report_generator_ios.mm b/ios/chrome/browser/policy/reporting/browser_report_generator_ios.mm index e405cf5..c9da165 100644 --- a/ios/chrome/browser/policy/reporting/browser_report_generator_ios.mm +++ b/ios/chrome/browser/policy/reporting/browser_report_generator_ios.mm
@@ -4,7 +4,7 @@ #import "ios/chrome/browser/policy/reporting/browser_report_generator_ios.h" -#import "base/mac/bundle_locations.h" +#import "base/apple/bundle_locations.h" #import "base/mac/foundation_util.h" #import "base/strings/sys_string_conversions.h" #import "components/policy/proto/device_management_backend.pb.h" @@ -26,7 +26,7 @@ BrowserReportGeneratorIOS::~BrowserReportGeneratorIOS() = default; std::string BrowserReportGeneratorIOS::GetExecutablePath() { - NSBundle* baseBundle = base::mac::OuterBundle(); + NSBundle* baseBundle = base::apple::OuterBundle(); return base::SysNSStringToUTF8([baseBundle bundleIdentifier]); }
diff --git a/ios/chrome/browser/push_notification/push_notification_delegate.h b/ios/chrome/browser/push_notification/push_notification_delegate.h index 5ec5143..df20ffe27 100644 --- a/ios/chrome/browser/push_notification/push_notification_delegate.h +++ b/ios/chrome/browser/push_notification/push_notification_delegate.h
@@ -9,15 +9,10 @@ #import <UIKit/UIKit.h> #import <UserNotifications/UserNotifications.h> -#import "ios/chrome/app/application_delegate/app_state.h" -#import "ios/chrome/app/application_delegate/app_state_observer.h" - +// Passes information from the application level to the push notification +// infrastructure. @interface PushNotificationDelegate - : NSObject <UNUserNotificationCenterDelegate, AppStateObserver> - -- (instancetype)initWithAppState:(AppState*)appState NS_DESIGNATED_INITIALIZER; - -- (instancetype)init NS_UNAVAILABLE; + : NSObject <UNUserNotificationCenterDelegate> // Passes the contents of an incoming push notification to the appropriate // `PushNotificationClient` for processing and logs the time it takes for the @@ -29,6 +24,9 @@ // token this function aggregates all the necessary information and registers // the device to the Push Notification server. - (void)applicationDidRegisterWithAPNS:(NSData*)deviceToken; + +// Called when the Browser objects are ready to use. +- (void)browserDidBecomeReady; @end #endif // IOS_CHROME_BROWSER_PUSH_NOTIFICATION_PUSH_NOTIFICATION_DELEGATE_H_
diff --git a/ios/chrome/browser/push_notification/push_notification_delegate.mm b/ios/chrome/browser/push_notification/push_notification_delegate.mm index 6661c14..00e7c2c0 100644 --- a/ios/chrome/browser/push_notification/push_notification_delegate.mm +++ b/ios/chrome/browser/push_notification/push_notification_delegate.mm
@@ -77,11 +77,6 @@ @implementation PushNotificationDelegate -- (instancetype)initWithAppState:(AppState*)appState { - [appState addObserver:self]; - return self; -} - #pragma mark - UNUserNotificationCenterDelegate - - (void)userNotificationCenter:(UNUserNotificationCenter*)center @@ -181,20 +176,13 @@ }); } -#pragma mark - AppStateObserver - -- (void)appState:(AppState*)appState - didTransitionFromInitStage:(InitStage)previousInitStage { - if (appState.initStage < InitStageFinal) { - return; - } +- (void)browserDidBecomeReady { PushNotificationClientManager* clientManager = GetApplicationContext() ->GetPushNotificationService() ->GetPushNotificationClientManager(); DCHECK(clientManager); clientManager->OnBrowserReady(); - [appState removeObserver:self]; } @end
diff --git a/ios/chrome/browser/shared/ui/util/terms_util.mm b/ios/chrome/browser/shared/ui/util/terms_util.mm index a5e63aa1..07ec69f1 100644 --- a/ios/chrome/browser/shared/ui/util/terms_util.mm +++ b/ios/chrome/browser/shared/ui/util/terms_util.mm
@@ -4,7 +4,7 @@ #import "ios/chrome/browser/shared/ui/util/terms_util.h" -#import "base/mac/bundle_locations.h" +#import "base/apple/bundle_locations.h" #import "base/mac/foundation_util.h" #import "base/strings/sys_string_conversions.h" #import "ios/chrome/browser/shared/model/application_context/application_context.h" @@ -32,7 +32,7 @@ const std::string& language, const std::string& ext) { std::string resource_file(base_name + "_" + language); - BOOL exists = [base::mac::FrameworkBundle() + BOOL exists = [base::apple::FrameworkBundle() URLForResource:base::SysUTF8ToNSString(resource_file) withExtension:base::SysUTF8ToNSString(ext)] != nil; return exists ? resource_file + "." + ext : std::string();
diff --git a/ios/chrome/browser/snapshots/snapshot_cache.mm b/ios/chrome/browser/snapshots/snapshot_cache.mm index 7abb4c7..9437068 100644 --- a/ios/chrome/browser/snapshots/snapshot_cache.mm +++ b/ios/chrome/browser/snapshots/snapshot_cache.mm
@@ -9,6 +9,7 @@ #import <set> +#import "base/apple/backup_util.h" #import "base/base_paths.h" #import "base/containers/contains.h" #import "base/files/file_enumerator.h" @@ -17,7 +18,6 @@ #import "base/functional/bind.h" #import "base/ios/crb_protocol_observers.h" #import "base/logging.h" -#import "base/mac/backup_util.h" #import "base/metrics/histogram_functions.h" #import "base/path_service.h" #import "base/sequence_checker.h" @@ -219,7 +219,7 @@ base::FilePath image_path = ImagePath(snapshot_id, IMAGE_TYPE_GREYSCALE, image_scale, cache_directory); WriteImageToDisk(grey_image, image_path); - base::mac::SetBackupExclusion(image_path); + base::apple::SetBackupExclusion(image_path); } void DeleteImageWithSnapshotID(const base::FilePath& cache_directory,
diff --git a/ios/chrome/browser/ui/alert_view/alert_view_controller.mm b/ios/chrome/browser/ui/alert_view/alert_view_controller.mm index 33f2db6..1f4c315d 100644 --- a/ios/chrome/browser/ui/alert_view/alert_view_controller.mm +++ b/ios/chrome/browser/ui/alert_view/alert_view_controller.mm
@@ -133,28 +133,6 @@ // Returns a GrayHighlightButton to be added to the alert for `action`. GrayHighlightButton* GetButtonForAction(AlertAction* action) { - // TODO(crbug.com/1418068): Simplify after minimum version required is >= - // iOS 15. - GrayHighlightButton* button = nil; - if (base::ios::IsRunningOnIOS15OrLater() && - IsUIButtonConfigurationEnabled()) { - if (@available(iOS 15, *)) { - UIButtonConfiguration* buttonConfiguration = - [UIButtonConfiguration plainButtonConfiguration]; - buttonConfiguration.contentInsets = - NSDirectionalEdgeInsetsMake(kButtonInsetTop, kButtonInsetLeading, - kButtonInsetBottom, kButtonInsetTrailing); - button = [GrayHighlightButton buttonWithConfiguration:buttonConfiguration - primaryAction:nil]; - } - } else { - button = [[GrayHighlightButton alloc] init]; - UIEdgeInsets contentEdgeInsets = - UIEdgeInsetsMake(kButtonInsetTop, kButtonInsetLeading, - kButtonInsetBottom, kButtonInsetTrailing); - SetContentEdgeInsets(button, contentEdgeInsets); - } - UIFont* font = nil; UIColor* textColor = nil; if (action.style == UIAlertActionStyleDefault) { @@ -167,11 +145,33 @@ font = [UIFont preferredFontForTextStyle:UIFontTextStyleBody]; textColor = [UIColor colorNamed:kRedColor]; } - button.titleLabel.font = font; - button.titleLabel.adjustsFontForContentSizeCategory = YES; - [button setTitleColor:textColor forState:UIControlStateNormal]; - [button setTitle:action.title forState:UIControlStateNormal]; + GrayHighlightButton* button = nil; + if (IsUIButtonConfigurationEnabled()) { + UIButtonConfiguration* buttonConfiguration = + [UIButtonConfiguration plainButtonConfiguration]; + buttonConfiguration.contentInsets = + NSDirectionalEdgeInsetsMake(kButtonInsetTop, kButtonInsetLeading, + kButtonInsetBottom, kButtonInsetTrailing); + NSDictionary* attributes = @{NSFontAttributeName : font}; + NSAttributedString* title = + [[NSAttributedString alloc] initWithString:action.title + attributes:attributes]; + buttonConfiguration.attributedTitle = title; + buttonConfiguration.baseForegroundColor = textColor; + button = [GrayHighlightButton buttonWithConfiguration:buttonConfiguration + primaryAction:nil]; + } else { + button = [[GrayHighlightButton alloc] init]; + UIEdgeInsets contentEdgeInsets = + UIEdgeInsetsMake(kButtonInsetTop, kButtonInsetLeading, + kButtonInsetBottom, kButtonInsetTrailing); + SetContentEdgeInsets(button, contentEdgeInsets); + button.titleLabel.font = font; + button.titleLabel.adjustsFontForContentSizeCategory = YES; + [button setTitleColor:textColor forState:UIControlStateNormal]; + [button setTitle:action.title forState:UIControlStateNormal]; + } button.contentHorizontalAlignment = UIControlContentHorizontalAlignmentCenter; button.translatesAutoresizingMaskIntoConstraints = NO;
diff --git a/ios/chrome/browser/ui/browser_view/browser_view_controller.mm b/ios/chrome/browser/ui/browser_view/browser_view_controller.mm index 66a877d..b67ec6ec 100644 --- a/ios/chrome/browser/ui/browser_view/browser_view_controller.mm +++ b/ios/chrome/browser/ui/browser_view/browser_view_controller.mm
@@ -6,7 +6,7 @@ #import "ios/chrome/browser/ui/browser_view/browser_view_controller+delegates.h" #import "ios/chrome/browser/ui/browser_view/browser_view_controller+private.h" -#import "base/mac/bundle_locations.h" +#import "base/apple/bundle_locations.h" #import "base/mac/foundation_util.h" #import "base/strings/sys_string_conversions.h" #import "base/task/sequenced_task_runner.h" @@ -424,7 +424,7 @@ (KeyCommandsProvider*)keyCommandsProvider dependencies:(BrowserViewControllerDependencies) dependencies { - self = [super initWithNibName:nil bundle:base::mac::FrameworkBundle()]; + self = [super initWithNibName:nil bundle:base::apple::FrameworkBundle()]; if (self) { _browserContainerViewController = browserContainerViewController; _keyCommandsProvider = keyCommandsProvider; @@ -1304,7 +1304,7 @@ self.hideStatusBar = YES; // Load view from Launch Screen and add it to window. - NSBundle* mainBundle = base::mac::FrameworkBundle(); + NSBundle* mainBundle = base::apple::FrameworkBundle(); NSArray* topObjects = [mainBundle loadNibNamed:@"LaunchScreen" owner:self options:nil];
diff --git a/ios/chrome/browser/ui/content_suggestions/cells/magic_stack_module_container.mm b/ios/chrome/browser/ui/content_suggestions/cells/magic_stack_module_container.mm index 26863b95..3cc518a 100644 --- a/ios/chrome/browser/ui/content_suggestions/cells/magic_stack_module_container.mm +++ b/ios/chrome/browser/ui/content_suggestions/cells/magic_stack_module_container.mm
@@ -6,6 +6,7 @@ #import "base/notreached.h" #import "ios/chrome/browser/ui/content_suggestions/content_suggestions_constants.h" +#import "ios/chrome/browser/ui/content_suggestions/content_suggestions_feature.h" #import "ios/chrome/common/ui/colors/semantic_color_names.h" #import "ios/chrome/grit/ios_strings.h" #import "ui/base/l10n/l10n_util_mac.h" @@ -57,6 +58,10 @@ return l10n_util::GetNSString( IDS_IOS_CONTENT_SUGGESTIONS_SHORTCUTS_MODULE_TITLE); case ContentSuggestionsModuleType::kMostVisited: + if (ShouldPutMostVisitedSitesInMagicStack()) { + return l10n_util::GetNSString( + IDS_IOS_CONTENT_SUGGESTIONS_MOST_VISITED_MODULE_TITLE); + } return @""; default: NOTREACHED();
diff --git a/ios/chrome/browser/ui/content_suggestions/content_suggestions_collection_utils.mm b/ios/chrome/browser/ui/content_suggestions/content_suggestions_collection_utils.mm index 0958145..b99045a 100644 --- a/ios/chrome/browser/ui/content_suggestions/content_suggestions_collection_utils.mm +++ b/ios/chrome/browser/ui/content_suggestions/content_suggestions_collection_utils.mm
@@ -104,6 +104,8 @@ top_inset + AlignValueToPixel(kDoodleScaledTopMarginOther * ui_util::SystemSuggestedFontSizeMultiplier()); + // If Magic Stack is not enabled, this value is zero (e.g. no-op). + top_margin -= ReducedNTPTopMarginSpaceForMagicStack(); if (ShouldShrinkLogoForStartSurface() && !IsCompactHeight(trait_collection)) { top_margin += kShrunkDoodleTopMarginOther; } else {
diff --git a/ios/chrome/browser/ui/content_suggestions/content_suggestions_feature.h b/ios/chrome/browser/ui/content_suggestions/content_suggestions_feature.h index 7a3867d6..ca43d0b 100644 --- a/ios/chrome/browser/ui/content_suggestions/content_suggestions_feature.h +++ b/ios/chrome/browser/ui/content_suggestions/content_suggestions_feature.h
@@ -19,6 +19,14 @@ // Feature for the Magic Stack. BASE_DECLARE_FEATURE(kMagicStack); +// A parameter to indicate whether the Most Visited Tiles should be in the Magic +// Stack. +extern const char kMagicStackMostVisitedModuleParam[]; + +// A parameter representing how much to reduce the NTP top space margin. If it +// is negative, it will increase the top space margin. +extern const char kReducedSpaceParam[]; + // A parameter to indicate whether the native UI is enabled for the discover // feed. // TODO(crbug.com/1385512): Remove this. @@ -31,4 +39,10 @@ // Whether the Magic Stack should be shown. bool IsMagicStackEnabled(); +// Whether the Most Visited Sites should be put into the Magic Stack. +bool ShouldPutMostVisitedSitesInMagicStack(); + +// How much the NTP top margin should be reduced by for the Magic Stack design. +double ReducedNTPTopMarginSpaceForMagicStack(); + #endif // IOS_CHROME_BROWSER_UI_CONTENT_SUGGESTIONS_CONTENT_SUGGESTIONS_FEATURE_H_
diff --git a/ios/chrome/browser/ui/content_suggestions/content_suggestions_feature.mm b/ios/chrome/browser/ui/content_suggestions/content_suggestions_feature.mm index f1fdc4d..a306d5b 100644 --- a/ios/chrome/browser/ui/content_suggestions/content_suggestions_feature.mm +++ b/ios/chrome/browser/ui/content_suggestions/content_suggestions_feature.mm
@@ -24,6 +24,10 @@ // Feature disabled by default. BASE_FEATURE(kMagicStack, "MagicStack", base::FEATURE_DISABLED_BY_DEFAULT); +const char kMagicStackMostVisitedModuleParam[] = "MagicStackMostVisitedModule"; + +const char kReducedSpaceParam[] = "ReducedNTPTopSpace"; + // A parameter to indicate whether the native UI is enabled for the discover // feed. const char kDiscoverFeedIsNativeUIEnabled[] = "DiscoverFeedIsNativeUIEnabled"; @@ -35,3 +39,13 @@ bool IsMagicStackEnabled() { return base::FeatureList::IsEnabled(kMagicStack); } + +bool ShouldPutMostVisitedSitesInMagicStack() { + return base::GetFieldTrialParamByFeatureAsBool( + kMagicStack, kMagicStackMostVisitedModuleParam, false); +} + +double ReducedNTPTopMarginSpaceForMagicStack() { + return base::GetFieldTrialParamByFeatureAsDouble(kMagicStack, + kReducedSpaceParam, 0); +}
diff --git a/ios/chrome/browser/ui/content_suggestions/content_suggestions_mediator.mm b/ios/chrome/browser/ui/content_suggestions/content_suggestions_mediator.mm index 252e21c..aef2ede 100644 --- a/ios/chrome/browser/ui/content_suggestions/content_suggestions_mediator.mm +++ b/ios/chrome/browser/ui/content_suggestions/content_suggestions_mediator.mm
@@ -222,9 +222,7 @@ [self.consumer setShortcutTilesWithConfigs:self.actionButtonItems]; } if (IsMagicStackEnabled()) { - [self.consumer setMagicStackOrder:@[ - @(int(ContentSuggestionsModuleType::kShortcuts)) - ]]; + [self.consumer setMagicStackOrder:[self magicStackOrder]]; } } @@ -649,6 +647,19 @@ kTileAblationHideMVTOnly; } +// Returns an array that represents the order of the modules to be shown in the +// Magic Stack. +- (NSArray<NSNumber*>*)magicStackOrder { + if (ShouldPutMostVisitedSitesInMagicStack()) { + return @[ + @(int(ContentSuggestionsModuleType::kMostVisited)), + @(int(ContentSuggestionsModuleType::kShortcuts)) + ]; + } else { + return @[ @(int(ContentSuggestionsModuleType::kShortcuts)) ]; + } +} + #pragma mark - Properties - (NSArray<ContentSuggestionsMostVisitedActionItem*>*)actionButtonItems {
diff --git a/ios/chrome/browser/ui/content_suggestions/content_suggestions_view_controller.mm b/ios/chrome/browser/ui/content_suggestions/content_suggestions_view_controller.mm index 10c6b2d..fac0eb09 100644 --- a/ios/chrome/browser/ui/content_suggestions/content_suggestions_view_controller.mm +++ b/ios/chrome/browser/ui/content_suggestions/content_suggestions_view_controller.mm
@@ -100,6 +100,7 @@ @implementation ContentSuggestionsViewController { UIScrollView* _magicStackScrollView; + UIStackView* _magicStack; BOOL _shouldShowMagicStack; NSArray<NSNumber*>* _magicStackModuleOrder; NSLayoutConstraint* _magicStackScrollViewWidthAnchor; @@ -155,8 +156,6 @@ constant:-bottomSpacing] ]]; - CGFloat horizontalSpacing = - ContentSuggestionsTilesHorizontalSpacing(self.traitCollection); if (self.returnToRecentTabTile) { UIView* parentView = self.returnToRecentTabTile; [self addUIElement:self.returnToRecentTabTile @@ -171,25 +170,7 @@ ]]; } if ([self.mostVisitedViews count] > 0) { - self.mostVisitedStackView = [[UIStackView alloc] init]; - self.mostVisitedStackView.axis = UILayoutConstraintAxisHorizontal; - self.mostVisitedStackView.distribution = UIStackViewDistributionFillEqually; - self.mostVisitedStackView.spacing = horizontalSpacing; - self.mostVisitedStackView.alignment = UIStackViewAlignmentTop; - if (!IsMagicStackEnabled()) { - [self addUIElement:self.mostVisitedStackView - withCustomBottomSpacing:kMostVisitedBottomMargin]; - CGFloat width = - MostVisitedTilesContentHorizontalSpace(self.traitCollection); - CGFloat height = - MostVisitedCellSize(self.traitCollection.preferredContentSizeCategory) - .height; - [NSLayoutConstraint activateConstraints:@[ - [self.mostVisitedStackView.widthAnchor constraintEqualToConstant:width], - [self.mostVisitedStackView.heightAnchor - constraintGreaterThanOrEqualToConstant:height] - ]]; - } + [self createAndInsertMostVisitedModule]; [self populateMostVisitedModule]; } if (self.shortcutsViews) { @@ -341,6 +322,11 @@ [self.mostVisitedViews addObject:view]; index++; } + // If viewDidLoad has been called before the first valid Most Visited Tiles + // are available, construct `mostVisitedStackView`. + if (self.verticalStackView && !self.mostVisitedStackView) { + [self createAndInsertMostVisitedModule]; + } [self populateMostVisitedModule]; [self.contentSuggestionsMetricsRecorder recordMostVisitedTilesShown]; // Trigger a relayout so that the MVTs will be counted in the Content @@ -399,7 +385,8 @@ - (CGFloat)contentSuggestionsHeight { CGFloat height = 0; - if ([self.mostVisitedViews count] > 0) { + if ([self.mostVisitedViews count] > 0 && + !ShouldPutMostVisitedSitesInMagicStack()) { height += MostVisitedCellSize( UIApplication.sharedApplication.preferredContentSizeCategory) .height + @@ -511,54 +498,53 @@ } } -// Add the elements in `mostVisitedViews` into `verticalStackView`, constructing -// `verticalStackView` beforehand if it has not been yet. -- (void)populateMostVisitedModule { - // If viewDidLoad has been called before the first valid Most Visited Tiles - // are available, construct `mostVisitedStackView`. - if (self.verticalStackView && !self.mostVisitedStackView) { - self.mostVisitedStackView = [[UIStackView alloc] init]; - self.mostVisitedStackView.axis = UILayoutConstraintAxisHorizontal; - self.mostVisitedStackView.alignment = UIStackViewAlignmentTop; - self.mostVisitedStackView.distribution = UIStackViewDistributionFillEqually; - self.mostVisitedStackView.spacing = - ContentSuggestionsTilesHorizontalSpacing(self.traitCollection); +- (void)createAndInsertMostVisitedModule { + CGFloat horizontalSpacing = + ContentSuggestionsTilesHorizontalSpacing(self.traitCollection); + self.mostVisitedStackView = [[UIStackView alloc] init]; + self.mostVisitedStackView.axis = UILayoutConstraintAxisHorizontal; + self.mostVisitedStackView.distribution = UIStackViewDistributionFillEqually; + self.mostVisitedStackView.spacing = horizontalSpacing; + self.mostVisitedStackView.alignment = UIStackViewAlignmentTop; - if (IsMagicStackEnabled()) { - self.mostVisitedModuleContainer = [[ActionListModule alloc] - initWithContentView:self.mostVisitedStackView - type:ContentSuggestionsModuleType::kMostVisited]; - // Find correct insertion position in the stack. - int insertionIndex = 0; - if (self.returnToRecentTabTile) { - insertionIndex++; - } + // Find correct insertion position in the stack. + int insertionIndex = 0; + if (self.returnToRecentTabTile) { + insertionIndex++; + } + if (IsMagicStackEnabled()) { + self.mostVisitedModuleContainer = [[ActionListModule alloc] + initWithContentView:self.mostVisitedStackView + type:ContentSuggestionsModuleType::kMostVisited]; + if (ShouldPutMostVisitedSitesInMagicStack()) { + [_magicStack insertArrangedSubview:self.mostVisitedModuleContainer + atIndex:0]; + } else { [self.verticalStackView insertArrangedSubview:self.mostVisitedModuleContainer atIndex:insertionIndex]; [self.verticalStackView setCustomSpacing:kMostVisitedBottomMargin afterView:self.mostVisitedModuleContainer]; - } else { - // Find correct insertion position in the stack. - int insertionIndex = 0; - if (self.returnToRecentTabTile) { - insertionIndex++; - } - [self.verticalStackView insertArrangedSubview:self.mostVisitedStackView - atIndex:insertionIndex]; - [self.verticalStackView setCustomSpacing:kMostVisitedBottomMargin - afterView:self.mostVisitedStackView]; - CGFloat width = - MostVisitedTilesContentHorizontalSpace(self.traitCollection); - CGSize size = MostVisitedCellSize( - self.traitCollection.preferredContentSizeCategory); - [NSLayoutConstraint activateConstraints:@[ - [self.mostVisitedStackView.widthAnchor constraintEqualToConstant:width], - [self.mostVisitedStackView.heightAnchor - constraintEqualToConstant:size.height] - ]]; } + } else { + [self.verticalStackView insertArrangedSubview:self.mostVisitedStackView + atIndex:insertionIndex]; + [self.verticalStackView setCustomSpacing:kMostVisitedBottomMargin + afterView:self.mostVisitedStackView]; + CGFloat width = + MostVisitedTilesContentHorizontalSpace(self.traitCollection); + CGSize size = + MostVisitedCellSize(self.traitCollection.preferredContentSizeCategory); + [NSLayoutConstraint activateConstraints:@[ + [self.mostVisitedStackView.widthAnchor constraintEqualToConstant:width], + [self.mostVisitedStackView.heightAnchor + constraintEqualToConstant:size.height] + ]]; } +} + +// Add the elements in `mostVisitedViews` into `verticalStackView`. +- (void)populateMostVisitedModule { for (ContentSuggestionsMostVisitedTileView* view in self.mostVisitedViews) { view.menuProvider = self.menuProvider; UITapGestureRecognizer* tapRecognizer = [[UITapGestureRecognizer alloc] @@ -605,13 +591,13 @@ [self addUIElement:_magicStackScrollView withCustomBottomSpacing:kMostVisitedBottomMargin]; - UIStackView* magicStack = [[UIStackView alloc] init]; - magicStack.translatesAutoresizingMaskIntoConstraints = NO; - magicStack.axis = UILayoutConstraintAxisHorizontal; - magicStack.distribution = UIStackViewDistributionEqualSpacing; - magicStack.spacing = 10; - magicStack.alignment = UIStackViewAlignmentCenter; - [_magicStackScrollView addSubview:magicStack]; + _magicStack = [[UIStackView alloc] init]; + _magicStack.translatesAutoresizingMaskIntoConstraints = NO; + _magicStack.axis = UILayoutConstraintAxisHorizontal; + _magicStack.distribution = UIStackViewDistributionEqualSpacing; + _magicStack.spacing = 10; + _magicStack.alignment = UIStackViewAlignmentCenter; + [_magicStackScrollView addSubview:_magicStack]; // Add Magic Stack modules in order dictated by `_magicStackModuleOrder`. for (NSNumber* moduleType in _magicStackModuleOrder) { @@ -622,13 +608,18 @@ self.shortcutsModuleContainer = [[ActionListModule alloc] initWithContentView:self.shortcutsStackView type:type]; - [magicStack addArrangedSubview:self.shortcutsModuleContainer]; + [_magicStack addArrangedSubview:self.shortcutsModuleContainer]; + break; + case ContentSuggestionsModuleType::kMostVisited: + if (ShouldPutMostVisitedSitesInMagicStack()) { + [_magicStack addArrangedSubview:self.mostVisitedModuleContainer]; + } break; default: break; } } - AddSameConstraints(magicStack, _magicStackScrollView); + AddSameConstraints(_magicStack, _magicStackScrollView); // Define width of ScrollView. Instrinsic content height of the // StackView within the ScrollView will define the height of the // ScrollView. @@ -636,7 +627,7 @@ [_magicStackScrollView.widthAnchor constraintEqualToConstant:width]; [NSLayoutConstraint activateConstraints:@[ // Ensures only horizontal scrolling - [magicStack.heightAnchor + [_magicStack.heightAnchor constraintEqualToAnchor:_magicStackScrollView.heightAnchor], _magicStackScrollViewWidthAnchor ]];
diff --git a/ios/chrome/browser/ui/find_bar/find_bar_controller_ios.mm b/ios/chrome/browser/ui/find_bar/find_bar_controller_ios.mm index 4da382e..4007e9c 100644 --- a/ios/chrome/browser/ui/find_bar/find_bar_controller_ios.mm +++ b/ios/chrome/browser/ui/find_bar/find_bar_controller_ios.mm
@@ -4,9 +4,9 @@ #import "ios/chrome/browser/ui/find_bar/find_bar_controller_ios.h" +#import "base/apple/bundle_locations.h" #import "base/format_macros.h" #import "base/i18n/rtl.h" -#import "base/mac/bundle_locations.h" #import "base/mac/foundation_util.h" #import "base/strings/sys_string_conversions.h" #import "components/strings/grit/components_strings.h"
diff --git a/ios/chrome/browser/ui/first_run/tos/tos_coordinator.mm b/ios/chrome/browser/ui/first_run/tos/tos_coordinator.mm index 9b25357..d0bdece 100644 --- a/ios/chrome/browser/ui/first_run/tos/tos_coordinator.mm +++ b/ios/chrome/browser/ui/first_run/tos/tos_coordinator.mm
@@ -6,7 +6,7 @@ #import <WebKit/WebKit.h> -#import "base/mac/bundle_locations.h" +#import "base/apple/bundle_locations.h" #import "base/strings/sys_string_conversions.h" #import "components/strings/grit/components_strings.h" #import "ios/chrome/browser/shared/coordinator/alert/alert_coordinator.h"
diff --git a/ios/chrome/browser/ui/main/incognito_blocker_scene_agent.mm b/ios/chrome/browser/ui/main/incognito_blocker_scene_agent.mm index 7124255..339421c 100644 --- a/ios/chrome/browser/ui/main/incognito_blocker_scene_agent.mm +++ b/ios/chrome/browser/ui/main/incognito_blocker_scene_agent.mm
@@ -4,8 +4,8 @@ #import "ios/chrome/browser/ui/main/incognito_blocker_scene_agent.h" +#import "base/apple/bundle_locations.h" #import "base/ios/ios_util.h" -#import "base/mac/bundle_locations.h" #import "base/mac/foundation_util.h" #if !defined(__has_feature) || !__has_feature(objc_arc) @@ -104,7 +104,7 @@ } - (UIViewController*)loadLaunchScreenControllerFromBundle { - NSBundle* mainBundle = base::mac::FrameworkBundle(); + NSBundle* mainBundle = base::apple::FrameworkBundle(); NSArray* topObjects = [mainBundle loadNibNamed:@"LaunchScreen" owner:self options:nil];
diff --git a/ios/chrome/browser/ui/passwords/bottom_sheet/password_suggestion_bottom_sheet_mediator.mm b/ios/chrome/browser/ui/passwords/bottom_sheet/password_suggestion_bottom_sheet_mediator.mm index 0403a14..f4bc07d 100644 --- a/ios/chrome/browser/ui/passwords/bottom_sheet/password_suggestion_bottom_sheet_mediator.mm +++ b/ios/chrome/browser/ui/passwords/bottom_sheet/password_suggestion_bottom_sheet_mediator.mm
@@ -368,10 +368,13 @@ // Increments the dismiss count preference. - (void)incrementDismissCount { if (_prefService) { - _prefService->SetInteger( - prefs::kIosPasswordBottomSheetDismissCount, + int newDismissCount = _prefService->GetInteger(prefs::kIosPasswordBottomSheetDismissCount) + - 1); + 1; + CHECK(newDismissCount <= + BottomSheetTabHelper::PasswordBottomSheetMaxDismissCount()); + _prefService->SetInteger(prefs::kIosPasswordBottomSheetDismissCount, + newDismissCount); } }
diff --git a/ios/chrome/browser/ui/tab_switcher/tab_grid/tab_grid_coordinator.mm b/ios/chrome/browser/ui/tab_switcher/tab_grid/tab_grid_coordinator.mm index ef57fea8..f68622c 100644 --- a/ios/chrome/browser/ui/tab_switcher/tab_grid/tab_grid_coordinator.mm +++ b/ios/chrome/browser/ui/tab_switcher/tab_grid/tab_grid_coordinator.mm
@@ -4,7 +4,7 @@ #import "ios/chrome/browser/ui/tab_switcher/tab_grid/tab_grid_coordinator.h" -#import "base/mac/bundle_locations.h" +#import "base/apple/bundle_locations.h" #import "base/mac/foundation_util.h" #import "base/metrics/histogram_functions.h" #import "base/metrics/user_metrics.h"
diff --git a/ios/chrome/browser/ui/tabs/tab_strip_controller.mm b/ios/chrome/browser/ui/tabs/tab_strip_controller.mm index f8ed04af..72623ae 100644 --- a/ios/chrome/browser/ui/tabs/tab_strip_controller.mm +++ b/ios/chrome/browser/ui/tabs/tab_strip_controller.mm
@@ -8,9 +8,9 @@ #import <memory> #import <vector> +#import "base/apple/bundle_locations.h" #import "base/i18n/rtl.h" #import "base/ios/ios_util.h" -#import "base/mac/bundle_locations.h" #import "base/mac/foundation_util.h" #import "base/metrics/histogram_functions.h" #import "base/metrics/user_metrics.h"
diff --git a/ios/chrome/browser/ui/webui/terms_ui.mm b/ios/chrome/browser/ui/webui/terms_ui.mm index 84c4c2f4..1c9215d 100644 --- a/ios/chrome/browser/ui/webui/terms_ui.mm +++ b/ios/chrome/browser/ui/webui/terms_ui.mm
@@ -6,7 +6,7 @@ #import <Foundation/Foundation.h> -#import "base/mac/bundle_locations.h" +#import "base/apple/bundle_locations.h" #import "base/memory/ref_counted_memory.h" #import "base/strings/sys_string_conversions.h" #import "ios/chrome/browser/shared/model/browser_state/chrome_browser_state.h" @@ -62,7 +62,7 @@ web::URLDataSourceIOS::GotDataCallback callback) { NSString* terms_of_service_path = base::SysUTF8ToNSString(GetTermsOfServicePath()); - NSString* bundle_path = [base::mac::FrameworkBundle() bundlePath]; + NSString* bundle_path = [base::apple::FrameworkBundle() bundlePath]; NSString* full_path = [bundle_path stringByAppendingPathComponent:terms_of_service_path]; DCHECK(full_path);
diff --git a/ios/chrome/browser/ui/whats_new/data_source/whats_new_data_source.mm b/ios/chrome/browser/ui/whats_new/data_source/whats_new_data_source.mm index e316c9d..e46bfbf8 100644 --- a/ios/chrome/browser/ui/whats_new/data_source/whats_new_data_source.mm +++ b/ios/chrome/browser/ui/whats_new/data_source/whats_new_data_source.mm
@@ -4,7 +4,7 @@ #import "ios/chrome/browser/ui/whats_new/data_source/whats_new_data_source.h" -#import "base/mac/bundle_locations.h" +#import "base/apple/bundle_locations.h" #import "base/mac/foundation_util.h" #import "base/notreached.h" #import "base/strings/string_util.h" @@ -240,7 +240,7 @@ } NSString* WhatsNewFilePath() { - NSString* bundle_path = [base::mac::FrameworkBundle() bundlePath]; + NSString* bundle_path = [base::apple::FrameworkBundle() bundlePath]; NSString* entries_file_path = [bundle_path stringByAppendingPathComponent:kfileName]; return entries_file_path;
diff --git a/ios/chrome/browser/upgrade/upgrade_center.mm b/ios/chrome/browser/upgrade/upgrade_center.mm index a793228..81ddfd6 100644 --- a/ios/chrome/browser/upgrade/upgrade_center.mm +++ b/ios/chrome/browser/upgrade/upgrade_center.mm
@@ -8,7 +8,7 @@ #import <set> #import <utility> -#import "base/mac/bundle_locations.h" +#import "base/apple/bundle_locations.h" #import "base/mac/foundation_util.h" #import "base/scoped_observation.h" #import "base/strings/sys_string_conversions.h"
diff --git a/ios/chrome/browser/voice/speech_input_locale_config_impl.mm b/ios/chrome/browser/voice/speech_input_locale_config_impl.mm index 35d49f4..70b1b186 100644 --- a/ios/chrome/browser/voice/speech_input_locale_config_impl.mm +++ b/ios/chrome/browser/voice/speech_input_locale_config_impl.mm
@@ -6,8 +6,8 @@ #import <Foundation/Foundation.h> +#import "base/apple/bundle_locations.h" #import "base/containers/contains.h" -#import "base/mac/bundle_locations.h" #import "base/mac/foundation_util.h" #import "base/mac/scoped_cftyperef.h" #import "base/strings/string_split.h"
diff --git a/ios/chrome/browser/web/blocked_popup_tab_helper.mm b/ios/chrome/browser/web/blocked_popup_tab_helper.mm index 79e20562..9343885b 100644 --- a/ios/chrome/browser/web/blocked_popup_tab_helper.mm +++ b/ios/chrome/browser/web/blocked_popup_tab_helper.mm
@@ -9,8 +9,8 @@ #import <memory> #import <utility> +#import "base/apple/bundle_locations.h" #import "base/format_macros.h" -#import "base/mac/bundle_locations.h" #import "base/mac/foundation_util.h" #import "base/strings/stringprintf.h" #import "base/strings/utf_string_conversions.h"
diff --git a/ios/chrome/browser/web/chrome_web_client.mm b/ios/chrome/browser/web/chrome_web_client.mm index 27fdfc83..522756e 100644 --- a/ios/chrome/browser/web/chrome_web_client.mm +++ b/ios/chrome/browser/web/chrome_web_client.mm
@@ -4,12 +4,12 @@ #import "ios/chrome/browser/web/chrome_web_client.h" +#import "base/apple/bundle_locations.h" #import "base/command_line.h" #import "base/feature_list.h" #import "base/files/file_util.h" #import "base/ios/ios_util.h" #import "base/ios/ns_error_util.h" -#import "base/mac/bundle_locations.h" #import "base/metrics/histogram_functions.h" #import "base/no_destructor.h" #import "base/strings/stringprintf.h"
diff --git a/ios/chrome/common/channel_info.mm b/ios/chrome/common/channel_info.mm index fc19ed85..ee65cc16 100644 --- a/ios/chrome/common/channel_info.mm +++ b/ios/chrome/common/channel_info.mm
@@ -7,7 +7,7 @@ #import <Foundation/Foundation.h> #import <dispatch/dispatch.h> -#import "base/mac/bundle_locations.h" +#import "base/apple/bundle_locations.h" #import "base/strings/sys_string_conversions.h" #import "build/branding_buildflags.h" #import "components/version_info/version_info.h" @@ -61,7 +61,7 @@ #if BUILDFLAG(GOOGLE_CHROME_BRANDING) static dispatch_once_t channel_dispatch_token; dispatch_once(&channel_dispatch_token, ^{ - NSBundle* bundle = base::mac::OuterBundle(); + NSBundle* bundle = base::apple::OuterBundle(); // Only Keystone-enabled build can have a channel. if (![bundle objectForInfoDictionaryKey:@"KSProductID"])
diff --git a/ios/web/js_messaging/page_script_util.mm b/ios/web/js_messaging/page_script_util.mm index e5a33ba..96763a3 100644 --- a/ios/web/js_messaging/page_script_util.mm +++ b/ios/web/js_messaging/page_script_util.mm
@@ -4,9 +4,9 @@ #import "ios/web/js_messaging/page_script_util.h" +#import "base/apple/bundle_locations.h" #import "base/files/file_path.h" #import "base/files/file_util.h" -#import "base/mac/bundle_locations.h" #import "base/strings/sys_string_conversions.h" #import "ios/web/public/browser_state.h" #import "ios/web/public/web_client.h" @@ -20,8 +20,8 @@ NSString* GetPageScript(NSString* script_file_name) { DCHECK(script_file_name); NSString* path = - [base::mac::FrameworkBundle() pathForResource:script_file_name - ofType:@"js"]; + [base::apple::FrameworkBundle() pathForResource:script_file_name + ofType:@"js"]; DCHECK(path) << "Script file not found: " << base::SysNSStringToUTF8(script_file_name) << ".js"; NSError* error = nil;
diff --git a/ios/web/navigation/navigation_manager_impl.mm b/ios/web/navigation/navigation_manager_impl.mm index 6a655d7..d49706b 100644 --- a/ios/web/navigation/navigation_manager_impl.mm +++ b/ios/web/navigation/navigation_manager_impl.mm
@@ -9,12 +9,12 @@ #import <memory> #import <utility> +#import "base/apple/bundle_locations.h" #import "base/debug/dump_without_crashing.h" #import "base/functional/bind.h" #import "base/functional/callback.h" #import "base/ios/ios_util.h" #import "base/logging.h" -#import "base/mac/bundle_locations.h" #import "base/memory/ptr_util.h" #import "base/metrics/histogram_macros.h" #import "base/numerics/checked_math.h"
diff --git a/ios/web/navigation/wk_navigation_util.mm b/ios/web/navigation/wk_navigation_util.mm index 53215e34..426c139 100644 --- a/ios/web/navigation/wk_navigation_util.mm +++ b/ios/web/navigation/wk_navigation_util.mm
@@ -6,8 +6,8 @@ #import <algorithm> +#import "base/apple/bundle_locations.h" #import "base/json/json_writer.h" -#import "base/mac/bundle_locations.h" #import "base/metrics/field_trial_params.h" #import "base/strings/escape.h" #import "base/strings/string_util.h" @@ -79,8 +79,8 @@ GURL GetRestoreSessionBaseUrl() { std::string restore_session_resource_path = base::SysNSStringToUTF8( - [base::mac::FrameworkBundle() pathForResource:@"restore_session" - ofType:@"html"]); + [base::apple::FrameworkBundle() pathForResource:@"restore_session" + ofType:@"html"]); GURL::Replacements replacements; replacements.SetSchemeStr(url::kFileScheme); replacements.SetPathStr(restore_session_resource_path);
diff --git a/ios/web/public/test/js_test_util.mm b/ios/web/public/test/js_test_util.mm index c50d79c..e7c99879 100644 --- a/ios/web/public/test/js_test_util.mm +++ b/ios/web/public/test/js_test_util.mm
@@ -6,7 +6,7 @@ #import <WebKit/WebKit.h> -#import "base/mac/bundle_locations.h" +#import "base/apple/bundle_locations.h" #import "base/strings/sys_string_conversions.h" #import "base/test/ios/wait_util.h" #import "ios/web/js_messaging/java_script_feature_manager.h"
diff --git a/ios/web_view/internal/web_view_web_client.mm b/ios/web_view/internal/web_view_web_client.mm index bcb0ab5..6192925f 100644 --- a/ios/web_view/internal/web_view_web_client.mm +++ b/ios/web_view/internal/web_view_web_client.mm
@@ -4,21 +4,21 @@ #import "ios/web_view/internal/web_view_web_client.h" -#include <dispatch/dispatch.h> +#import <dispatch/dispatch.h> -#include "base/check.h" -#include "base/functional/bind.h" +#import "base/apple/bundle_locations.h" +#import "base/check.h" +#import "base/functional/bind.h" #import "base/ios/ns_error_util.h" -#include "base/mac/bundle_locations.h" -#include "base/strings/sys_string_conversions.h" -#include "components/autofill/ios/browser/autofill_java_script_feature.h" +#import "base/strings/sys_string_conversions.h" +#import "components/autofill/ios/browser/autofill_java_script_feature.h" #import "components/autofill/ios/browser/suggestion_controller_java_script_feature.h" #import "components/autofill/ios/form_util/form_handlers_java_script_feature.h" #import "components/language/ios/browser/language_detection_java_script_feature.h" #import "components/password_manager/ios/password_manager_java_script_feature.h" #import "components/security_interstitials/core/unsafe_resource.h" -#include "components/ssl_errors/error_info.h" -#include "components/strings/grit/components_strings.h" +#import "components/ssl_errors/error_info.h" +#import "components/strings/grit/components_strings.h" #import "components/translate/ios/browser/translate_java_script_feature.h" #import "ios/components/security_interstitials/https_only_mode/feature.h" #import "ios/components/security_interstitials/ios_security_interstitial_java_script_feature.h" @@ -26,28 +26,28 @@ #import "ios/components/security_interstitials/lookalikes/lookalike_url_error.h" #import "ios/components/security_interstitials/safe_browsing/safe_browsing_error.h" #import "ios/components/security_interstitials/safe_browsing/safe_browsing_unsafe_resource_container.h" -#include "ios/components/webui/web_ui_url_constants.h" -#include "ios/web/common/user_agent.h" +#import "ios/components/webui/web_ui_url_constants.h" +#import "ios/web/common/user_agent.h" #import "ios/web/public/navigation/navigation_manager.h" -#include "ios/web/public/security/ssl_status.h" -#include "ios/web/public/thread/web_task_traits.h" -#include "ios/web/public/thread/web_thread.h" +#import "ios/web/public/security/ssl_status.h" +#import "ios/web/public/thread/web_task_traits.h" +#import "ios/web/public/thread/web_thread.h" #import "ios/web_view/internal/cwv_lookalike_url_handler_internal.h" #import "ios/web_view/internal/cwv_ssl_error_handler_internal.h" #import "ios/web_view/internal/cwv_ssl_status_internal.h" #import "ios/web_view/internal/cwv_ssl_util.h" #import "ios/web_view/internal/cwv_web_view_internal.h" #import "ios/web_view/internal/safe_browsing/cwv_unsafe_url_handler_internal.h" -#include "ios/web_view/internal/web_view_browser_state.h" +#import "ios/web_view/internal/web_view_browser_state.h" #import "ios/web_view/internal/web_view_early_page_script_provider.h" #import "ios/web_view/internal/web_view_message_handler_java_script_feature.h" #import "ios/web_view/internal/web_view_web_main_parts.h" #import "ios/web_view/public/cwv_navigation_delegate.h" #import "ios/web_view/public/cwv_web_view.h" #import "net/base/mac/url_conversions.h" -#include "net/cert/cert_status_flags.h" -#include "ui/base/l10n/l10n_util.h" -#include "ui/base/resource/resource_bundle.h" +#import "net/cert/cert_status_flags.h" +#import "ui/base/l10n/l10n_util.h" +#import "ui/base/resource/resource_bundle.h" #if !defined(__has_feature) || !__has_feature(objc_arc) #error "This file requires ARC support."
diff --git a/ios/web_view/internal/web_view_web_main_delegate.mm b/ios/web_view/internal/web_view_web_main_delegate.mm index 91a9830..74a7f656 100644 --- a/ios/web_view/internal/web_view_web_main_delegate.mm +++ b/ios/web_view/internal/web_view_web_main_delegate.mm
@@ -4,9 +4,9 @@ #import "ios/web_view/internal/web_view_web_main_delegate.h" +#import "base/apple/bundle_locations.h" #include "base/base_paths.h" #include "base/logging.h" -#import "base/mac/bundle_locations.h" #include "components/component_updater/component_updater_paths.h" #if !defined(__has_feature) || !__has_feature(objc_arc) @@ -27,7 +27,7 @@ WebViewWebMainDelegate::~WebViewWebMainDelegate() = default; void WebViewWebMainDelegate::BasicStartupComplete() { - base::mac::SetOverrideFrameworkBundle( + base::apple::SetOverrideFrameworkBundle( [NSBundle bundleForClass:[CWVBundleLocator class]]); // Sets up logging so logging levels can be controlled.
diff --git a/ipc/BUILD.gn b/ipc/BUILD.gn index 6edeb54..5625f67 100644 --- a/ipc/BUILD.gn +++ b/ipc/BUILD.gn
@@ -99,9 +99,7 @@ "//services/tracing/public/cpp", ] - if (is_apple) { - public_deps += [ "//base:base_arc" ] - } + deps = [ "//base" ] if (enable_ipc_fuzzer) { public_configs = [ "//tools/ipc_fuzzer:ipc_fuzzer_config" ]
diff --git a/media/base/media_switches.cc b/media/base/media_switches.cc index 1eb891b2..f9b0f15 100644 --- a/media/base/media_switches.cc +++ b/media/base/media_switches.cc
@@ -285,12 +285,6 @@ const char kCastStreamingForceEnableHardwareVp8[] = "cast-streaming-force-enable-hardware-vp8"; -// Disables the code path that makes Pepper use the MojoVideoDecoder for -// hardware accelerated video decoding. It overrides the value of the -// kUseMojoVideoDecoderForPepper feature flag. -const char kDisableUseMojoVideoDecoderForPepper[] = - "disable-use-mojo-video-decoder-for-pepper"; - #if !BUILDFLAG(IS_ANDROID) const char kCastMirroringTargetPlayoutDelay[] = "cast-mirroring-target-playout-delay"; @@ -1283,13 +1277,6 @@ "UseOutOfProcessVideoEncoding", base::FEATURE_DISABLED_BY_DEFAULT}; #endif // BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS) -// Make the PepperVideoDecoderHost use the MojoVideoDecoder to talk to hardware -// decoders instead of using the GpuVideoDecodeAcceleratorHost. Note: this -// doesn't affect the PPB_VideoDecoder_Impl which will continue to use the -// GpuVideoDecodeAcceleratorHost for the PPB_VideoDecoder_Dev interface. -const base::Feature MEDIA_EXPORT kUseMojoVideoDecoderForPepper{ - "UseMojoVideoDecoderForPepper", base::FEATURE_ENABLED_BY_DEFAULT}; - // Use SequencedTaskRunner for MediaService. BASE_FEATURE(kUseSequencedTaskRunnerForMediaService, "UseSequencedTaskRunnerForMediaService",
diff --git a/media/base/media_switches.h b/media/base/media_switches.h index 3c4e360..c61d765 100644 --- a/media/base/media_switches.h +++ b/media/base/media_switches.h
@@ -138,8 +138,6 @@ // to take effect. MEDIA_EXPORT extern const char kCastStreamingForceEnableHardwareVp8[]; -MEDIA_EXPORT extern const char kDisableUseMojoVideoDecoderForPepper[]; - #if !BUILDFLAG(IS_ANDROID) // If enabled, overrides the target playout delay for a casting mirroring // session. The value will be parsed as milliseconds. Lowering this value will @@ -430,7 +428,6 @@ MEDIA_EXPORT BASE_DECLARE_FEATURE(kUseOutOfProcessVideoEncoding); #endif // BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS) -MEDIA_EXPORT BASE_DECLARE_FEATURE(kUseMojoVideoDecoderForPepper); MEDIA_EXPORT BASE_DECLARE_FEATURE(kUseSequencedTaskRunnerForMediaService); MEDIA_EXPORT BASE_DECLARE_FEATURE(kUseSequencedTaskRunnerForMojoVEAProvider); MEDIA_EXPORT BASE_DECLARE_FEATURE(kUseTaskRunnerForMojoVEAService);
diff --git a/media/gpu/v4l2/generic_v4l2_device.cc b/media/gpu/v4l2/generic_v4l2_device.cc index fe0e251..20cc4576 100644 --- a/media/gpu/v4l2/generic_v4l2_device.cc +++ b/media/gpu/v4l2/generic_v4l2_device.cc
@@ -29,6 +29,7 @@ #include "media/gpu/chromeos/fourcc.h" #include "media/gpu/macros.h" #include "media/gpu/v4l2/generic_v4l2_device.h" +#include "media/gpu/v4l2/v4l2_utils.h" #include "ui/gfx/native_pixmap.h" #include "ui/gfx/native_pixmap_handle.h" #include "ui/gl/egl_util.h" @@ -312,8 +313,8 @@ continue; } - std::vector<uint32_t> pixelformats = - EnumerateSupportedPixelformats(buf_type); + const auto pixelformats = EnumerateSupportedPixFmts( + base::BindRepeating(&V4L2Device::Ioctl, this), buf_type); supported_pixelformats.insert(supported_pixelformats.end(), pixelformats.begin(), pixelformats.end()); @@ -324,8 +325,8 @@ } VideoDecodeAccelerator::SupportedProfiles -GenericV4L2Device::GetSupportedDecodeProfiles(const size_t num_formats, - const uint32_t pixelformats[]) { +GenericV4L2Device::GetSupportedDecodeProfiles( + const std::vector<uint32_t>& pixelformats) { VideoDecodeAccelerator::SupportedProfiles supported_profiles; Type type = Type::kDecoder; @@ -336,8 +337,7 @@ continue; } - const auto& profiles = - EnumerateSupportedDecodeProfiles(num_formats, pixelformats); + const auto& profiles = EnumerateSupportedDecodeProfiles(pixelformats); supported_profiles.insert(supported_profiles.end(), profiles.begin(), profiles.end()); CloseDevice(); @@ -470,9 +470,9 @@ for (const auto& path : candidate_paths) { if (!OpenDevicePath(path, type)) continue; + const auto supported_pixelformats = EnumerateSupportedPixFmts( + base::BindRepeating(&V4L2Device::Ioctl, this), buf_type); - const auto& supported_pixelformats = - EnumerateSupportedPixelformats(buf_type); if (!supported_pixelformats.empty()) { DVLOGF(3) << "Found device: " << path; devices.push_back(std::make_pair(path, supported_pixelformats));
diff --git a/media/gpu/v4l2/generic_v4l2_device.h b/media/gpu/v4l2/generic_v4l2_device.h index cb49a7e..1aa4a9c 100644 --- a/media/gpu/v4l2/generic_v4l2_device.h +++ b/media/gpu/v4l2/generic_v4l2_device.h
@@ -64,8 +64,7 @@ v4l2_buf_type buf_type) override; VideoDecodeAccelerator::SupportedProfiles GetSupportedDecodeProfiles( - const size_t num_formats, - const uint32_t pixelformats[]) override; + const std::vector<uint32_t>& pixelformats) override; VideoEncodeAccelerator::SupportedProfiles GetSupportedEncodeProfiles() override;
diff --git a/media/gpu/v4l2/legacy/v4l2_slice_video_decode_accelerator.cc b/media/gpu/v4l2/legacy/v4l2_slice_video_decode_accelerator.cc index 164ec84..6cf3c78 100644 --- a/media/gpu/v4l2/legacy/v4l2_slice_video_decode_accelerator.cc +++ b/media/gpu/v4l2/legacy/v4l2_slice_video_decode_accelerator.cc
@@ -83,8 +83,7 @@ namespace media { -// static -const uint32_t V4L2SliceVideoDecodeAccelerator::supported_input_fourccs_[] = { +static const std::vector<uint32_t> kSupportedInputFourCCs = { V4L2_PIX_FMT_H264_SLICE, #if BUILDFLAG(ENABLE_HEVC_PARSER_AND_HW_DECODER) V4L2_PIX_FMT_HEVC_SLICE, @@ -2216,8 +2215,7 @@ if (!device) return SupportedProfiles(); - return device->GetSupportedDecodeProfiles(std::size(supported_input_fourccs_), - supported_input_fourccs_); + return device->GetSupportedDecodeProfiles(kSupportedInputFourCCs); } bool V4L2SliceVideoDecodeAccelerator::IsSupportedProfile(
diff --git a/media/gpu/v4l2/legacy/v4l2_slice_video_decode_accelerator.h b/media/gpu/v4l2/legacy/v4l2_slice_video_decode_accelerator.h index 0165525..1d00d0d9 100644 --- a/media/gpu/v4l2/legacy/v4l2_slice_video_decode_accelerator.h +++ b/media/gpu/v4l2/legacy/v4l2_slice_video_decode_accelerator.h
@@ -140,9 +140,6 @@ const size_t kInputBufferMaxSizeFor4k = 4 * kInputBufferMaxSizeFor1080p; const size_t kNumInputBuffers = 16; - // Input format V4L2 fourccs this class supports. - static const uint32_t supported_input_fourccs_[]; - static scoped_refptr<gpu::GLImageNativePixmap> CreateGLImage( const gfx::Size& size, const Fourcc fourcc,
diff --git a/media/gpu/v4l2/legacy/v4l2_stateful_workaround.cc b/media/gpu/v4l2/legacy/v4l2_stateful_workaround.cc index 62c2c51..7bb1da0 100644 --- a/media/gpu/v4l2/legacy/v4l2_stateful_workaround.cc +++ b/media/gpu/v4l2/legacy/v4l2_stateful_workaround.cc
@@ -167,15 +167,15 @@ if (strcmp(reinterpret_cast<const char*>(caps.driver), go2001)) return nullptr; - constexpr uint32_t supported_input_fourccs[] = { + const std::vector<uint32_t> supported_input_fourccs = { V4L2_PIX_FMT_VP8, }; // Recreate the V4L2 device in order to close the opened decoder, since // we are about to query the supported decode profiles. device = V4L2Device::Create(); - auto supported_profiles = device->GetSupportedDecodeProfiles( - std::size(supported_input_fourccs), supported_input_fourccs); + auto supported_profiles = + device->GetSupportedDecodeProfiles(supported_input_fourccs); SupportedProfileMap supported_profile_map; for (const auto& entry : supported_profiles) supported_profile_map[entry.profile] = entry;
diff --git a/media/gpu/v4l2/legacy/v4l2_video_decode_accelerator.cc b/media/gpu/v4l2/legacy/v4l2_video_decode_accelerator.cc index e6ac7114..12b092d 100644 --- a/media/gpu/v4l2/legacy/v4l2_video_decode_accelerator.cc +++ b/media/gpu/v4l2/legacy/v4l2_video_decode_accelerator.cc
@@ -84,9 +84,10 @@ } // namespace -// static -const uint32_t V4L2VideoDecodeAccelerator::supported_input_fourccs_[] = { - V4L2_PIX_FMT_H264, V4L2_PIX_FMT_VP8, V4L2_PIX_FMT_VP9, +static const std::vector<uint32_t> kSupportedInputFourCCs = { + V4L2_PIX_FMT_H264, + V4L2_PIX_FMT_VP8, + V4L2_PIX_FMT_VP9, }; // static @@ -854,8 +855,7 @@ if (!device) return SupportedProfiles(); - return device->GetSupportedDecodeProfiles(std::size(supported_input_fourccs_), - supported_input_fourccs_); + return device->GetSupportedDecodeProfiles(kSupportedInputFourCCs); } void V4L2VideoDecodeAccelerator::DecodeTask(scoped_refptr<DecoderBuffer> buffer,
diff --git a/media/gpu/v4l2/legacy/v4l2_video_decode_accelerator.h b/media/gpu/v4l2/legacy/v4l2_video_decode_accelerator.h index 2e3f329..cc1f056 100644 --- a/media/gpu/v4l2/legacy/v4l2_video_decode_accelerator.h +++ b/media/gpu/v4l2/legacy/v4l2_video_decode_accelerator.h
@@ -620,9 +620,6 @@ // The logical dimensions of EGLImage buffer in pixels. gfx::Size egl_image_size_; - // Input format V4L2 fourccs this class supports. - static const uint32_t supported_input_fourccs_[]; - // The WeakPtrFactory for |weak_this_|. base::WeakPtrFactory<V4L2VideoDecodeAccelerator> weak_this_factory_; };
diff --git a/media/gpu/v4l2/v4l2_device.cc b/media/gpu/v4l2/v4l2_device.cc index e59918b57..da59d39 100644 --- a/media/gpu/v4l2/v4l2_device.cc +++ b/media/gpu/v4l2/v4l2_device.cc
@@ -1945,35 +1945,19 @@ return rate_control_mode; } -std::vector<uint32_t> V4L2Device::EnumerateSupportedPixelformats( - v4l2_buf_type buf_type) { - std::vector<uint32_t> pixelformats; - - v4l2_fmtdesc fmtdesc; - memset(&fmtdesc, 0, sizeof(fmtdesc)); - fmtdesc.type = buf_type; - - for (; Ioctl(VIDIOC_ENUM_FMT, &fmtdesc) == 0; ++fmtdesc.index) { - DVLOGF(3) << "Found " << FourccToString(fmtdesc.pixelformat) << " (" - << fmtdesc.description << ")"; - pixelformats.push_back(fmtdesc.pixelformat); - } - - return pixelformats; -} - VideoDecodeAccelerator::SupportedProfiles -V4L2Device::EnumerateSupportedDecodeProfiles(const size_t num_formats, - const uint32_t pixelformats[]) { +V4L2Device::EnumerateSupportedDecodeProfiles( + const std::vector<uint32_t>& pixelformats) { VideoDecodeAccelerator::SupportedProfiles profiles; - const auto& supported_pixelformats = - EnumerateSupportedPixelformats(V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE); + const auto v4l2_codecs_as_pix_fmts = + EnumerateSupportedPixFmts(base::BindRepeating(&V4L2Device::Ioctl, this), + V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE); - for (uint32_t pixelformat : supported_pixelformats) { - if (std::find(pixelformats, pixelformats + num_formats, pixelformat) == - pixelformats + num_formats) + for (uint32_t pixelformat : v4l2_codecs_as_pix_fmts) { + if (!base::Contains(pixelformats, pixelformat)) { continue; + } // Skip AV1 decoder profiles if kChromeOSHWAV1Decoder is disabled. if ((pixelformat == V4L2_PIX_FMT_AV1 || @@ -2006,10 +1990,11 @@ V4L2Device::EnumerateSupportedEncodeProfiles() { VideoEncodeAccelerator::SupportedProfiles profiles; - const auto& supported_pixelformats = - EnumerateSupportedPixelformats(V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE); + const auto v4l2_codecs_as_pix_fmts = + EnumerateSupportedPixFmts(base::BindRepeating(&V4L2Device::Ioctl, this), + V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE); - for (const auto& pixelformat : supported_pixelformats) { + for (const auto& pixelformat : v4l2_codecs_as_pix_fmts) { VideoEncodeAccelerator::SupportedProfile profile; profile.max_framerate_numerator = 30; profile.max_framerate_denominator = 1;
diff --git a/media/gpu/v4l2/v4l2_device.h b/media/gpu/v4l2/v4l2_device.h index 1a82aba..f88a8a6 100644 --- a/media/gpu/v4l2/v4l2_device.h +++ b/media/gpu/v4l2/v4l2_device.h
@@ -807,8 +807,6 @@ VideoEncodeAccelerator::SupportedRateControlMode GetSupportedRateControlMode(); - std::vector<uint32_t> EnumerateSupportedPixelformats(v4l2_buf_type buf_type); - // NOTE: The below methods to query capabilities have a side effect of // closing the previously-open device, if any, and should not be called after // Open(). @@ -822,8 +820,7 @@ // Return supported profiles for decoder, including only profiles for given // fourcc |pixelformats|. virtual VideoDecodeAccelerator::SupportedProfiles GetSupportedDecodeProfiles( - const size_t num_formats, - const uint32_t pixelformats[]) = 0; + const std::vector<uint32_t>& pixelformats) = 0; // Return supported profiles for encoder. virtual VideoEncodeAccelerator::SupportedProfiles @@ -879,8 +876,7 @@ virtual ~V4L2Device(); VideoDecodeAccelerator::SupportedProfiles EnumerateSupportedDecodeProfiles( - const size_t num_formats, - const uint32_t pixelformats[]); + const std::vector<uint32_t>& pixelformats); VideoEncodeAccelerator::SupportedProfiles EnumerateSupportedEncodeProfiles();
diff --git a/media/gpu/v4l2/v4l2_unittest.cc b/media/gpu/v4l2/v4l2_unittest.cc index d84b6a0..8a949ae 100644 --- a/media/gpu/v4l2/v4l2_unittest.cc +++ b/media/gpu/v4l2/v4l2_unittest.cc
@@ -15,6 +15,7 @@ #include "base/test/test_suite.h" #include "media/base/video_codecs.h" #include "media/gpu/v4l2/v4l2_device.h" +#include "media/gpu/v4l2/v4l2_utils.h" #include "third_party/libdrm/src/include/drm/drm_fourcc.h" #include <drm.h> @@ -184,8 +185,8 @@ scoped_refptr<V4L2Device> device = V4L2Device::Create(); ASSERT_TRUE(device); - const auto fourcc_stateful = - V4L2Device::VideoCodecProfileToV4L2PixFmt(video_codec_profile, false); + const auto fourcc_stateful = V4L2Device::VideoCodecProfileToV4L2PixFmt( + video_codec_profile, /*slice_based=*/false); const bool is_stateful = device->Open(V4L2Device::Type::kDecoder, fourcc_stateful); @@ -199,8 +200,8 @@ constexpr uint32_t desired_v4l2_pixel_formats[] = {V4L2_PIX_FMT_NV12, V4L2_PIX_FMT_NV12M}; std::vector<uint32_t> supported_v4l2_pixel_formats = - device->EnumerateSupportedPixelformats( - V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE); + EnumerateSupportedPixFmts(base::BindRepeating(&V4L2Device::Ioctl, device), + V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE); int32_t chosen_v4l2_pixel_format = 0; for (const auto supported_v4l2_pixel_format : supported_v4l2_pixel_formats) { if (base::Contains(desired_v4l2_pixel_formats,
diff --git a/media/gpu/v4l2/v4l2_utils.cc b/media/gpu/v4l2/v4l2_utils.cc index 94a5ba4..5a501e2 100644 --- a/media/gpu/v4l2/v4l2_utils.cc +++ b/media/gpu/v4l2/v4l2_utils.cc
@@ -55,6 +55,9 @@ namespace media { +// Numerical value of ioctl() OK return value; +constexpr int kIoctlOk = 0; + const char* V4L2MemoryToString(const v4l2_memory memory) { switch (memory) { case V4L2_MEMORY_MMAP: @@ -252,7 +255,6 @@ } const auto profile_cid = kV4L2CodecPixFmtToProfileCID.at(codec_as_pix_fmt); - constexpr int kIoctlOk = 0; v4l2_queryctrl query_ctrl = {.id = static_cast<__u32>(profile_cid)}; if (ioctl_cb.Run(VIDIOC_QUERYCTRL, &query_ctrl) != kIoctlOk) { // This happens for example for VP8 on Hana MTK8173, or for HEVC on Trogdor @@ -293,4 +295,25 @@ return profiles; } +std::vector<uint32_t> EnumerateSupportedPixFmts( + base::RepeatingCallback<int(int, void*)> ioctl_cb, + v4l2_buf_type buf_type) { + DCHECK(buf_type == V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE || + buf_type == V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE); + + std::vector<v4l2_enum_type> pix_fmts; + v4l2_fmtdesc fmtdesc = {.type = buf_type}; + for (; ioctl_cb.Run(VIDIOC_ENUM_FMT, &fmtdesc) == kIoctlOk; ++fmtdesc.index) { + DVLOGF(4) << "Enumerated " + << (buf_type == V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE + ? "codec: " + : "pixel format: ") + << FourccToString(fmtdesc.pixelformat) << " (" + << fmtdesc.description << ")"; + pix_fmts.push_back(fmtdesc.pixelformat); + } + + return pix_fmts; +} + } // namespace media
diff --git a/media/gpu/v4l2/v4l2_utils.h b/media/gpu/v4l2/v4l2_utils.h index e59c2c77..9fa8125f 100644 --- a/media/gpu/v4l2/v4l2_utils.h +++ b/media/gpu/v4l2/v4l2_utils.h
@@ -42,6 +42,13 @@ base::RepeatingCallback<int(int, void*)> ioctl_cb, uint32_t codec_as_pix_fmt); +// Enumerates all supported pixel formats for a given device (accessed via +// |ioctl_cb|) and for |buf_type|; these will be the supported video codecs +// (e.g. V4L2_PIX_FMT_VP9) for V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE. +std::vector<uint32_t> EnumerateSupportedPixFmts( + base::RepeatingCallback<int(int, void*)> ioctl_cb, + v4l2_buf_type buf_type); + } // namespace media #endif // MEDIA_GPU_V4L2_V4L2_UTILS_H_
diff --git a/media/gpu/v4l2/v4l2_video_decoder.cc b/media/gpu/v4l2/v4l2_video_decoder.cc index 6ba2cd9d..94c9eac 100644 --- a/media/gpu/v4l2/v4l2_video_decoder.cc +++ b/media/gpu/v4l2/v4l2_video_decoder.cc
@@ -27,6 +27,7 @@ #include "media/gpu/gpu_video_decode_accelerator_helpers.h" #include "media/gpu/macros.h" #include "media/gpu/v4l2/v4l2_status.h" +#include "media/gpu/v4l2/v4l2_utils.h" #include "media/gpu/v4l2/v4l2_video_decoder_backend_stateful.h" #include "media/gpu/v4l2/v4l2_video_decoder_backend_stateless.h" @@ -44,7 +45,7 @@ constexpr size_t kInputBufferMaxSizeFor4k = 4 * kInputBufferMaxSizeFor1080p; // Input format V4L2 fourccs this class supports. -constexpr uint32_t kSupportedInputFourccs[] = { +const std::vector<uint32_t> kSupportedInputFourccs = { // V4L2 stateless formats V4L2_PIX_FMT_H264_SLICE, #if BUILDFLAG(ENABLE_HEVC_PARSER_AND_HW_DECODER) @@ -94,9 +95,7 @@ if (!device) return absl::nullopt; - auto configs = device->GetSupportedDecodeProfiles( - std::size(kSupportedInputFourccs), kSupportedInputFourccs); - + auto configs = device->GetSupportedDecodeProfiles(kSupportedInputFourccs); if (configs.empty()) return absl::nullopt; @@ -389,9 +388,10 @@ DCHECK_EQ(state_, State::kInitialized); // Check if the format is supported. - std::vector<uint32_t> formats = device_->EnumerateSupportedPixelformats( + const auto v4l2_codecs_as_pix_fmts = EnumerateSupportedPixFmts( + base::BindRepeating(&V4L2Device::Ioctl, device_), V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE); - if (!base::Contains(formats, fourcc)) { + if (!base::Contains(v4l2_codecs_as_pix_fmts, fourcc)) { DVLOGF(1) << FourccToString(fourcc) << " not recognised, skipping..."; return false; } @@ -426,10 +426,12 @@ DVLOGF(3) << "size: " << size.ToString() << ", visible_rect: " << visible_rect.ToString(); - // Get the supported output formats and their corresponding negotiated sizes. + const auto v4l2_pix_fmts = EnumerateSupportedPixFmts( + base::BindRepeating(&V4L2Device::Ioctl, device_), + V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE); + std::vector<PixelLayoutCandidate> candidates; - for (const uint32_t& pixfmt : device_->EnumerateSupportedPixelformats( - V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE)) { + for (const uint32_t& pixfmt : v4l2_pix_fmts) { const auto candidate = Fourcc::FromV4L2PixFmt(pixfmt); if (!candidate) { DVLOGF(1) << FourccToString(pixfmt) << " is not recognised, skipping...";
diff --git a/media/gpu/v4l2/v4l2_video_decoder_backend_stateful.cc b/media/gpu/v4l2/v4l2_video_decoder_backend_stateful.cc index 26039ada0..c0dfc14 100644 --- a/media/gpu/v4l2/v4l2_video_decoder_backend_stateful.cc +++ b/media/gpu/v4l2/v4l2_video_decoder_backend_stateful.cc
@@ -771,7 +771,7 @@ DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); DCHECK(device_); if (supported_profiles_.empty()) { - constexpr uint32_t kSupportedInputFourccs[] = { + const std::vector<uint32_t> kSupportedInputFourccs = { V4L2_PIX_FMT_H264, #if BUILDFLAG(ENABLE_HEVC_PARSER_AND_HW_DECODER) V4L2_PIX_FMT_HEVC, @@ -781,8 +781,7 @@ }; scoped_refptr<V4L2Device> device = V4L2Device::Create(); VideoDecodeAccelerator::SupportedProfiles profiles = - device->GetSupportedDecodeProfiles(std::size(kSupportedInputFourccs), - kSupportedInputFourccs); + device->GetSupportedDecodeProfiles(kSupportedInputFourccs); for (const auto& entry : profiles) supported_profiles_.push_back(entry.profile); }
diff --git a/media/gpu/v4l2/v4l2_video_decoder_backend_stateless.cc b/media/gpu/v4l2/v4l2_video_decoder_backend_stateless.cc index b1cfa01..1cc53239 100644 --- a/media/gpu/v4l2/v4l2_video_decoder_backend_stateless.cc +++ b/media/gpu/v4l2/v4l2_video_decoder_backend_stateless.cc
@@ -685,7 +685,7 @@ DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); DCHECK(device_); if (supported_profiles_.empty()) { - constexpr uint32_t kSupportedInputFourccs[] = { + const std::vector<uint32_t> kSupportedInputFourccs = { V4L2_PIX_FMT_H264_SLICE, #if BUILDFLAG(ENABLE_HEVC_PARSER_AND_HW_DECODER) V4L2_PIX_FMT_HEVC_SLICE, @@ -696,8 +696,7 @@ }; scoped_refptr<V4L2Device> device = V4L2Device::Create(); VideoDecodeAccelerator::SupportedProfiles profiles = - device->GetSupportedDecodeProfiles(std::size(kSupportedInputFourccs), - kSupportedInputFourccs); + device->GetSupportedDecodeProfiles(kSupportedInputFourccs); for (const auto& entry : profiles) supported_profiles_.push_back(entry.profile); }
diff --git a/mojo/public/cpp/platform/BUILD.gn b/mojo/public/cpp/platform/BUILD.gn index 8fbfbc8a..5cfcc0f 100644 --- a/mojo/public/cpp/platform/BUILD.gn +++ b/mojo/public/cpp/platform/BUILD.gn
@@ -58,10 +58,6 @@ deps += [ "//net" ] } - if (is_apple) { - public_deps += [ "//base:base_arc" ] - } - if (is_mac) { sources += [ "named_platform_channel_mac.cc" ] }
diff --git a/net/android/BUILD.gn b/net/android/BUILD.gn index a15bfc1..c772343a 100644 --- a/net/android/BUILD.gn +++ b/net/android/BUILD.gn
@@ -78,6 +78,7 @@ ":embedded_test_server_aidl_java", ":net_java", "//base:base_java", + "//base:base_java_test_support", "//base:base_java_url_utils_for_test", "//base:jni_java", "//third_party/androidx:androidx_annotation_annotation_java", @@ -142,9 +143,7 @@ # Used as an additional_apk in test scripts. never_incremental = true - # Multidex requires a custom Application class to initialize it. Simpler to - # just disable it. - enable_multidex = false + enable_multidex = true # Required on Android Q+ to read from /sdcard when installing certs. target_sdk_version = 28
diff --git a/net/android/java/src/org/chromium/net/X509Util.java b/net/android/java/src/org/chromium/net/X509Util.java index a9e3dba1..54e02dec 100644 --- a/net/android/java/src/org/chromium/net/X509Util.java +++ b/net/android/java/src/org/chromium/net/X509Util.java
@@ -163,6 +163,11 @@ private static boolean sLoadedSystemKeyStore; /** + * A root that will be installed as a user-trusted root for testing purposes. + */ + private static X509Certificate sTestRoot; + + /** * Lock object used to synchronize all calls that modify or depend on the trust managers. */ private static final Object sLock = new Object(); @@ -319,17 +324,24 @@ new ByteArrayInputStream(derBytes)); } + /** + * Add a test root certificate for use by the Android Platform verifier. + */ public static void addTestRootCertificate(byte[] rootCertBytes) throws CertificateException, KeyStoreException, NoSuchAlgorithmException { X509Certificate rootCert = createCertificateFromBytes(rootCertBytes); synchronized (sLock) { ensureTestInitializedLocked(); + // Add the cert to be used by the Android Platform Verifier. sTestKeyStore.setCertificateEntry( "root_cert_" + Integer.toString(sTestKeyStore.size()), rootCert); reloadTestTrustManager(); } } + /** + * Clear test root certificates in use by the Android Platform verifier. + */ public static void clearTestRootCertificates() throws NoSuchAlgorithmException, CertificateException, KeyStoreException { synchronized (sLock) { @@ -343,6 +355,22 @@ } } + /** + * Set a test root certificate for use by CertVerifierBuiltin. + */ + public static void setTestRootCertificateForBuiltin(byte[] rootCertBytes) + throws NoSuchAlgorithmException, CertificateException, KeyStoreException { + X509Certificate rootCert = createCertificateFromBytes(rootCertBytes); + synchronized (sLock) { + // Add the cert to be used by CertVerifierBuiltin. + // + // This saves the root so it is returned from getUserAddedRoots, for TrustStoreAndroid. + // This is done for the Java EmbeddedTestServer implementation and must run before + // native code is loaded, when getUserAddedRoots is first run. + sTestRoot = rootCert; + } + } + private static final char[] HEX_DIGITS = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f', @@ -503,6 +531,14 @@ Log.e(TAG, "Error reading cert aliases: %s", e); return new byte[0][]; } + + if (sTestRoot != null) { + try { + userRootBytes.add(sTestRoot.getEncoded()); + } catch (CertificateEncodingException e) { + Log.e(TAG, "Error encoding test root cert, error %s", e); + } + } } return userRootBytes.toArray(new byte[0][]);
diff --git a/net/test/android/javatests/AndroidManifest.xml b/net/test/android/javatests/AndroidManifest.xml index 830392b..e3ad40b6 100644 --- a/net/test/android/javatests/AndroidManifest.xml +++ b/net/test/android/javatests/AndroidManifest.xml
@@ -11,7 +11,8 @@ <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/> <uses-permission android:name="android.permission.INTERNET"/> - <application android:label="ChromiumNetTestSupport"> + <application android:label="ChromiumNetTestSupport" + android:name="androidx.multidex.MultiDexApplication"> <uses-library android:name="android.test.runner" />
diff --git a/net/test/android/javatests/src/org/chromium/net/test/EmbeddedTestServer.java b/net/test/android/javatests/src/org/chromium/net/test/EmbeddedTestServer.java index 1b560e5..de076f49 100644 --- a/net/test/android/javatests/src/org/chromium/net/test/EmbeddedTestServer.java +++ b/net/test/android/javatests/src/org/chromium/net/test/EmbeddedTestServer.java
@@ -18,6 +18,8 @@ import org.chromium.base.Log; import org.chromium.base.ThreadUtils; +import org.chromium.base.test.BaseJUnit4ClassRunner.ClassHook; +import org.chromium.base.test.util.UrlUtils; import org.chromium.net.X509Util; import org.chromium.net.test.util.CertTestUtil; @@ -525,4 +527,31 @@ throw new EmbeddedTestServerFailure("Failed to get root cert's path", e); } } + + public static ClassHook getPreClassHook() { + return (targetContext, testClass) -> EmbeddedTestServer.setUpClass(testClass); + } + + private static boolean sTestRootInitDone; + + public static void setUpClass(Class<?> clazz) { + if (sTestRootInitDone) { + return; + } + + // Always try to add the testing HTTPS root to the cert verifier. We do this here because we + // need this to happen before the native code loads the user-added roots, and this is the + // safest place to put it. + try { + // Use the same PEM file as net/test/embedded_test_server/embedded_test_server.cc. + String rootCertPemPath = + UrlUtils.getIsolatedTestFilePath("net/data/ssl/certificates/root_ca_cert.pem"); + byte[] rootCertBytesDer = CertTestUtil.pemToDer(rootCertPemPath); + X509Util.setTestRootCertificateForBuiltin(rootCertBytesDer); + sTestRootInitDone = true; + } catch (Exception e) { + throw new EmbeddedTestServer.EmbeddedTestServerFailure( + "Failed to install root certificate.", e); + } + } }
diff --git a/remoting/host/linux/clipboard_portal_injector.cc b/remoting/host/linux/clipboard_portal_injector.cc index 854c793..023a8d0a 100644 --- a/remoting/host/linux/clipboard_portal_injector.cc +++ b/remoting/host/linux/clipboard_portal_injector.cc
@@ -262,6 +262,15 @@ DCHECK(cancellable_); DCHECK(!session_handle_.empty()); + // we can only process one `SelectionRead` at a time, so eat any extra + // requests we receive. if any requests get eaten, then we perform another + // read to capture the latest contents. + if (pending_selection_read_) { + queued_selection_read_ = true; + return; + } + pending_selection_read_ = true; + g_dbus_proxy_call_with_unix_fd_list( proxy_, "SelectionRead", g_variant_new("(os)", session_handle_.c_str(), mime_type.c_str()), @@ -281,8 +290,17 @@ Scoped<GError> error; Scoped<GUnixFDList> outlist; + that->pending_selection_read_ = false; + Scoped<GVariant> variant(g_dbus_proxy_call_with_unix_fd_list_finish( proxy, outlist.receive(), result, error.receive())); + + if (that->queued_selection_read_) { + that->queued_selection_read_ = false; + that->SelectionRead(TranslateMimeTypeForPortal(kMimeTypeTextUtf8)); + return; + } + if (!variant) { LOG(ERROR) << "Failed to read selection: " << error->message; return;
diff --git a/remoting/host/linux/clipboard_portal_injector.h b/remoting/host/linux/clipboard_portal_injector.h index 1226d1a2..34d1fe68 100644 --- a/remoting/host/linux/clipboard_portal_injector.h +++ b/remoting/host/linux/clipboard_portal_injector.h
@@ -96,6 +96,9 @@ std::unordered_set<std::string> readable_mime_type_set_ GUARDED_BY_CONTEXT(sequence_checker_); + bool pending_selection_read_ GUARDED_BY_CONTEXT(sequence_checker_) = false; + bool queued_selection_read_ GUARDED_BY_CONTEXT(sequence_checker_) = false; + guint selection_owner_changed_signal_id_ = 0; guint selection_transfer_signal_id_ = 0; };
diff --git a/remoting/host/resources_mac.cc b/remoting/host/resources_mac.cc index b7dd3ac..ce9ffedd 100644 --- a/remoting/host/resources_mac.cc +++ b/remoting/host/resources_mac.cc
@@ -6,9 +6,9 @@ #include <dlfcn.h> +#include "base/apple/bundle_locations.h" #include "base/check.h" #include "base/files/file_path.h" -#include "base/mac/bundle_locations.h" #include "ui/base/l10n/l10n_util_mac.h" #include "ui/base/resource/resource_bundle.h" @@ -26,7 +26,7 @@ // DirName() calls strip "Contents/MacOS/<binary>" from the path. base::FilePath path = base::FilePath(info.dli_fname).DirName().DirName().DirName(); - base::mac::SetOverrideFrameworkBundlePath(path); + base::apple::SetOverrideFrameworkBundlePath(path); // Override the locale with the value from Cocoa. if (pref_locale.empty()) {
diff --git a/services/device/generic_sensor/BUILD.gn b/services/device/generic_sensor/BUILD.gn index b196fb1d..dacdaa57 100644 --- a/services/device/generic_sensor/BUILD.gn +++ b/services/device/generic_sensor/BUILD.gn
@@ -70,10 +70,7 @@ "platform_sensor_provider_android.cc", "platform_sensor_provider_android.h", ] - deps += [ - ":jni_headers", - "//services/device/public/cpp:device_feature_list", - ] + deps += [ ":jni_headers" ] } if (is_mac) { @@ -177,7 +174,6 @@ "//base:base_java", "//base:jni_java", "//build/android:build_java", - "//services/device/public/java:device_feature_list_java", "//services/device/public/mojom:generic_sensor_java", "//third_party/androidx:androidx_annotation_annotation_java", ]
diff --git a/services/device/generic_sensor/android/java/src/org/chromium/device/sensors/PlatformSensor.java b/services/device/generic_sensor/android/java/src/org/chromium/device/sensors/PlatformSensor.java index c4ac40c..a71f3500 100644 --- a/services/device/generic_sensor/android/java/src/org/chromium/device/sensors/PlatformSensor.java +++ b/services/device/generic_sensor/android/java/src/org/chromium/device/sensors/PlatformSensor.java
@@ -15,7 +15,6 @@ import org.chromium.base.annotations.CalledByNative; import org.chromium.base.annotations.JNINamespace; import org.chromium.base.annotations.NativeMethods; -import org.chromium.device.DeviceFeatureList; import org.chromium.device.mojom.ReportingMode; import org.chromium.device.mojom.SensorType; @@ -181,42 +180,9 @@ /** * Requests sensor to start polling for data. - * - * @return boolean true if successful, false otherwise. */ @CalledByNative - protected boolean startSensor(double frequency) { - // If we already polling hw with same frequency, do not restart the sensor. - if (mCurrentPollingFrequency == frequency) return true; - - // Unregister old listener if polling frequency has changed. - unregisterListener(); - - mProvider.sensorStarted(this); - boolean sensorStarted; - try { - sensorStarted = mProvider.getSensorManager().registerListener( - this, mSensor, getSamplingPeriod(frequency), mProvider.getHandler()); - } catch (RuntimeException e) { - // This can fail due to internal framework errors. https://crbug.com/884190 - Log.w(TAG, "Failed to register sensor listener.", e); - sensorStarted = false; - } - - if (!sensorStarted) { - stopSensor(); - return sensorStarted; - } - - mCurrentPollingFrequency = frequency; - return sensorStarted; - } - - /** - * Requests sensor to start polling for data. - */ - @CalledByNative - protected void startSensor2(double frequency) { + protected void startSensor(double frequency) { // If we already polling hw with same frequency, do not restart the sensor. if (mCurrentPollingFrequency == frequency) return; @@ -277,9 +243,6 @@ */ @CalledByNative protected void sensorDestroyed() { - if (!DeviceFeatureList.isEnabled(DeviceFeatureList.ASYNC_SENSOR_CALLS)) { - stopSensor(); - } synchronized (mLock) { mNativePlatformSensorAndroid = 0; }
diff --git a/services/device/generic_sensor/android/junit/src/org/chromium/device/sensors/PlatformSensorAndProviderTest.java b/services/device/generic_sensor/android/junit/src/org/chromium/device/sensors/PlatformSensorAndProviderTest.java index b2bd92d..b46ecf6 100644 --- a/services/device/generic_sensor/android/junit/src/org/chromium/device/sensors/PlatformSensorAndProviderTest.java +++ b/services/device/generic_sensor/android/junit/src/org/chromium/device/sensors/PlatformSensorAndProviderTest.java
@@ -40,8 +40,6 @@ import org.chromium.base.FeatureList; import org.chromium.base.test.BaseRobolectricTestRunner; import org.chromium.base.test.util.Feature; -import org.chromium.base.test.util.Features; -import org.chromium.device.DeviceFeatureList; import org.chromium.device.mojom.ReportingMode; import org.chromium.device.mojom.SensorType; @@ -109,7 +107,6 @@ @Before public void setUp() { FeatureList.TestValues testValues = new FeatureList.TestValues(); - testValues.addFeatureFlagOverride(DeviceFeatureList.ASYNC_SENSOR_CALLS, false); FeatureList.setTestValues(testValues); MockitoAnnotations.initMocks(this); @@ -242,46 +239,6 @@ } /** - * Test that PlatformSensor notifies PlatformSensorProvider when it starts (stops) polling, - * and SensorEventListener is registered (unregistered) to sensor manager. - */ - @Test - @Feature({"PlatformSensor"}) - public void testSensorStartStop2() { - Features.getInstance().enable(DeviceFeatureList.ASYNC_SENSOR_CALLS); - - addMockSensor(50000, Sensor.TYPE_ACCELEROMETER, Sensor.REPORTING_MODE_CONTINUOUS); - PlatformSensor sensor = PlatformSensor.create( - mPlatformSensorProvider, SensorType.ACCELEROMETER, PLATFORM_SENSOR_ANDROID); - assertNotNull(sensor); - - sensor.startSensor2(5); - sensor.stopSensor(); - - // Multiple start invocations. - sensor.startSensor2(1); - sensor.startSensor2(2); - sensor.startSensor2(3); - // Same frequency, should not restart sensor - sensor.startSensor2(3); - - // Started polling with 5, 1, 2 and 3 Hz frequency. - verify(mPlatformSensorProvider, times(4)).getHandler(); - verify(mPlatformSensorProvider, times(4)).sensorStarted(sensor); - verify(mSensorManager, times(4)) - .registerListener(any(SensorEventListener.class), any(Sensor.class), anyInt(), - any(Handler.class)); - - sensor.stopSensor(); - sensor.stopSensor(); - verify(mPlatformSensorProvider, times(3)).sensorStopped(sensor); - verify(mSensorManager, times(4)) - .unregisterListener(any(SensorEventListener.class), any(Sensor.class)); - - sensor.sensorDestroyed(); - } - - /** * Test that PlatformSensorProvider is notified when PlatformSensor starts and in case of * failure, tells PlatformSensorProvider that the sensor is stopped, so that polling thread * can be stopped. @@ -289,34 +246,6 @@ @Test @Feature({"PlatformSensor"}) public void testSensorStartFails() { - addMockSensor(50000, Sensor.TYPE_ACCELEROMETER, Sensor.REPORTING_MODE_CONTINUOUS); - PlatformSensor sensor = PlatformSensor.create( - mPlatformSensorProvider, SensorType.ACCELEROMETER, PLATFORM_SENSOR_ANDROID); - assertNotNull(sensor); - - doReturn(false) - .when(mSensorManager) - .registerListener(any(SensorEventListener.class), any(Sensor.class), anyInt(), - any(Handler.class)); - - sensor.startSensor(5); - verify(mPlatformSensorProvider, times(1)).sensorStarted(sensor); - verify(mPlatformSensorProvider, times(1)).sensorStopped(sensor); - verify(mPlatformSensorProvider, times(1)).getHandler(); - - sensor.sensorDestroyed(); - } - - /** - * Test that PlatformSensorProvider is notified when PlatformSensor starts and in case of - * failure, tells PlatformSensorProvider that the sensor is stopped, so that polling thread - * can be stopped. - */ - @Test - @Feature({"PlatformSensor"}) - public void testSensorStartFails2() { - Features.getInstance().enable(DeviceFeatureList.ASYNC_SENSOR_CALLS); - TestPlatformSensor sensor = createTestPlatformSensor( 50000, Sensor.TYPE_ACCELEROMETER, 3, Sensor.REPORTING_MODE_CONTINUOUS); TestPlatformSensor spySensor = spy(sensor); @@ -331,7 +260,7 @@ .registerListener(any(SensorEventListener.class), any(Sensor.class), anyInt(), any(Handler.class)); - spySensor.startSensor2(5); + spySensor.startSensor(5); verify(mPlatformSensorProvider, times(1)).sensorStarted(spySensor); verify(mPlatformSensorProvider, times(2)).sensorStopped(spySensor); verify(mPlatformSensorProvider, times(1)).getHandler(); @@ -346,31 +275,6 @@ @Test @Feature({"PlatformSensor"}) public void testSensorStartFailsWithException() { - addMockSensor(50000, Sensor.TYPE_ACCELEROMETER, Sensor.REPORTING_MODE_CONTINUOUS); - PlatformSensor sensor = PlatformSensor.create( - mPlatformSensorProvider, SensorType.ACCELEROMETER, PLATFORM_SENSOR_ANDROID); - assertNotNull(sensor); - - when(mSensorManager.registerListener(any(SensorEventListener.class), any(Sensor.class), - anyInt(), any(Handler.class))) - .thenThrow(RuntimeException.class); - - sensor.startSensor(5); - verify(mPlatformSensorProvider, times(1)).sensorStarted(sensor); - verify(mPlatformSensorProvider, times(1)).sensorStopped(sensor); - verify(mPlatformSensorProvider, times(1)).getHandler(); - - sensor.sensorDestroyed(); - } - - /** - * Same as the above except instead of a clean failure an exception is thrown. - */ - @Test - @Feature({"PlatformSensor"}) - public void testSensorStartFailsWithException2() { - Features.getInstance().enable(DeviceFeatureList.ASYNC_SENSOR_CALLS); - TestPlatformSensor sensor = createTestPlatformSensor( 50000, Sensor.TYPE_ACCELEROMETER, 3, Sensor.REPORTING_MODE_CONTINUOUS); TestPlatformSensor spySensor = spy(sensor); @@ -384,7 +288,7 @@ anyInt(), any(Handler.class))) .thenThrow(RuntimeException.class); - spySensor.startSensor2(5); + spySensor.startSensor(5); verify(mPlatformSensorProvider, times(1)).sensorStarted(spySensor); verify(mPlatformSensorProvider, times(2)).sensorStopped(spySensor); verify(mPlatformSensorProvider, times(1)).getHandler(); @@ -546,49 +450,6 @@ } /** - * Test that multiple PlatformSensor instances correctly register (unregister) to - * sensor manager and notify PlatformSensorProvider when they start (stop) polling for data. - */ - @Test - @Feature({"PlatformSensor"}) - public void testMultipleSensorTypeInstances2() { - Features.getInstance().enable(DeviceFeatureList.ASYNC_SENSOR_CALLS); - - addMockSensor(200000, Sensor.TYPE_LIGHT, Sensor.REPORTING_MODE_ON_CHANGE); - addMockSensor(50000, Sensor.TYPE_ACCELEROMETER, Sensor.REPORTING_MODE_CONTINUOUS); - - TestPlatformSensorProvider spyProvider = spy(new TestPlatformSensorProvider(mContext)); - PlatformSensor lightSensor = PlatformSensor.create( - spyProvider, SensorType.AMBIENT_LIGHT, PLATFORM_SENSOR_ANDROID); - assertNotNull(lightSensor); - - PlatformSensor accelerometerSensor = PlatformSensor.create( - spyProvider, SensorType.ACCELEROMETER, PLATFORM_SENSOR_ANDROID); - assertNotNull(accelerometerSensor); - - lightSensor.startSensor2(3); - accelerometerSensor.startSensor2(10); - lightSensor.stopSensor(); - accelerometerSensor.stopSensor(); - - verify(spyProvider, times(2)).getHandler(); - verify(spyProvider, times(1)).sensorStarted(lightSensor); - verify(spyProvider, times(1)).sensorStarted(accelerometerSensor); - verify(spyProvider, times(1)).sensorStopped(lightSensor); - verify(spyProvider, times(1)).sensorStopped(accelerometerSensor); - verify(spyProvider, times(1)).startSensorThread(); - verify(spyProvider, times(1)).stopSensorThread(); - verify(mSensorManager, times(2)) - .registerListener(any(SensorEventListener.class), any(Sensor.class), anyInt(), - any(Handler.class)); - verify(mSensorManager, times(2)) - .unregisterListener(any(SensorEventListener.class), any(Sensor.class)); - - lightSensor.sensorDestroyed(); - accelerometerSensor.sensorDestroyed(); - } - - /** * Creates fake event. The SensorEvent constructor is not accessible outside android.hardware * package, therefore, java reflection is used to make constructor accessible to construct * SensorEvent instance.
diff --git a/services/device/generic_sensor/platform_sensor.cc b/services/device/generic_sensor/platform_sensor.cc index e42d5113..0715bb6c 100644 --- a/services/device/generic_sensor/platform_sensor.cc +++ b/services/device/generic_sensor/platform_sensor.cc
@@ -10,7 +10,6 @@ #include "base/containers/cxx20_erase.h" #include "base/functional/bind.h" #include "base/functional/callback.h" -#include "base/no_destructor.h" #include "base/observer_list.h" #include "base/task/sequenced_task_runner.h" #include "services/device/generic_sensor/platform_sensor_provider.h" @@ -28,16 +27,12 @@ type_(type), provider_(provider), is_active_(false) { - CHECK(!PlatformSensor::GetInitializedSensors().contains(type)); - PlatformSensor::GetInitializedSensors().insert(type); VLOG(1) << "Platform sensor created. Type " << type_ << "."; } PlatformSensor::~PlatformSensor() { if (provider_) provider_->RemoveSensor(GetType(), this); - CHECK(PlatformSensor::GetInitializedSensors().contains(type_)); - PlatformSensor::GetInitializedSensors().erase(type_); VLOG(1) << "Platform sensor released. Type " << type_ << "."; } @@ -239,12 +234,6 @@ } } -base::flat_set<mojom::SensorType>& PlatformSensor::GetInitializedSensors() { - static base::NoDestructor<base::flat_set<mojom::SensorType>> - initialized_sensors; - return *initialized_sensors; -} - bool PlatformSensor::IsActiveForTesting() const { base::AutoLock auto_lock(lock_); return is_active_;
diff --git a/services/device/generic_sensor/platform_sensor.h b/services/device/generic_sensor/platform_sensor.h index b4ad4b6..48acccd 100644 --- a/services/device/generic_sensor/platform_sensor.h +++ b/services/device/generic_sensor/platform_sensor.h
@@ -9,7 +9,6 @@ #include <map> #include <memory> -#include "base/containers/flat_set.h" #include "base/functional/callback_forward.h" #include "base/location.h" #include "base/memory/raw_ptr.h" @@ -146,10 +145,6 @@ bool do_significance_check) EXCLUSIVE_LOCKS_REQUIRED(lock_); - // Check if multiple instances of PlatformSensor can exist at once. It weas - // first suggested in crbug.com/1383180. - static base::flat_set<mojom::SensorType>& GetInitializedSensors(); - scoped_refptr<base::SequencedTaskRunner> main_task_runner_; raw_ptr<SensorReadingSharedBuffer>
diff --git a/services/device/generic_sensor/platform_sensor_android.cc b/services/device/generic_sensor/platform_sensor_android.cc index 6800c60..04949f2 100644 --- a/services/device/generic_sensor/platform_sensor_android.cc +++ b/services/device/generic_sensor/platform_sensor_android.cc
@@ -5,9 +5,7 @@ #include "services/device/generic_sensor/platform_sensor_android.h" #include "base/functional/bind.h" -#include "base/metrics/field_trial_params.h" #include "services/device/generic_sensor/jni_headers/PlatformSensor_jni.h" -#include "services/device/public/cpp/device_features.h" using base::android::AttachCurrentThread; using base::android::JavaRef; @@ -16,8 +14,8 @@ namespace { void StartSensorBlocking(base::android::ScopedJavaGlobalRef<jobject> j_object, double frequency) { - device::Java_PlatformSensor_startSensor2(AttachCurrentThread(), j_object, - frequency); + device::Java_PlatformSensor_startSensor(AttachCurrentThread(), j_object, + frequency); } void StopSensorBlocking(base::android::ScopedJavaGlobalRef<jobject> j_object) { @@ -52,9 +50,7 @@ PlatformSensorAndroid::~PlatformSensorAndroid() { if (j_object_) { - if (base::FeatureList::IsEnabled(features::kAsyncSensorCalls)) { - StopSensor(); - } + StopSensor(); Java_PlatformSensor_sensorDestroyed(AttachCurrentThread(), j_object_); } } @@ -79,24 +75,15 @@ bool PlatformSensorAndroid::StartSensor( const PlatformSensorConfiguration& configuration) { - if (base::FeatureList::IsEnabled(features::kAsyncSensorCalls)) { - sequenced_task_runner_->PostTask( - FROM_HERE, base::BindOnce(&StartSensorBlocking, j_object_, - configuration.frequency())); - return true; - } else { - return Java_PlatformSensor_startSensor(AttachCurrentThread(), j_object_, - configuration.frequency()); - } + sequenced_task_runner_->PostTask( + FROM_HERE, base::BindOnce(&StartSensorBlocking, j_object_, + configuration.frequency())); + return true; } void PlatformSensorAndroid::StopSensor() { - if (base::FeatureList::IsEnabled(features::kAsyncSensorCalls)) { - sequenced_task_runner_->PostTask( - FROM_HERE, base::BindOnce(&StopSensorBlocking, j_object_)); - } else { - Java_PlatformSensor_stopSensor(AttachCurrentThread(), j_object_); - } + sequenced_task_runner_->PostTask( + FROM_HERE, base::BindOnce(&StopSensorBlocking, j_object_)); } bool PlatformSensorAndroid::CheckSensorConfiguration(
diff --git a/services/device/generic_sensor/platform_sensor_android.h b/services/device/generic_sensor/platform_sensor_android.h index 01712eb..9d7a285 100644 --- a/services/device/generic_sensor/platform_sensor_android.h +++ b/services/device/generic_sensor/platform_sensor_android.h
@@ -12,6 +12,7 @@ #include "services/device/generic_sensor/platform_sensor.h" namespace device { + class PlatformSensorAndroid : public PlatformSensor { public: // Creates a new PlatformSensorAndroid for the given sensor type, returning @@ -58,6 +59,7 @@ const scoped_refptr<base::SequencedTaskRunner> sequenced_task_runner_ = base::ThreadPool::CreateSequencedTaskRunner({base::MayBlock()}); }; + } // namespace device #endif // SERVICES_DEVICE_GENERIC_SENSOR_PLATFORM_SENSOR_ANDROID_H_
diff --git a/services/device/hid/hid_connection_linux.cc b/services/device/hid/hid_connection_linux.cc index 9b68928..02c30ba 100644 --- a/services/device/hid/hid_connection_linux.cc +++ b/services/device/hid/hid_connection_linux.cc
@@ -212,7 +212,8 @@ auto callback_wrapper = base::BindOnce( [](ReadCallback callback, std::tuple<bool, scoped_refptr<base::RefCountedBytes>, int> result) { - std::move(callback).Run(get<0>(result), get<1>(result), get<2>(result)); + std::move(callback).Run(std::get<0>(result), std::get<1>(result), + std::get<2>(result)); }, std::move(callback));
diff --git a/services/device/public/cpp/device_feature_list.cc b/services/device/public/cpp/device_feature_list.cc index 9a92cec..4c00a7e9 100644 --- a/services/device/public/cpp/device_feature_list.cc +++ b/services/device/public/cpp/device_feature_list.cc
@@ -21,8 +21,6 @@ // in other locations in the code base (e.g. content_features.h). const base::Feature* const kFeaturesExposedToJava[] = { &device::kWebAuthnAndroidCredMan, - &device::kWebAuthnHybridLinkWithoutNotifications, - &kAsyncSensorCalls, &kGenericSensorExtraClasses, };
diff --git a/services/device/public/cpp/device_features.cc b/services/device/public/cpp/device_features.cc index 2d2bb27..bdd85a0b 100644 --- a/services/device/public/cpp/device_features.cc +++ b/services/device/public/cpp/device_features.cc
@@ -21,11 +21,6 @@ BASE_FEATURE(kMacCoreLocationBackend, "MacCoreLocationBackend", base::FEATURE_DISABLED_BY_DEFAULT); -// Enables async calls to stopSensor and startSensor on a different thread than -// the main thread. -BASE_FEATURE(kAsyncSensorCalls, - "AsyncSensorCalls", - base::FEATURE_ENABLED_BY_DEFAULT); // Reduces the interval between WiFi polls to fetch new WiFi data sooner. This // can be useful in situations where new WiFi data is needed frequently. BASE_FEATURE(kCrOSGeolocationReducedWifiPollingInterval,
diff --git a/services/device/public/cpp/device_features.h b/services/device/public/cpp/device_features.h index ca1bc261..ca3df8c 100644 --- a/services/device/public/cpp/device_features.h +++ b/services/device/public/cpp/device_features.h
@@ -19,7 +19,6 @@ DEVICE_FEATURES_EXPORT BASE_DECLARE_FEATURE(kGenericSensorExtraClasses); DEVICE_FEATURES_EXPORT BASE_DECLARE_FEATURE(kWinrtGeolocationImplementation); DEVICE_FEATURES_EXPORT BASE_DECLARE_FEATURE(kMacCoreLocationBackend); -DEVICE_FEATURES_EXPORT BASE_DECLARE_FEATURE(kAsyncSensorCalls); DEVICE_FEATURES_EXPORT BASE_DECLARE_FEATURE( kCrOSGeolocationReducedWifiPollingInterval);
diff --git a/services/device/public/java/src/org/chromium/device/DeviceFeatureList.java b/services/device/public/java/src/org/chromium/device/DeviceFeatureList.java index 45f02f8a..d47ee2f5 100644 --- a/services/device/public/java/src/org/chromium/device/DeviceFeatureList.java +++ b/services/device/public/java/src/org/chromium/device/DeviceFeatureList.java
@@ -14,7 +14,6 @@ // TODO(crbug.com/1060097): Remove/update this once a generalized FeatureList exists. @JNINamespace("features") public class DeviceFeatureList { - public static final String ASYNC_SENSOR_CALLS = "AsyncSensorCalls"; public static final String GENERIC_SENSOR_EXTRA_CLASSES = "GenericSensorExtraClasses"; public static final String WEBAUTHN_ANDROID_CRED_MAN = "WebAuthenticationAndroidCredMan"; public static final String WEBAUTHN_HYBRID_LINK_WITHOUT_NOTIFICATIONS =
diff --git a/services/network/cors/preflight_cache.cc b/services/network/cors/preflight_cache.cc index b5fe078..6bec2c7 100644 --- a/services/network/cors/preflight_cache.cc +++ b/services/network/cors/preflight_cache.cc
@@ -172,7 +172,7 @@ for (auto it = cache_.begin(); it != cache_.end();) { auto next_it = std::next(it); - auto cached_url = get<0>(it->first).GetURL(); + auto cached_url = std::get<0>(it->first).GetURL(); if (network::DoesUrlMatchFilter(url_filter->type, origins, domains, cached_url)) { cache_.erase(it);
diff --git a/services/network/restricted_cookie_manager_unittest.cc b/services/network/restricted_cookie_manager_unittest.cc index 8d484ef..85c588d9 100644 --- a/services/network/restricted_cookie_manager_unittest.cc +++ b/services/network/restricted_cookie_manager_unittest.cc
@@ -542,7 +542,7 @@ testing::Values( net::CookieSettingOverrides(), net::CookieSettingOverrides( - net::CookieSettingOverride::kForceThirdPartyByUser)))); + {net::CookieSettingOverride::kForceThirdPartyByUser})))); namespace { @@ -2016,7 +2016,7 @@ testing::Values( net::CookieSettingOverrides(), net::CookieSettingOverrides( - net::CookieSettingOverride::kForceThirdPartyByUser)))); + {net::CookieSettingOverride::kForceThirdPartyByUser})))); class UnpartitionedCookiesRestrictedCookieManagerTest : public RestrictedCookieManagerTest { @@ -2463,6 +2463,6 @@ testing::Values( net::CookieSettingOverrides(), net::CookieSettingOverrides( - net::CookieSettingOverride::kForceThirdPartyByUser)))); + {net::CookieSettingOverride::kForceThirdPartyByUser})))); } // namespace network
diff --git a/services/service_manager/BUILD.gn b/services/service_manager/BUILD.gn index 00c7045b..b39f414 100644 --- a/services/service_manager/BUILD.gn +++ b/services/service_manager/BUILD.gn
@@ -65,10 +65,6 @@ "//mojo/core/embedder", "//services/service_manager/public/cpp/service_executable:switches", ] - - if (is_mac) { - public_deps += [ "//base:base_arc" ] - } } if (is_linux || is_chromeos) {
diff --git a/services/service_manager/public/cpp/service_executable/main.cc b/services/service_manager/public/cpp/service_executable/main.cc index ebf7096..57b4326b 100644 --- a/services/service_manager/public/cpp/service_executable/main.cc +++ b/services/service_manager/public/cpp/service_executable/main.cc
@@ -23,7 +23,7 @@ #include "services/service_manager/public/mojom/service.mojom.h" #if BUILDFLAG(IS_MAC) -#include "base/mac/bundle_locations.h" +#include "base/apple/bundle_locations.h" #endif #if BUILDFLAG(IS_WIN)
diff --git a/sql/sqlite_features_unittest.cc b/sql/sqlite_features_unittest.cc index 6fb0517e..29d4208 100644 --- a/sql/sqlite_features_unittest.cc +++ b/sql/sqlite_features_unittest.cc
@@ -22,7 +22,7 @@ #include "third_party/sqlite/sqlite3.h" #if BUILDFLAG(IS_APPLE) -#include "base/mac/backup_util.h" +#include "base/apple/backup_util.h" #endif // Test that certain features are/are-not enabled in our SQLite. @@ -627,19 +627,19 @@ ASSERT_TRUE(base::PathExists(journal_path)); // Not excluded to start. - EXPECT_FALSE(base::mac::GetBackupExclusion(db_path_)); - EXPECT_FALSE(base::mac::GetBackupExclusion(journal_path)); + EXPECT_FALSE(base::apple::GetBackupExclusion(db_path_)); + EXPECT_FALSE(base::apple::GetBackupExclusion(journal_path)); // Exclude the main database file. - EXPECT_TRUE(base::mac::SetBackupExclusion(db_path_)); + EXPECT_TRUE(base::apple::SetBackupExclusion(db_path_)); - EXPECT_TRUE(base::mac::GetBackupExclusion(db_path_)); - EXPECT_FALSE(base::mac::GetBackupExclusion(journal_path)); + EXPECT_TRUE(base::apple::GetBackupExclusion(db_path_)); + EXPECT_FALSE(base::apple::GetBackupExclusion(journal_path)); EXPECT_TRUE(db_.Open(db_path_)); ASSERT_TRUE(db_.Execute("INSERT INTO t VALUES (1)")); - EXPECT_TRUE(base::mac::GetBackupExclusion(db_path_)); - EXPECT_TRUE(base::mac::GetBackupExclusion(journal_path)); + EXPECT_TRUE(base::apple::GetBackupExclusion(db_path_)); + EXPECT_TRUE(base::apple::GetBackupExclusion(journal_path)); // TODO(shess): In WAL mode this will touch -wal and -shm files. -shm files // could be always excluded.
diff --git a/sql/vfs_wrapper.cc b/sql/vfs_wrapper.cc index 5a820fc..f8b3cf9 100644 --- a/sql/vfs_wrapper.cc +++ b/sql/vfs_wrapper.cc
@@ -18,7 +18,7 @@ #include "build/build_config.h" #if BUILDFLAG(IS_APPLE) -#include "base/mac/backup_util.h" +#include "base/apple/backup_util.h" #endif #if BUILDFLAG(IS_FUCHSIA) @@ -206,8 +206,8 @@ size_t dash_index = file_name_string_piece.rfind('-'); if (dash_index != base::StringPiece::npos) { base::StringPiece db_name(file_name, dash_index); - if (base::mac::GetBackupExclusion(base::FilePath(db_name))) { - base::mac::SetBackupExclusion(base::FilePath(file_name_string_piece)); + if (base::apple::GetBackupExclusion(base::FilePath(db_name))) { + base::apple::SetBackupExclusion(base::FilePath(file_name_string_piece)); } } }
diff --git a/styleguide/swift/OWNERS b/styleguide/swift/OWNERS index 3f88f384..04c64383 100644 --- a/styleguide/swift/OWNERS +++ b/styleguide/swift/OWNERS
@@ -1,2 +1 @@ -pinkerton@chromium.org rkgibson@google.com
diff --git a/testing/buildbot/chromium.chromiumos.json b/testing/buildbot/chromium.chromiumos.json index ebf9100..8965f2c 100644 --- a/testing/buildbot/chromium.chromiumos.json +++ b/testing/buildbot/chromium.chromiumos.json
@@ -5730,9 +5730,9 @@ { "args": [ "--test-launcher-filter-file=../../testing/buildbot/filters/linux-lacros.interactive_ui_tests.filter;../../testing/buildbot/filters/linux-lacros.interactive_ui_tests.skew.filter", - "--ash-chrome-path-override=../../lacros_version_skew_tests_v115.0.5766.0/test_ash_chrome" + "--ash-chrome-path-override=../../lacros_version_skew_tests_v115.0.5767.0/test_ash_chrome" ], - "description": "Run with ash-chrome version 115.0.5766.0", + "description": "Run with ash-chrome version 115.0.5767.0", "isolate_profile_data": true, "merge": { "script": "//testing/merge_scripts/standard_gtest_merge.py" @@ -5743,8 +5743,8 @@ "cipd_packages": [ { "cipd_package": "chromium/testing/linux-ash-chromium/x86_64/ash.zip", - "location": "lacros_version_skew_tests_v115.0.5766.0", - "revision": "version:115.0.5766.0" + "location": "lacros_version_skew_tests_v115.0.5767.0", + "revision": "version:115.0.5767.0" } ], "dimension_sets": [ @@ -5895,9 +5895,9 @@ { "args": [ "--test-launcher-filter-file=../../testing/buildbot/filters/linux-lacros.lacros_chrome_browsertests.skew.filter", - "--ash-chrome-path-override=../../lacros_version_skew_tests_v115.0.5766.0/test_ash_chrome" + "--ash-chrome-path-override=../../lacros_version_skew_tests_v115.0.5767.0/test_ash_chrome" ], - "description": "Run with ash-chrome version 115.0.5766.0", + "description": "Run with ash-chrome version 115.0.5767.0", "isolate_profile_data": true, "merge": { "script": "//testing/merge_scripts/standard_gtest_merge.py" @@ -5908,8 +5908,8 @@ "cipd_packages": [ { "cipd_package": "chromium/testing/linux-ash-chromium/x86_64/ash.zip", - "location": "lacros_version_skew_tests_v115.0.5766.0", - "revision": "version:115.0.5766.0" + "location": "lacros_version_skew_tests_v115.0.5767.0", + "revision": "version:115.0.5767.0" } ], "dimension_sets": [ @@ -6042,9 +6042,9 @@ { "args": [ "--test-launcher-filter-file=../../testing/buildbot/filters/linux-lacros.lacros_chrome_browsertests.skew.filter", - "--ash-chrome-path-override=../../lacros_version_skew_tests_v115.0.5766.0/test_ash_chrome" + "--ash-chrome-path-override=../../lacros_version_skew_tests_v115.0.5767.0/test_ash_chrome" ], - "description": "Run with ash-chrome version 115.0.5766.0", + "description": "Run with ash-chrome version 115.0.5767.0", "isolate_profile_data": true, "merge": { "script": "//testing/merge_scripts/standard_gtest_merge.py" @@ -6055,8 +6055,8 @@ "cipd_packages": [ { "cipd_package": "chromium/testing/linux-ash-chromium/x86_64/ash.zip", - "location": "lacros_version_skew_tests_v115.0.5766.0", - "revision": "version:115.0.5766.0" + "location": "lacros_version_skew_tests_v115.0.5767.0", + "revision": "version:115.0.5767.0" } ], "dimension_sets": [
diff --git a/testing/buildbot/chromium.coverage.json b/testing/buildbot/chromium.coverage.json index de0844f..42639fa5 100644 --- a/testing/buildbot/chromium.coverage.json +++ b/testing/buildbot/chromium.coverage.json
@@ -25491,9 +25491,9 @@ { "args": [ "--test-launcher-filter-file=../../testing/buildbot/filters/linux-lacros.interactive_ui_tests.filter;../../testing/buildbot/filters/linux-lacros.interactive_ui_tests.skew.filter", - "--ash-chrome-path-override=../../lacros_version_skew_tests_v115.0.5766.0/test_ash_chrome" + "--ash-chrome-path-override=../../lacros_version_skew_tests_v115.0.5767.0/test_ash_chrome" ], - "description": "Run with ash-chrome version 115.0.5766.0", + "description": "Run with ash-chrome version 115.0.5767.0", "isolate_profile_data": true, "merge": { "script": "//testing/merge_scripts/standard_gtest_merge.py" @@ -25504,8 +25504,8 @@ "cipd_packages": [ { "cipd_package": "chromium/testing/linux-ash-chromium/x86_64/ash.zip", - "location": "lacros_version_skew_tests_v115.0.5766.0", - "revision": "version:115.0.5766.0" + "location": "lacros_version_skew_tests_v115.0.5767.0", + "revision": "version:115.0.5767.0" } ], "dimension_sets": [ @@ -25656,9 +25656,9 @@ { "args": [ "--test-launcher-filter-file=../../testing/buildbot/filters/linux-lacros.lacros_chrome_browsertests.skew.filter", - "--ash-chrome-path-override=../../lacros_version_skew_tests_v115.0.5766.0/test_ash_chrome" + "--ash-chrome-path-override=../../lacros_version_skew_tests_v115.0.5767.0/test_ash_chrome" ], - "description": "Run with ash-chrome version 115.0.5766.0", + "description": "Run with ash-chrome version 115.0.5767.0", "isolate_profile_data": true, "merge": { "script": "//testing/merge_scripts/standard_gtest_merge.py" @@ -25669,8 +25669,8 @@ "cipd_packages": [ { "cipd_package": "chromium/testing/linux-ash-chromium/x86_64/ash.zip", - "location": "lacros_version_skew_tests_v115.0.5766.0", - "revision": "version:115.0.5766.0" + "location": "lacros_version_skew_tests_v115.0.5767.0", + "revision": "version:115.0.5767.0" } ], "dimension_sets": [ @@ -25803,9 +25803,9 @@ { "args": [ "--test-launcher-filter-file=../../testing/buildbot/filters/linux-lacros.lacros_chrome_browsertests.skew.filter", - "--ash-chrome-path-override=../../lacros_version_skew_tests_v115.0.5766.0/test_ash_chrome" + "--ash-chrome-path-override=../../lacros_version_skew_tests_v115.0.5767.0/test_ash_chrome" ], - "description": "Run with ash-chrome version 115.0.5766.0", + "description": "Run with ash-chrome version 115.0.5767.0", "isolate_profile_data": true, "merge": { "script": "//testing/merge_scripts/standard_gtest_merge.py" @@ -25816,8 +25816,8 @@ "cipd_packages": [ { "cipd_package": "chromium/testing/linux-ash-chromium/x86_64/ash.zip", - "location": "lacros_version_skew_tests_v115.0.5766.0", - "revision": "version:115.0.5766.0" + "location": "lacros_version_skew_tests_v115.0.5767.0", + "revision": "version:115.0.5767.0" } ], "dimension_sets": [
diff --git a/testing/buildbot/chromium.fyi.json b/testing/buildbot/chromium.fyi.json index d4b3b6e..e676520 100644 --- a/testing/buildbot/chromium.fyi.json +++ b/testing/buildbot/chromium.fyi.json
@@ -41382,9 +41382,9 @@ { "args": [ "--test-launcher-filter-file=../../testing/buildbot/filters/linux-lacros.interactive_ui_tests.filter;../../testing/buildbot/filters/linux-lacros.interactive_ui_tests.skew.filter", - "--ash-chrome-path-override=../../lacros_version_skew_tests_v115.0.5766.0/test_ash_chrome" + "--ash-chrome-path-override=../../lacros_version_skew_tests_v115.0.5767.0/test_ash_chrome" ], - "description": "Run with ash-chrome version 115.0.5766.0", + "description": "Run with ash-chrome version 115.0.5767.0", "merge": { "script": "//testing/merge_scripts/standard_gtest_merge.py" }, @@ -41394,8 +41394,8 @@ "cipd_packages": [ { "cipd_package": "chromium/testing/linux-ash-chromium/x86_64/ash.zip", - "location": "lacros_version_skew_tests_v115.0.5766.0", - "revision": "version:115.0.5766.0" + "location": "lacros_version_skew_tests_v115.0.5767.0", + "revision": "version:115.0.5767.0" } ], "dimension_sets": [ @@ -41547,9 +41547,9 @@ { "args": [ "--test-launcher-filter-file=../../testing/buildbot/filters/linux-lacros.lacros_chrome_browsertests.skew.filter", - "--ash-chrome-path-override=../../lacros_version_skew_tests_v115.0.5766.0/test_ash_chrome" + "--ash-chrome-path-override=../../lacros_version_skew_tests_v115.0.5767.0/test_ash_chrome" ], - "description": "Run with ash-chrome version 115.0.5766.0", + "description": "Run with ash-chrome version 115.0.5767.0", "merge": { "script": "//testing/merge_scripts/standard_gtest_merge.py" }, @@ -41559,8 +41559,8 @@ "cipd_packages": [ { "cipd_package": "chromium/testing/linux-ash-chromium/x86_64/ash.zip", - "location": "lacros_version_skew_tests_v115.0.5766.0", - "revision": "version:115.0.5766.0" + "location": "lacros_version_skew_tests_v115.0.5767.0", + "revision": "version:115.0.5767.0" } ], "dimension_sets": [ @@ -41694,9 +41694,9 @@ { "args": [ "--test-launcher-filter-file=../../testing/buildbot/filters/linux-lacros.lacros_chrome_browsertests.skew.filter", - "--ash-chrome-path-override=../../lacros_version_skew_tests_v115.0.5766.0/test_ash_chrome" + "--ash-chrome-path-override=../../lacros_version_skew_tests_v115.0.5767.0/test_ash_chrome" ], - "description": "Run with ash-chrome version 115.0.5766.0", + "description": "Run with ash-chrome version 115.0.5767.0", "merge": { "script": "//testing/merge_scripts/standard_gtest_merge.py" }, @@ -41706,8 +41706,8 @@ "cipd_packages": [ { "cipd_package": "chromium/testing/linux-ash-chromium/x86_64/ash.zip", - "location": "lacros_version_skew_tests_v115.0.5766.0", - "revision": "version:115.0.5766.0" + "location": "lacros_version_skew_tests_v115.0.5767.0", + "revision": "version:115.0.5767.0" } ], "dimension_sets": [ @@ -43171,9 +43171,9 @@ { "args": [ "--test-launcher-filter-file=../../testing/buildbot/filters/linux-lacros.interactive_ui_tests.filter;../../testing/buildbot/filters/linux-lacros.interactive_ui_tests.skew.filter", - "--ash-chrome-path-override=../../lacros_version_skew_tests_v115.0.5766.0/test_ash_chrome" + "--ash-chrome-path-override=../../lacros_version_skew_tests_v115.0.5767.0/test_ash_chrome" ], - "description": "Run with ash-chrome version 115.0.5766.0", + "description": "Run with ash-chrome version 115.0.5767.0", "merge": { "script": "//testing/merge_scripts/standard_gtest_merge.py" }, @@ -43183,8 +43183,8 @@ "cipd_packages": [ { "cipd_package": "chromium/testing/linux-ash-chromium/x86_64/ash.zip", - "location": "lacros_version_skew_tests_v115.0.5766.0", - "revision": "version:115.0.5766.0" + "location": "lacros_version_skew_tests_v115.0.5767.0", + "revision": "version:115.0.5767.0" } ], "dimension_sets": [ @@ -43336,9 +43336,9 @@ { "args": [ "--test-launcher-filter-file=../../testing/buildbot/filters/linux-lacros.lacros_chrome_browsertests.skew.filter", - "--ash-chrome-path-override=../../lacros_version_skew_tests_v115.0.5766.0/test_ash_chrome" + "--ash-chrome-path-override=../../lacros_version_skew_tests_v115.0.5767.0/test_ash_chrome" ], - "description": "Run with ash-chrome version 115.0.5766.0", + "description": "Run with ash-chrome version 115.0.5767.0", "merge": { "script": "//testing/merge_scripts/standard_gtest_merge.py" }, @@ -43348,8 +43348,8 @@ "cipd_packages": [ { "cipd_package": "chromium/testing/linux-ash-chromium/x86_64/ash.zip", - "location": "lacros_version_skew_tests_v115.0.5766.0", - "revision": "version:115.0.5766.0" + "location": "lacros_version_skew_tests_v115.0.5767.0", + "revision": "version:115.0.5767.0" } ], "dimension_sets": [ @@ -43483,9 +43483,9 @@ { "args": [ "--test-launcher-filter-file=../../testing/buildbot/filters/linux-lacros.lacros_chrome_browsertests.skew.filter", - "--ash-chrome-path-override=../../lacros_version_skew_tests_v115.0.5766.0/test_ash_chrome" + "--ash-chrome-path-override=../../lacros_version_skew_tests_v115.0.5767.0/test_ash_chrome" ], - "description": "Run with ash-chrome version 115.0.5766.0", + "description": "Run with ash-chrome version 115.0.5767.0", "merge": { "script": "//testing/merge_scripts/standard_gtest_merge.py" }, @@ -43495,8 +43495,8 @@ "cipd_packages": [ { "cipd_package": "chromium/testing/linux-ash-chromium/x86_64/ash.zip", - "location": "lacros_version_skew_tests_v115.0.5766.0", - "revision": "version:115.0.5766.0" + "location": "lacros_version_skew_tests_v115.0.5767.0", + "revision": "version:115.0.5767.0" } ], "dimension_sets": [ @@ -44231,9 +44231,9 @@ { "args": [ "--test-launcher-filter-file=../../testing/buildbot/filters/linux-lacros.interactive_ui_tests.filter;../../testing/buildbot/filters/linux-lacros.interactive_ui_tests.skew.filter", - "--ash-chrome-path-override=../../lacros_version_skew_tests_v115.0.5766.0/test_ash_chrome" + "--ash-chrome-path-override=../../lacros_version_skew_tests_v115.0.5767.0/test_ash_chrome" ], - "description": "Run with ash-chrome version 115.0.5766.0", + "description": "Run with ash-chrome version 115.0.5767.0", "merge": { "script": "//testing/merge_scripts/standard_gtest_merge.py" }, @@ -44243,8 +44243,8 @@ "cipd_packages": [ { "cipd_package": "chromium/testing/linux-ash-chromium/x86_64/ash.zip", - "location": "lacros_version_skew_tests_v115.0.5766.0", - "revision": "version:115.0.5766.0" + "location": "lacros_version_skew_tests_v115.0.5767.0", + "revision": "version:115.0.5767.0" } ], "dimension_sets": [
diff --git a/testing/buildbot/chromium.memory.json b/testing/buildbot/chromium.memory.json index 707e741..db344f8 100644 --- a/testing/buildbot/chromium.memory.json +++ b/testing/buildbot/chromium.memory.json
@@ -18080,12 +18080,12 @@ { "args": [ "--test-launcher-filter-file=../../testing/buildbot/filters/linux-lacros.interactive_ui_tests.filter;../../testing/buildbot/filters/linux-lacros.interactive_ui_tests.skew.filter", - "--ash-chrome-path-override=../../lacros_version_skew_tests_v115.0.5766.0/test_ash_chrome", + "--ash-chrome-path-override=../../lacros_version_skew_tests_v115.0.5767.0/test_ash_chrome", "--test-launcher-print-test-stdio=always", "--combine-ash-logs-on-bots", "--asan-symbolize-output" ], - "description": "Run with ash-chrome version 115.0.5766.0", + "description": "Run with ash-chrome version 115.0.5767.0", "isolate_profile_data": true, "merge": { "script": "//testing/merge_scripts/standard_gtest_merge.py" @@ -18096,8 +18096,8 @@ "cipd_packages": [ { "cipd_package": "chromium/testing/linux-ash-chromium/x86_64/ash.zip", - "location": "lacros_version_skew_tests_v115.0.5766.0", - "revision": "version:115.0.5766.0" + "location": "lacros_version_skew_tests_v115.0.5767.0", + "revision": "version:115.0.5767.0" } ], "dimension_sets": [ @@ -18265,12 +18265,12 @@ { "args": [ "--test-launcher-filter-file=../../testing/buildbot/filters/linux-lacros.lacros_chrome_browsertests.skew.filter", - "--ash-chrome-path-override=../../lacros_version_skew_tests_v115.0.5766.0/test_ash_chrome", + "--ash-chrome-path-override=../../lacros_version_skew_tests_v115.0.5767.0/test_ash_chrome", "--test-launcher-print-test-stdio=always", "--combine-ash-logs-on-bots", "--asan-symbolize-output" ], - "description": "Run with ash-chrome version 115.0.5766.0", + "description": "Run with ash-chrome version 115.0.5767.0", "isolate_profile_data": true, "merge": { "script": "//testing/merge_scripts/standard_gtest_merge.py" @@ -18281,8 +18281,8 @@ "cipd_packages": [ { "cipd_package": "chromium/testing/linux-ash-chromium/x86_64/ash.zip", - "location": "lacros_version_skew_tests_v115.0.5766.0", - "revision": "version:115.0.5766.0" + "location": "lacros_version_skew_tests_v115.0.5767.0", + "revision": "version:115.0.5767.0" } ], "dimension_sets": [ @@ -18427,12 +18427,12 @@ { "args": [ "--test-launcher-filter-file=../../testing/buildbot/filters/linux-lacros.lacros_chrome_browsertests.skew.filter", - "--ash-chrome-path-override=../../lacros_version_skew_tests_v115.0.5766.0/test_ash_chrome", + "--ash-chrome-path-override=../../lacros_version_skew_tests_v115.0.5767.0/test_ash_chrome", "--test-launcher-print-test-stdio=always", "--combine-ash-logs-on-bots", "--asan-symbolize-output" ], - "description": "Run with ash-chrome version 115.0.5766.0", + "description": "Run with ash-chrome version 115.0.5767.0", "isolate_profile_data": true, "merge": { "script": "//testing/merge_scripts/standard_gtest_merge.py" @@ -18443,8 +18443,8 @@ "cipd_packages": [ { "cipd_package": "chromium/testing/linux-ash-chromium/x86_64/ash.zip", - "location": "lacros_version_skew_tests_v115.0.5766.0", - "revision": "version:115.0.5766.0" + "location": "lacros_version_skew_tests_v115.0.5767.0", + "revision": "version:115.0.5767.0" } ], "dimension_sets": [
diff --git a/testing/buildbot/internal.chrome.fyi.json b/testing/buildbot/internal.chrome.fyi.json index 43affda7..7a81e95 100644 --- a/testing/buildbot/internal.chrome.fyi.json +++ b/testing/buildbot/internal.chrome.fyi.json
@@ -97,36 +97,6 @@ "service_account": "chrome-tester@chops-service-accounts.iam.gserviceaccount.com" }, "test_id_prefix": "ninja://chrome/test/variations:variations_desktop_smoke_tests/" - }, - { - "args": [ - "--git-revision=${got_revision}" - ], - "isolate_name": "variations_smoke_tests", - "merge": { - "script": "//testing/merge_scripts/standard_isolated_script_merge.py" - }, - "name": "variations_smoke_tests", - "precommit_args": [ - "--gerrit-issue=${patch_issue}", - "--gerrit-patchset=${patch_set}", - "--buildbucket-id=${buildbucket_build_id}" - ], - "resultdb": { - "enable": true, - "result_format": "single" - }, - "swarming": { - "can_use_on_swarming_builders": true, - "dimension_sets": [ - { - "os": "Ubuntu-18.04", - "pool": "chrome.tests.finch" - } - ], - "service_account": "chrome-tester@chops-service-accounts.iam.gserviceaccount.com" - }, - "test_id_prefix": "ninja://chrome/test:variations_smoke_tests/" } ] }, @@ -162,37 +132,6 @@ "service_account": "chrome-tester@chops-service-accounts.iam.gserviceaccount.com" }, "test_id_prefix": "ninja://chrome/test/variations:variations_desktop_smoke_tests/" - }, - { - "args": [ - "--git-revision=${got_revision}" - ], - "isolate_name": "variations_smoke_tests", - "merge": { - "script": "//testing/merge_scripts/standard_isolated_script_merge.py" - }, - "name": "variations_smoke_tests", - "precommit_args": [ - "--gerrit-issue=${patch_issue}", - "--gerrit-patchset=${patch_set}", - "--buildbucket-id=${buildbucket_build_id}" - ], - "resultdb": { - "enable": true, - "result_format": "single" - }, - "swarming": { - "can_use_on_swarming_builders": true, - "dimension_sets": [ - { - "cpu": "arm64", - "os": "Mac-12", - "pool": "chrome.tests.finch" - } - ], - "service_account": "chrome-tester@chops-service-accounts.iam.gserviceaccount.com" - }, - "test_id_prefix": "ninja://chrome/test:variations_smoke_tests/" } ] }, @@ -2823,36 +2762,6 @@ "service_account": "chrome-tester@chops-service-accounts.iam.gserviceaccount.com" }, "test_id_prefix": "ninja://chrome/test/variations:variations_desktop_smoke_tests/" - }, - { - "args": [ - "--git-revision=${got_revision}" - ], - "isolate_name": "variations_smoke_tests", - "merge": { - "script": "//testing/merge_scripts/standard_isolated_script_merge.py" - }, - "name": "variations_smoke_tests", - "precommit_args": [ - "--gerrit-issue=${patch_issue}", - "--gerrit-patchset=${patch_set}", - "--buildbucket-id=${buildbucket_build_id}" - ], - "resultdb": { - "enable": true, - "result_format": "single" - }, - "swarming": { - "can_use_on_swarming_builders": true, - "dimension_sets": [ - { - "os": "Windows-10", - "pool": "chrome.tests.finch" - } - ], - "service_account": "chrome-tester@chops-service-accounts.iam.gserviceaccount.com" - }, - "test_id_prefix": "ninja://chrome/test:variations_smoke_tests/" } ] }
diff --git a/testing/buildbot/internal.chromeos.fyi.json b/testing/buildbot/internal.chromeos.fyi.json index b4aaca4..134638a7 100644 --- a/testing/buildbot/internal.chromeos.fyi.json +++ b/testing/buildbot/internal.chromeos.fyi.json
@@ -1104,6 +1104,56 @@ "test": "chrome_variations_tast_tests", "test_id_prefix": "ninja://chromeos:chrome_variations_tast_tests/" } + ], + "isolated_scripts": [ + { + "args": [ + "--target-platform=cros", + "--magic-vm-cache=magic_cros_vm_cache", + "--git-revision=${got_revision}" + ], + "isolate_name": "variations_desktop_smoke_tests", + "merge": { + "script": "//testing/merge_scripts/standard_isolated_script_merge.py" + }, + "name": "variations_desktop_smoke_tests", + "precommit_args": [ + "--gerrit-issue=${patch_issue}", + "--gerrit-patchset=${patch_set}", + "--buildbucket-id=${buildbucket_build_id}" + ], + "resultdb": { + "enable": true, + "result_format": "single" + }, + "swarming": { + "can_use_on_swarming_builders": true, + "dimension_sets": [ + { + "cpu": "x86", + "gce": "1", + "kvm": "1", + "os": "Ubuntu-18.04", + "pool": "chrome.tests.finch" + } + ], + "named_caches": [ + { + "name": "cros_vm", + "path": "magic_cros_vm_cache" + } + ], + "optional_dimensions": { + "60": [ + { + "caches": "cros_vm" + } + ] + }, + "service_account": "chrome-tester@chops-service-accounts.iam.gserviceaccount.com" + }, + "test_id_prefix": "ninja://chrome/test/variations:variations_desktop_smoke_tests/" + } ] }, "chromeos-brya-chrome-skylab-fyi": {
diff --git a/testing/buildbot/test_suites.pyl b/testing/buildbot/test_suites.pyl index b7a67d8..9cbbb55 100644 --- a/testing/buildbot/test_suites.pyl +++ b/testing/buildbot/test_suites.pyl
@@ -460,16 +460,15 @@ 'chrome_finch_smoke_tests': { 'variations_desktop_smoke_tests': { 'isolate_name': 'variations_desktop_smoke_tests', - 'mixins': [ - 'skia_gold_test', + 'lacros_args': [ + '--target-platform=lacros', ], - 'resultdb': { - 'enable': True, - 'result_format': 'single' - }, - }, - 'variations_smoke_tests': { - 'isolate_name': 'variations_smoke_tests', + 'android_args': [ + '--target-platform=android', + ], + 'chromeos_args': [ + '--target-platform=cros', + ], 'mixins': [ 'skia_gold_test', ],
diff --git a/testing/buildbot/variants.pyl b/testing/buildbot/variants.pyl index c78040c..9f0b59a6 100644 --- a/testing/buildbot/variants.pyl +++ b/testing/buildbot/variants.pyl
@@ -22,16 +22,16 @@ }, 'LACROS_VERSION_SKEW_CANARY': { 'args': [ - '--ash-chrome-path-override=../../lacros_version_skew_tests_v115.0.5766.0/test_ash_chrome', + '--ash-chrome-path-override=../../lacros_version_skew_tests_v115.0.5767.0/test_ash_chrome', ], - 'description': 'Run with ash-chrome version 115.0.5766.0', + 'description': 'Run with ash-chrome version 115.0.5767.0', 'identifier': 'Lacros version skew testing ash canary', 'swarming': { 'cipd_packages': [ { 'cipd_package': 'chromium/testing/linux-ash-chromium/x86_64/ash.zip', - 'location': 'lacros_version_skew_tests_v115.0.5766.0', - 'revision': 'version:115.0.5766.0', + 'location': 'lacros_version_skew_tests_v115.0.5767.0', + 'revision': 'version:115.0.5767.0', }, ], },
diff --git a/testing/buildbot/waterfalls.pyl b/testing/buildbot/waterfalls.pyl index 0602f1c..484369e1 100644 --- a/testing/buildbot/waterfalls.pyl +++ b/testing/buildbot/waterfalls.pyl
@@ -6531,6 +6531,7 @@ 'test_suites': { 'isolated_scripts': 'android_finch_smoke_tests', }, + 'os_type': 'android', }, 'chromeos-arm-generic-cfi-thin-lto-chrome-reclient': { 'additional_compile_targets': [ @@ -6561,6 +6562,7 @@ 'test_suites': { 'isolated_scripts': 'chrome_finch_smoke_tests', }, + 'os_type': 'linux', }, 'mac-arm64-finch-smoke-chrome': { 'mixins': [ @@ -6570,6 +6572,7 @@ 'test_suites': { 'isolated_scripts': 'chrome_finch_smoke_tests', }, + 'os_type': 'mac', }, 'mac-chrome-reclient': { 'additional_compile_targets': [ @@ -6619,6 +6622,7 @@ 'test_suites': { 'isolated_scripts': 'chrome_finch_smoke_tests', }, + 'os_type': 'win', }, }, }, @@ -6649,7 +6653,9 @@ ], 'test_suites': { 'gtest_tests': 'chromeos_browser_finch_tests', + 'isolated_scripts': 'chrome_finch_smoke_tests', }, + 'os_type': 'chromeos', }, 'chromeos-brya-chrome-skylab-fyi': { 'additional_compile_targets': [
diff --git a/testing/variations/fieldtrial_testing_config.json b/testing/variations/fieldtrial_testing_config.json index 65fd0bf..e7c4138d 100644 --- a/testing/variations/fieldtrial_testing_config.json +++ b/testing/variations/fieldtrial_testing_config.json
@@ -951,6 +951,21 @@ ] } ], + "AutoDisableAccessibilityV2": [ + { + "platforms": [ + "android" + ], + "experiments": [ + { + "name": "Enabled", + "enable_features": [ + "AutoDisableAccessibilityV2" + ] + } + ] + } + ], "AutocorrectByDefault": [ { "platforms": [ @@ -2514,6 +2529,21 @@ ] } ], + "CertVerifierBuiltin": [ + { + "platforms": [ + "android" + ], + "experiments": [ + { + "name": "Enabled", + "enable_features": [ + "ChromeRootStoreUsed" + ] + } + ] + } + ], "ChangeExtensionEventPageSuspendDelay": [ { "platforms": [ @@ -6621,6 +6651,30 @@ ] } ], + "IOSBringYourOwnTabs": [ + { + "platforms": [ + "ios" + ], + "experiments": [ + { + "name": "Enabled", + "enable_features": [ + "BringYourOwnTabsIOS" + ] + }, + { + "name": "EnabledWithBottomMessage", + "params": { + "bottom-message": "true" + }, + "enable_features": [ + "BringYourOwnTabsIOS" + ] + } + ] + } + ], "IOSBrowserEditMenuMetrics": [ { "platforms": [ @@ -9403,6 +9457,25 @@ ] } ], + "OutOfProcessPrintDriversPrintPreview": [ + { + "platforms": [ + "windows" + ], + "experiments": [ + { + "name": "Enabled_20221024", + "params": { + "JobPrint": "true", + "Sandbox": "false" + }, + "enable_features": [ + "EnableOopPrintDrivers" + ] + } + ] + } + ], "OutOfProcessSystemDnsResolution": [ { "platforms": [
diff --git a/third_party/blink/common/scheduler/web_scheduler_tracked_feature.cc b/third_party/blink/common/scheduler/web_scheduler_tracked_feature.cc index db179658..ea9b10a5 100644 --- a/third_party/blink/common/scheduler/web_scheduler_tracked_feature.cc +++ b/third_party/blink/common/scheduler/web_scheduler_tracked_feature.cc
@@ -190,7 +190,7 @@ } WebSchedulerTrackedFeatures StickyFeatures() { - constexpr WebSchedulerTrackedFeatures features = WebSchedulerTrackedFeatures( + constexpr WebSchedulerTrackedFeatures features = { WebSchedulerTrackedFeature::kMainResourceHasCacheControlNoStore, WebSchedulerTrackedFeature::kMainResourceHasCacheControlNoCache, WebSchedulerTrackedFeature::kSubresourceHasCacheControlNoStore, @@ -214,7 +214,7 @@ WebSchedulerTrackedFeature::kInjectedStyleSheet, WebSchedulerTrackedFeature::kKeepaliveRequest, WebSchedulerTrackedFeature::kDummy, - WebSchedulerTrackedFeature::kAuthorizationHeader); + WebSchedulerTrackedFeature::kAuthorizationHeader}; return features; }
diff --git a/third_party/blink/public/mojom/use_counter/metrics/web_feature.mojom b/third_party/blink/public/mojom/use_counter/metrics/web_feature.mojom index 679d7c9e..19b8f45 100644 --- a/third_party/blink/public/mojom/use_counter/metrics/web_feature.mojom +++ b/third_party/blink/public/mojom/use_counter/metrics/web_feature.mojom
@@ -3901,6 +3901,14 @@ kLinkRelPreloadAsFont = 4561, kCrossWindowAccessToBrowserGeneratedDocument = 4562, kSpeculationRulesNoVarySearchHint = 4563, + kFileSystemAccessMoveRename = 4564, + kFileSystemAccessMoveReparent = 4565, + kFileSystemAccessMoveReparentAndRename = 4566, + kV8FileSystemDirectoryHandle_RemoveEntry_Method = 4567, + kV8FileSystemFileHandle_CreateWritable_Method = 4568, + kV8FileSystemFileHandle_GetFile_Method = 4569, + kV8FileSystemHandle_GetUniqueId_Method = 4570, + kV8FileSystemHandle_Remove_Method = 4571, // Add new features immediately above this line. Don't change assigned // numbers of any item, and don't reuse removed slots.
diff --git a/third_party/blink/public/web/web_local_frame.h b/third_party/blink/public/web/web_local_frame.h index 157a7a9..7b0ac6cb 100644 --- a/third_party/blink/public/web/web_local_frame.h +++ b/third_party/blink/public/web/web_local_frame.h
@@ -767,10 +767,8 @@ // not in printing mode. virtual float GetPrintPageShrink(uint32_t page) = 0; - // Prints one page, and returns the calculated page shrinking factor - // (usually between 1/1.33 and 1/2). Returns 0 if the page number is - // invalid or not in printing mode. - virtual float PrintPage(uint32_t page_to_print, cc::PaintCanvas*) = 0; + // Prints one page. + virtual void PrintPage(uint32_t page_to_print, cc::PaintCanvas*) = 0; // Reformats the WebFrame for screen display. virtual void PrintEnd() = 0;
diff --git a/third_party/blink/renderer/bindings/generated_in_modules.gni b/third_party/blink/renderer/bindings/generated_in_modules.gni index d520b17..5e0c67b 100644 --- a/third_party/blink/renderer/bindings/generated_in_modules.gni +++ b/third_party/blink/renderer/bindings/generated_in_modules.gni
@@ -1889,6 +1889,8 @@ "$root_gen_dir/third_party/blink/renderer/bindings/modules/v8/v8_encoded_audio_chunk.h", "$root_gen_dir/third_party/blink/renderer/bindings/modules/v8/v8_encoded_video_chunk.cc", "$root_gen_dir/third_party/blink/renderer/bindings/modules/v8/v8_encoded_video_chunk.h", + "$root_gen_dir/third_party/blink/renderer/bindings/modules/v8/v8_environment_integrity.cc", + "$root_gen_dir/third_party/blink/renderer/bindings/modules/v8/v8_environment_integrity.h", "$root_gen_dir/third_party/blink/renderer/bindings/modules/v8/v8_entry.cc", "$root_gen_dir/third_party/blink/renderer/bindings/modules/v8/v8_entry.h", "$root_gen_dir/third_party/blink/renderer/bindings/modules/v8/v8_entry_sync.cc",
diff --git a/third_party/blink/renderer/bindings/idl_in_modules.gni b/third_party/blink/renderer/bindings/idl_in_modules.gni index 131e51c6..9a5b48a8 100644 --- a/third_party/blink/renderer/bindings/idl_in_modules.gni +++ b/third_party/blink/renderer/bindings/idl_in_modules.gni
@@ -241,6 +241,7 @@ "//third_party/blink/renderer/modules/encryptedmedia/media_keys_get_status_for_policy.idl", "//third_party/blink/renderer/modules/encryptedmedia/media_keys_policy.idl", "//third_party/blink/renderer/modules/encryptedmedia/navigator_request_media_key_system_access.idl", + "//third_party/blink/renderer/modules/environment_integrity/environment_integrity.idl", "//third_party/blink/renderer/modules/environment_integrity/navigator_environment_integrity.idl", "//third_party/blink/renderer/modules/eventsource/event_source.idl", "//third_party/blink/renderer/modules/eventsource/event_source_init.idl",
diff --git a/third_party/blink/renderer/core/css/css.dict b/third_party/blink/renderer/core/css/css.dict index db200ac..d6b1dba4 100644 --- a/third_party/blink/renderer/core/css/css.dict +++ b/third_party/blink/renderer/core/css/css.dict
@@ -935,6 +935,8 @@ "spelling-error" "grammar-error" "color-contrast" +"accentcolor" +"accentcolortext" # at-rules "@charset"
diff --git a/third_party/blink/renderer/core/css/css_value_keywords.json5 b/third_party/blink/renderer/core/css/css_value_keywords.json5 index ed0bda78..3638a8be 100644 --- a/third_party/blink/renderer/core/css/css_value_keywords.json5 +++ b/third_party/blink/renderer/core/css/css_value_keywords.json5
@@ -213,6 +213,8 @@ "transparent", "-webkit-link", "-webkit-activelink", + "accentcolor", + "accentcolortext", "activeborder", "activecaption", "activetext",
diff --git a/third_party/blink/renderer/core/css/cssom/css_hsl.cc b/third_party/blink/renderer/core/css/cssom/css_hsl.cc index 0d61dc4..bd468b0 100644 --- a/third_party/blink/renderer/core/css/cssom/css_hsl.cc +++ b/third_party/blink/renderer/core/css/cssom/css_hsl.cc
@@ -19,7 +19,7 @@ s_ = CSSUnitValue::Create(s * 100, CSSPrimitiveValue::UnitType::kPercentage); l_ = CSSUnitValue::Create(l * 100, CSSPrimitiveValue::UnitType::kPercentage); - double a = double(input_color.AlphaAsInteger()) / 255; + double a = input_color.Alpha(); alpha_ = CSSUnitValue::Create(a * 100, CSSPrimitiveValue::UnitType::kPercentage); }
diff --git a/third_party/blink/renderer/core/css/cssom/css_hwb.cc b/third_party/blink/renderer/core/css/cssom/css_hwb.cc index c6a2124a..39f3814a 100644 --- a/third_party/blink/renderer/core/css/cssom/css_hwb.cc +++ b/third_party/blink/renderer/core/css/cssom/css_hwb.cc
@@ -19,7 +19,7 @@ w_ = CSSUnitValue::Create(w * 100, CSSPrimitiveValue::UnitType::kPercentage); b_ = CSSUnitValue::Create(b * 100, CSSPrimitiveValue::UnitType::kPercentage); - double a = double(input_color.AlphaAsInteger()) / 255; + double a = input_color.Alpha(); alpha_ = CSSUnitValue::Create(a * 100, CSSPrimitiveValue::UnitType::kPercentage); }
diff --git a/third_party/blink/renderer/core/css/properties/css_parsing_utils.cc b/third_party/blink/renderer/core/css/properties/css_parsing_utils.cc index d798cb6..8069929 100644 --- a/third_party/blink/renderer/core/css/properties/css_parsing_utils.cc +++ b/third_party/blink/renderer/core/css/properties/css_parsing_utils.cc
@@ -2438,6 +2438,10 @@ } CSSValueID id = range.Peek().Id(); + if ((id == CSSValueID::kAccentcolor || id == CSSValueID::kAccentcolortext) && + !RuntimeEnabledFeatures::CSSSystemAccentColorEnabled()) { + return nullptr; + } if (StyleColor::IsColorKeyword(id)) { if (!isValueAllowedInMode(id, context.Mode())) { return nullptr;
diff --git a/third_party/blink/renderer/core/css/style_color.cc b/third_party/blink/renderer/core/css/style_color.cc index 91d6476..9cebdf6 100644 --- a/third_party/blink/renderer/core/css/style_color.cc +++ b/third_party/blink/renderer/core/css/style_color.cc
@@ -319,6 +319,8 @@ bool StyleColor::IsSystemColor(CSSValueID id) { switch (id) { + case CSSValueID::kAccentcolor: + case CSSValueID::kAccentcolortext: case CSSValueID::kActivetext: case CSSValueID::kButtonborder: case CSSValueID::kButtonface:
diff --git a/third_party/blink/renderer/core/dom/container_node.cc b/third_party/blink/renderer/core/dom/container_node.cc index a83dff1..e09221c4 100644 --- a/third_party/blink/renderer/core/dom/container_node.cc +++ b/third_party/blink/renderer/core/dom/container_node.cc
@@ -1639,14 +1639,6 @@ Element* ContainerNode::GetAutofocusDelegate() const { Element* element = ElementTraversal::Next(*this, this); while (element) { - if (auto* html_element = DynamicTo<HTMLElement>(element)) { - if (DynamicTo<HTMLDialogElement>(html_element) || - html_element->HasPopoverAttribute()) { - element = ElementTraversal::NextSkippingChildren(*element, this); - continue; - } - } - if (!element->IsAutofocusable()) { element = ElementTraversal::Next(*element, this); continue;
diff --git a/third_party/blink/renderer/core/dom/xml_document.cc b/third_party/blink/renderer/core/dom/xml_document.cc index 8d5e560..7f28d676 100644 --- a/third_party/blink/renderer/core/dom/xml_document.cc +++ b/third_party/blink/renderer/core/dom/xml_document.cc
@@ -30,7 +30,7 @@ XMLDocument::XMLDocument(const DocumentInit& initializer, DocumentClassFlags extended_document_classes) : Document(initializer, - base::Union(DocumentClassFlags(DocumentClass::kXML), + base::Union(DocumentClassFlags({DocumentClass::kXML}), extended_document_classes)) {} } // namespace blink
diff --git a/third_party/blink/renderer/core/dom/xml_document.h b/third_party/blink/renderer/core/dom/xml_document.h index 35902eb..a9b8548 100644 --- a/third_party/blink/renderer/core/dom/xml_document.h +++ b/third_party/blink/renderer/core/dom/xml_document.h
@@ -38,12 +38,12 @@ public: static XMLDocument* CreateXHTML(const DocumentInit& initializer) { return MakeGarbageCollected<XMLDocument>( - initializer, DocumentClassFlags(DocumentClass::kXHTML)); + initializer, DocumentClassFlags({DocumentClass::kXHTML})); } static XMLDocument* CreateSVG(const DocumentInit& initializer) { return MakeGarbageCollected<XMLDocument>( - initializer, DocumentClassFlags(DocumentClass::kSVG)); + initializer, DocumentClassFlags({DocumentClass::kSVG})); } explicit XMLDocument(
diff --git a/third_party/blink/renderer/core/editing/commands/editor_command.cc b/third_party/blink/renderer/core/editing/commands/editor_command.cc index e0987b0..8ec99072 100644 --- a/third_party/blink/renderer/core/editing/commands/editor_command.cc +++ b/third_party/blink/renderer/core/editing/commands/editor_command.cc
@@ -70,11 +70,13 @@ #include "third_party/blink/renderer/core/html_names.h" #include "third_party/blink/renderer/core/input/event_handler.h" #include "third_party/blink/renderer/core/input/keyboard_shortcut_recorder.h" +#include "third_party/blink/renderer/core/layout/layout_text.h" #include "third_party/blink/renderer/core/page/chrome_client.h" #include "third_party/blink/renderer/core/page/page.h" #include "third_party/blink/renderer/core/scroll/scrollbar.h" #include "third_party/blink/renderer/platform/bindings/exception_state.h" #include "third_party/blink/renderer/platform/heap/garbage_collected.h" +#include "third_party/blink/renderer/platform/runtime_enabled_features.h" #include "third_party/blink/renderer/platform/wtf/allocator/allocator.h" #include "third_party/blink/renderer/platform/wtf/text/atomic_string.h" @@ -1213,11 +1215,21 @@ if (!root->hasChildren()) return false; - // When the editable contains a BR only, it appears as an empty line, in - // which case allowing select-all confuses users. - if (root->firstChild() == root->lastChild() && - IsA<HTMLBRElement>(root->firstChild())) - return false; + // When the editable appears as an empty line without any visible content, + // allowing select-all confuses users. + if (root->firstChild() == root->lastChild()) { + if (IsA<HTMLBRElement>(root->firstChild())) { + return false; + } + if (RuntimeEnabledFeatures::DisableSelectAllForEmptyTextEnabled()) { + if (Text* text = DynamicTo<Text>(root->firstChild())) { + LayoutText* layout_text = text->GetLayoutObject(); + if (!layout_text || !layout_text->HasNonCollapsedText()) { + return false; + } + } + } + } // TODO(amaralp): Return false if already fully selected. }
diff --git a/third_party/blink/renderer/core/editing/editing_style_utilities.cc b/third_party/blink/renderer/core/editing/editing_style_utilities.cc index 751bd406..a9ed3e39 100644 --- a/third_party/blink/renderer/core/editing/editing_style_utilities.cc +++ b/third_party/blink/renderer/core/editing/editing_style_utilities.cc
@@ -207,7 +207,7 @@ if (!css_value) return true; if (auto* color_value = DynamicTo<cssvalue::CSSColor>(css_value)) - return !color_value->Value().AlphaAsInteger(); + return color_value->Value().IsFullyTransparent(); if (auto* identifier_value = DynamicTo<CSSIdentifierValue>(css_value)) return identifier_value->GetValueID() == CSSValueID::kTransparent; return false;
diff --git a/third_party/blink/renderer/core/editing/substring_util.mm b/third_party/blink/renderer/core/editing/substring_util.mm index bb5f38f..f0e5e71 100644 --- a/third_party/blink/renderer/core/editing/substring_util.mm +++ b/third_party/blink/renderer/core/editing/substring_util.mm
@@ -147,14 +147,15 @@ } attrs[NSFontAttributeName] = font; - if (style->VisitedDependentColor(GetCSSPropertyColor()).AlphaAsInteger()) { + if (!style->VisitedDependentColor(GetCSSPropertyColor()) + .IsFullyTransparent()) { attrs[NSForegroundColorAttributeName] = NsColor(style->VisitedDependentColor(GetCSSPropertyColor())); } else { [attrs removeObjectForKey:NSForegroundColorAttributeName]; } - if (style->VisitedDependentColor(GetCSSPropertyBackgroundColor()) - .AlphaAsInteger()) { + if (!style->VisitedDependentColor(GetCSSPropertyBackgroundColor()) + .IsFullyTransparent()) { attrs[NSBackgroundColorAttributeName] = NsColor( style->VisitedDependentColor(GetCSSPropertyBackgroundColor())); } else {
diff --git a/third_party/blink/renderer/core/frame/root_frame_viewport.cc b/third_party/blink/renderer/core/frame/root_frame_viewport.cc index 849e563..f8ed1249 100644 --- a/third_party/blink/renderer/core/frame/root_frame_viewport.cc +++ b/third_party/blink/renderer/core/frame/root_frame_viewport.cc
@@ -52,7 +52,7 @@ static base::RepeatingCallback<void(ScrollableArea::ScrollCompletionMode)> MakeViewportScrollCompletion(ScrollableArea::ScrollCallback callback) { return callback - ? BarrierCallback<ScrollableArea::ScrollCompletionMode>( + ? base::BarrierCallback<ScrollableArea::ScrollCompletionMode>( 2, WTF::BindOnce( [](ScrollableArea::ScrollCallback on_finish, const std::vector<
diff --git a/third_party/blink/renderer/core/frame/web_frame_test.cc b/third_party/blink/renderer/core/frame/web_frame_test.cc index c56e27f2..574f461 100644 --- a/third_party/blink/renderer/core/frame/web_frame_test.cc +++ b/third_party/blink/renderer/core/frame/web_frame_test.cc
@@ -13394,7 +13394,7 @@ EXPECT_TRUE(TestSelectAll("<input value='nonempty'>")); EXPECT_FALSE(TestSelectAll("<div contenteditable></div>")); EXPECT_TRUE(TestSelectAll("<div contenteditable>nonempty</div>")); - EXPECT_TRUE(TestSelectAll("<div contenteditable>\n</div>")); + EXPECT_FALSE(TestSelectAll("<div contenteditable>\n</div>")); } TEST_F(WebFrameTest, ContextMenuDataSelectedText) {
diff --git a/third_party/blink/renderer/core/frame/web_local_frame_impl.cc b/third_party/blink/renderer/core/frame/web_local_frame_impl.cc index eec6aa3..66aad25 100644 --- a/third_party/blink/renderer/core/frame/web_local_frame_impl.cc +++ b/third_party/blink/renderer/core/frame/web_local_frame_impl.cc
@@ -349,16 +349,18 @@ return printed_page_width_ / page_rect.width(); } - float SpoolSinglePage(cc::PaintCanvas* canvas, int page_number) { + void SpoolSinglePage(cc::PaintCanvas* canvas, int page_number) { DispatchEventsForPrintingOnAllFrames(); if (!GetFrame()->GetDocument() || - !GetFrame()->GetDocument()->GetLayoutView()) - return 0; + !GetFrame()->GetDocument()->GetLayoutView()) { + return; + } GetFrame()->View()->UpdateLifecyclePhasesForPrinting(); if (!GetFrame()->GetDocument() || - !GetFrame()->GetDocument()->GetLayoutView()) - return 0; + !GetFrame()->GetDocument()->GetLayoutView()) { + return; + } // The page rect gets scaled and translated, so specify the entire // print content area here as the recording rect. @@ -367,9 +369,8 @@ context.SetPrintingMetafile(canvas->GetPrintingMetafile()); context.SetPrinting(true); context.BeginRecording(); - float scale = SpoolPage(context, page_number); + SpoolPage(context, page_number); canvas->drawPicture(context.EndRecording()); - return scale; } void SpoolPagesWithBoundariesForTesting( @@ -462,10 +463,8 @@ } protected: - virtual float SpoolPage(GraphicsContext& context, int page_number) { + virtual void SpoolPage(GraphicsContext& context, int page_number) { gfx::Rect page_rect = page_rects_[page_number]; - float scale = printed_page_width_ / page_rect.width(); - AffineTransform transform; transform.Translate(static_cast<float>(-page_rect.x()), static_cast<float>(-page_rect.y())); @@ -495,8 +494,6 @@ context.DrawRecord(builder->EndRecording(property_tree_state.Unalias())); context.Restore(); - - return scale; } private: @@ -568,15 +565,10 @@ } protected: - // Spools the printed page, a subrect of frame(). Skip the scale step. - // NativeTheme doesn't play well with scaling. Scaling is done browser side - // instead. Returns the scale to be applied. - float SpoolPage(GraphicsContext& context, int page_number) override { + void SpoolPage(GraphicsContext& context, int page_number) override { auto* builder = MakeGarbageCollected<PaintRecordBuilder>(context); plugin_->PrintPage(page_number, builder->Context()); context.DrawRecord(builder->EndRecording()); - - return 1.0; } private: @@ -1902,12 +1894,12 @@ return print_context_->GetPageShrink(page); } -float WebLocalFrameImpl::PrintPage(uint32_t page, cc::PaintCanvas* canvas) { +void WebLocalFrameImpl::PrintPage(uint32_t page, cc::PaintCanvas* canvas) { DCHECK(print_context_); DCHECK(GetFrame()); DCHECK(GetFrame()->GetDocument()); - return print_context_->SpoolSinglePage(canvas, page); + print_context_->SpoolSinglePage(canvas, page); } void WebLocalFrameImpl::PrintEnd() {
diff --git a/third_party/blink/renderer/core/frame/web_local_frame_impl.h b/third_party/blink/renderer/core/frame/web_local_frame_impl.h index aa8c03c..8c16b15b 100644 --- a/third_party/blink/renderer/core/frame/web_local_frame_impl.h +++ b/third_party/blink/renderer/core/frame/web_local_frame_impl.h
@@ -308,7 +308,7 @@ const WebNode& constrain_to_node) override; bool WillPrintSoon() override; float GetPrintPageShrink(uint32_t page) override; - float PrintPage(uint32_t page_to_print, cc::PaintCanvas*) override; + void PrintPage(uint32_t page_to_print, cc::PaintCanvas*) override; void PrintEnd() override; void DispatchAfterPrintEvent() override; bool GetPrintPresetOptionsForPlugin(const WebNode&,
diff --git a/third_party/blink/renderer/core/html/build.gni b/third_party/blink/renderer/core/html/build.gni index 8060255..bf312108 100644 --- a/third_party/blink/renderer/core/html/build.gni +++ b/third_party/blink/renderer/core/html/build.gni
@@ -697,6 +697,7 @@ "html_image_element_test.cc", "html_link_element_sizes_attribute_test.cc", "html_link_element_test.cc", + "html_dialog_element_test.cc", "html_meta_element_test.cc", "html_object_element_test.cc", "html_plugin_element_test.cc",
diff --git a/third_party/blink/renderer/core/html/html_dialog_element.cc b/third_party/blink/renderer/core/html/html_dialog_element.cc index b3193acd..ca1bcd9 100644 --- a/third_party/blink/renderer/core/html/html_dialog_element.cc +++ b/third_party/blink/renderer/core/html/html_dialog_element.cc
@@ -327,16 +327,6 @@ } } -void HTMLDialogElement::DefaultEventHandler(Event& event) { - if (!RuntimeEnabledFeatures::CloseWatcherEnabled() && - event.type() == event_type_names::kCancel) { - close(); - event.SetDefaultHandled(); - return; - } - HTMLElement::DefaultEventHandler(event); -} - void HTMLDialogElement::CloseWatcherFiredCancel(Event* close_watcher_event) { if (!RuntimeEnabledFeatures::CloseWatcherEnabled()) return;
diff --git a/third_party/blink/renderer/core/html/html_dialog_element.h b/third_party/blink/renderer/core/html/html_dialog_element.h index ce23caf68..29594b8 100644 --- a/third_party/blink/renderer/core/html/html_dialog_element.h +++ b/third_party/blink/renderer/core/html/html_dialog_element.h
@@ -74,8 +74,6 @@ static void SetFocusForDialogLegacy(HTMLDialogElement* dialog); private: - void DefaultEventHandler(Event&) override; - void SetIsModal(bool is_modal); void ScheduleCloseEvent();
diff --git a/third_party/blink/renderer/core/html/html_dialog_element_test.cc b/third_party/blink/renderer/core/html/html_dialog_element_test.cc new file mode 100644 index 0000000..4fb0917 --- /dev/null +++ b/third_party/blink/renderer/core/html/html_dialog_element_test.cc
@@ -0,0 +1,27 @@ +// Copyright 2023 The Chromium Authors +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "third_party/blink/renderer/core/html/html_dialog_element.h" + +#include "testing/gmock/include/gmock/gmock.h" +#include "testing/gtest/include/gtest/gtest.h" +#include "third_party/blink/renderer/core/dom/document.h" +#include "third_party/blink/renderer/core/dom/events/event.h" +#include "third_party/blink/renderer/core/html/html_body_element.h" +#include "third_party/blink/renderer/core/testing/page_test_base.h" + +namespace blink { + +class HTMLDialogElementTest : public PageTestBase {}; + +// The dialog event should not be closed in response to cancel events. +TEST_F(HTMLDialogElementTest, CancelEventDontClose) { + auto* dialog = MakeGarbageCollected<HTMLDialogElement>(GetDocument()); + GetDocument().FirstBodyElement()->AppendChild(dialog); + dialog->showModal(ASSERT_NO_EXCEPTION); + dialog->DispatchScopedEvent(*Event::CreateBubble(event_type_names::kCancel)); + EXPECT_TRUE(dialog->FastHasAttribute(html_names::kOpenAttr)); +} + +} // namespace blink
diff --git a/third_party/blink/renderer/core/html/html_document.cc b/third_party/blink/renderer/core/html/html_document.cc index 5352daf6e..37061e49 100644 --- a/third_party/blink/renderer/core/html/html_document.cc +++ b/third_party/blink/renderer/core/html/html_document.cc
@@ -64,7 +64,7 @@ HTMLDocument::HTMLDocument(const DocumentInit& initializer, DocumentClassFlags extended_document_classes) : Document(initializer, - base::Union(DocumentClassFlags(DocumentClass::kHTML), + base::Union(DocumentClassFlags({DocumentClass::kHTML}), extended_document_classes)) { ClearXMLVersion(); if (IsSrcdocDocument()) {
diff --git a/third_party/blink/renderer/core/html/image_document.cc b/third_party/blink/renderer/core/html/image_document.cc index 76cb978..1475324 100644 --- a/third_party/blink/renderer/core/html/image_document.cc +++ b/third_party/blink/renderer/core/html/image_document.cc
@@ -197,7 +197,7 @@ // -------- ImageDocument::ImageDocument(const DocumentInit& initializer) - : HTMLDocument(initializer, DocumentClassFlags(DocumentClass::kImage)), + : HTMLDocument(initializer, {DocumentClass::kImage}), div_element_(nullptr), image_element_(nullptr), image_size_is_known_(false),
diff --git a/third_party/blink/renderer/core/html/media/media_document.cc b/third_party/blink/renderer/core/html/media/media_document.cc index 76979bc..cd5c64b 100644 --- a/third_party/blink/renderer/core/html/media/media_document.cc +++ b/third_party/blink/renderer/core/html/media/media_document.cc
@@ -119,7 +119,7 @@ } MediaDocument::MediaDocument(const DocumentInit& initializer) - : HTMLDocument(initializer, DocumentClassFlags(DocumentClass::kMedia)) { + : HTMLDocument(initializer, {DocumentClass::kMedia}) { SetCompatibilityMode(kNoQuirksMode); LockCompatibilityMode();
diff --git a/third_party/blink/renderer/core/html/plugin_document.cc b/third_party/blink/renderer/core/html/plugin_document.cc index bf79ed1..fe3a1c4 100644 --- a/third_party/blink/renderer/core/html/plugin_document.cc +++ b/third_party/blink/renderer/core/html/plugin_document.cc
@@ -181,7 +181,7 @@ } PluginDocument::PluginDocument(const DocumentInit& initializer) - : HTMLDocument(initializer, DocumentClass::kPlugin), + : HTMLDocument(initializer, {DocumentClass::kPlugin}), background_color_( GetFrame()->GetPluginData()->PluginBackgroundColorForMimeType( initializer.GetMimeType())) {
diff --git a/third_party/blink/renderer/core/html/text_document.cc b/third_party/blink/renderer/core/html/text_document.cc index eaeae962..8bed09c 100644 --- a/third_party/blink/renderer/core/html/text_document.cc +++ b/third_party/blink/renderer/core/html/text_document.cc
@@ -31,7 +31,7 @@ namespace blink { TextDocument::TextDocument(const DocumentInit& initializer) - : HTMLDocument(initializer, DocumentClassFlags(DocumentClass::kText)) { + : HTMLDocument(initializer, {DocumentClass::kText}) { SetCompatibilityMode(kNoQuirksMode); LockCompatibilityMode(); }
diff --git a/third_party/blink/renderer/core/input/keyboard_event_manager.cc b/third_party/blink/renderer/core/input/keyboard_event_manager.cc index ad9e29c..c130db6 100644 --- a/third_party/blink/renderer/core/input/keyboard_event_manager.cc +++ b/third_party/blink/renderer/core/input/keyboard_event_manager.cc
@@ -603,6 +603,9 @@ frame_->GetDocument(), WebFeature::kDialogCloseWatcherCancelSkippedAndDefaultPrevented); } + if (!cancel_event->defaultPrevented()) { + dialog->close(); + } } auto* target_node = event->GetEventPath()[0].Target()->ToNode();
diff --git a/third_party/blink/renderer/core/inspector/inspector_contrast.cc b/third_party/blink/renderer/core/inspector/inspector_contrast.cc index 498458f..85eaa0b 100644 --- a/third_party/blink/renderer/core/inspector/inspector_contrast.cc +++ b/third_party/blink/renderer/core/inspector/inspector_contrast.cc
@@ -58,7 +58,7 @@ colors.clear(); for (auto stop_color : stop_colors) { found_non_transparent_color = - found_non_transparent_color || (stop_color.AlphaAsInteger() != 0); + found_non_transparent_color || !stop_color.IsFullyTransparent(); colors.push_back(existing_color.Blend(stop_color)); } } @@ -348,7 +348,7 @@ } bool found_non_transparent_color = false; - if (background_color.AlphaAsInteger() != 0) { + if (!background_color.IsFullyTransparent()) { found_non_transparent_color = true; if (!background_color.IsOpaque()) { if (colors.empty()) {
diff --git a/third_party/blink/renderer/core/inspector/inspector_highlight.cc b/third_party/blink/renderer/core/inspector/inspector_highlight.cc index 9e06823..745b647 100644 --- a/third_party/blink/renderer/core/inspector/inspector_highlight.cc +++ b/third_party/blink/renderer/core/inspector/inspector_highlight.cc
@@ -419,7 +419,7 @@ const absl::optional<LineStyle>& line_style, std::unique_ptr<protocol::DictionaryValue>& parent_config, String line_name) { - if (!line_style || line_style->IsTransparent()) { + if (!line_style || line_style->IsFullyTransparent()) { return; } @@ -435,7 +435,7 @@ const absl::optional<BoxStyle>& box_style, std::unique_ptr<protocol::DictionaryValue>& parent_config, String box_name) { - if (!box_style || box_style->IsTransparent()) { + if (!box_style || box_style->IsFullyTransparent()) { return; } @@ -2321,7 +2321,7 @@ bool include_descendants = container_query_container_highlight_config.descendant_border && !container_query_container_highlight_config.descendant_border - ->IsTransparent(); + ->IsFullyTransparent(); if (element && include_descendants) { std::unique_ptr<protocol::ListValue> descendants_info = protocol::ListValue::create();
diff --git a/third_party/blink/renderer/core/inspector/inspector_highlight.h b/third_party/blink/renderer/core/inspector/inspector_highlight.h index d7547a4..f24fb54 100644 --- a/third_party/blink/renderer/core/inspector/inspector_highlight.h +++ b/third_party/blink/renderer/core/inspector/inspector_highlight.h
@@ -27,7 +27,7 @@ public: LineStyle(); - bool IsTransparent() const { return color == Color::kTransparent; } + bool IsFullyTransparent() const { return color == Color::kTransparent; } Color color; String pattern; @@ -39,7 +39,7 @@ public: BoxStyle(); - bool IsTransparent() const { + bool IsFullyTransparent() const { return fill_color == Color::kTransparent && hatch_color == Color::kTransparent; }
diff --git a/third_party/blink/renderer/core/layout/layout_box.cc b/third_party/blink/renderer/core/layout/layout_box.cc index d0e168b..66f847db 100644 --- a/third_party/blink/renderer/core/layout/layout_box.cc +++ b/third_party/blink/renderer/core/layout/layout_box.cc
@@ -1568,7 +1568,7 @@ // Ignore invisible background layers for kBackgroundPaintedExtent. DCHECK_EQ(rect_type, kBackgroundPaintedExtent); if (!cur->GetImage() && - (cur->Next() || background_color.AlphaAsInteger() == 0)) { + (cur->Next() || background_color.IsFullyTransparent())) { continue; } // A content-box clipped fill layer can be scrolled into the padding box @@ -6157,22 +6157,22 @@ } if (StyleRef().BorderTopWidth() && - (ResolveColor(GetCSSPropertyBorderTopColor()).HasTransparency() || + (!ResolveColor(GetCSSPropertyBorderTopColor()).IsOpaque() || StyleRef().BorderTopStyle() != EBorderStyle::kSolid)) { return false; } if (StyleRef().BorderRightWidth() && - (ResolveColor(GetCSSPropertyBorderRightColor()).HasTransparency() || + (!ResolveColor(GetCSSPropertyBorderRightColor()).IsOpaque() || StyleRef().BorderRightStyle() != EBorderStyle::kSolid)) { return false; } if (StyleRef().BorderBottomWidth() && - (ResolveColor(GetCSSPropertyBorderBottomColor()).HasTransparency() || + (!ResolveColor(GetCSSPropertyBorderBottomColor()).IsOpaque() || StyleRef().BorderBottomStyle() != EBorderStyle::kSolid)) { return false; } if (StyleRef().BorderLeftWidth() && - (ResolveColor(GetCSSPropertyBorderLeftColor()).HasTransparency() || + (!ResolveColor(GetCSSPropertyBorderLeftColor()).IsOpaque() || StyleRef().BorderLeftStyle() != EBorderStyle::kSolid)) { return false; } @@ -6217,7 +6217,7 @@ // bottommost value from the background property (see final-bg-layer in // https://drafts.csswg.org/css-backgrounds/#the-background). if (!layer->GetImage() && !layer->Next() && - background_color.AlphaAsInteger() > 0 && + !background_color.IsFullyTransparent() && StyleRef().IsScrollbarGutterAuto()) { // Solid color layers with an effective background clip of the padding box // can be treated as local.
diff --git a/third_party/blink/renderer/core/layout/layout_theme.cc b/third_party/blink/renderer/core/layout/layout_theme.cc index e1f5c36..4ef3e33 100644 --- a/third_party/blink/renderer/core/layout/layout_theme.cc +++ b/third_party/blink/renderer/core/layout/layout_theme.cc
@@ -610,6 +610,14 @@ // https://www.w3.org/TR/css-color-4/#deprecated-system-colors. switch (css_value_id) { + case CSSValueID::kAccentcolor: + return RuntimeEnabledFeatures::CSSSystemAccentColorEnabled() + ? GetAccentColorOrDefault(color_scheme) + : Color(); + case CSSValueID::kAccentcolortext: + return RuntimeEnabledFeatures::CSSSystemAccentColorEnabled() + ? GetAccentColorText(color_scheme) + : Color(); case CSSValueID::kActivetext: return Color::FromRGBA32(0xFFFF0000); case CSSValueID::kButtonborder: @@ -869,4 +877,22 @@ ForcedColors::kNone; } +Color LayoutTheme::GetAccentColorOrDefault( + mojom::blink::ColorScheme color_scheme) const { + // This is from the kAccent color from NativeThemeBase::GetControlColor + const Color kDefaultAccentColor = Color(0x00, 0x75, 0xFF); + Color accent_color = GetSystemAccentColor(color_scheme); + return accent_color == Color() ? kDefaultAccentColor : accent_color; +} + +Color LayoutTheme::GetAccentColorText( + mojom::blink::ColorScheme color_scheme) const { + Color accent_color = GetAccentColorOrDefault(color_scheme); + // This logic matches AccentColorText in Firefox. If the accent color to draw + // text on is dark, then use white. If it's light, then use dark. + return color_utils::GetRelativeLuminance4f(accent_color.toSkColor4f()) <= 128 + ? Color::kWhite + : Color::kBlack; +} + } // namespace blink
diff --git a/third_party/blink/renderer/core/layout/layout_theme.h b/third_party/blink/renderer/core/layout/layout_theme.h index 2cb87ce..7437f1fa 100644 --- a/third_party/blink/renderer/core/layout/layout_theme.h +++ b/third_party/blink/renderer/core/layout/layout_theme.h
@@ -185,9 +185,18 @@ mojom::blink::ColorScheme color_scheme) const { return false; } - virtual Color GetAccentColor(mojom::blink::ColorScheme color_scheme) const { + // GetSystemAccentColor returns transparent unless there is a special value + // from the OS color scheme. + virtual Color GetSystemAccentColor( + mojom::blink::ColorScheme color_scheme) const { return Color(); } + // GetAccentColorOrDefault will return GetAccentColor if there is a value from + // the OS, otherwise it will return the default accent color. + Color GetAccentColorOrDefault(mojom::blink::ColorScheme color_scheme) const; + // GetAccentColorText returns black or white depending on which can be + // rendered with enough contrast on the result of GetAccentColorOrDefault. + Color GetAccentColorText(mojom::blink::ColorScheme color_scheme) const; bool InForcedColorsMode() const { return in_forced_colors_mode_; }
diff --git a/third_party/blink/renderer/core/layout/layout_theme_mac.h b/third_party/blink/renderer/core/layout/layout_theme_mac.h index 6e71638d..34c883ad 100644 --- a/third_party/blink/renderer/core/layout/layout_theme_mac.h +++ b/third_party/blink/renderer/core/layout/layout_theme_mac.h
@@ -52,7 +52,8 @@ bool SupportsSelectionForegroundColors() const override { return false; } bool IsAccentColorCustomized( mojom::blink::ColorScheme color_scheme) const override; - Color GetAccentColor(mojom::blink::ColorScheme color_scheme) const override; + Color GetSystemAccentColor( + mojom::blink::ColorScheme color_scheme) const override; protected: // Controls color values returned from FocusRingColor().
diff --git a/third_party/blink/renderer/core/layout/layout_theme_mac.mm b/third_party/blink/renderer/core/layout/layout_theme_mac.mm index ba3f469..8e8e0fa 100644 --- a/third_party/blink/renderer/core/layout/layout_theme_mac.mm +++ b/third_party/blink/renderer/core/layout/layout_theme_mac.mm
@@ -104,7 +104,7 @@ return true; } -Color LayoutThemeMac::GetAccentColor( +Color LayoutThemeMac::GetSystemAccentColor( mojom::blink::ColorScheme color_scheme) const { if (@available(macOS 10.14, *)) { return GetSystemColor(MacSystemColorID::kControlAccentColor, color_scheme);
diff --git a/third_party/blink/renderer/core/page/link_highlight.cc b/third_party/blink/renderer/core/page/link_highlight.cc index 4097fee..fe72cce 100644 --- a/third_party/blink/renderer/core/page/link_highlight.cc +++ b/third_party/blink/renderer/core/page/link_highlight.cc
@@ -62,7 +62,7 @@ // Safari documentation for -webkit-tap-highlight-color says if the // specified color has 0 alpha, then tap highlighting is disabled. // http://developer.apple.com/library/safari/#documentation/appleapplications/reference/safaricssref/articles/standardcssproperties.html - if (!highlight_color.AlphaAsInteger()) { + if (highlight_color.IsFullyTransparent()) { return; }
diff --git a/third_party/blink/renderer/core/paint/box_border_painter.cc b/third_party/blink/renderer/core/paint/box_border_painter.cc index 30be3139..8545ca4 100644 --- a/third_party/blink/renderer/core/paint/box_border_painter.cc +++ b/third_party/blink/renderer/core/paint/box_border_painter.cc
@@ -1082,7 +1082,7 @@ visible_edge_count_++; visible_edge_set_ |= EdgeFlagForSide(static_cast<BoxSide>(i)); - if (edge.GetColor().HasTransparency()) { + if (!edge.GetColor().IsOpaque()) { has_transparency_ = true; }
diff --git a/third_party/blink/renderer/core/paint/box_decoration_data.cc b/third_party/blink/renderer/core/paint/box_decoration_data.cc index abc75a5a6..485adf3d 100644 --- a/third_party/blink/renderer/core/paint/box_decoration_data.cc +++ b/third_party/blink/renderer/core/paint/box_decoration_data.cc
@@ -40,7 +40,7 @@ // behind the top layer. But only if we need to draw something // underneath. const FillLayer& fill_layer = style_.BackgroundLayers(); - if ((BackgroundColor().AlphaAsInteger() || fill_layer.Next()) && + if ((!BackgroundColor().IsFullyTransparent() || fill_layer.Next()) && !fill_layer.ImageOccludesNextLayers(layout_box_.GetDocument(), style_)) { return kBackgroundBleedClipLayer;
diff --git a/third_party/blink/renderer/core/paint/box_painter_base.cc b/third_party/blink/renderer/core/paint/box_painter_base.cc index b0e2dd9..e5dabd5 100644 --- a/third_party/blink/renderer/core/paint/box_painter_base.cc +++ b/third_party/blink/renderer/core/paint/box_painter_base.cc
@@ -150,8 +150,7 @@ bool has_border_radius = style.HasBorderRadius(); bool has_opaque_background = !background_is_skipped && - style.VisitedDependentColor(GetCSSPropertyBackgroundColor()) - .AlphaAsInteger() == 255; + style.VisitedDependentColor(GetCSSPropertyBackgroundColor()).IsOpaque(); GraphicsContextStateSaver state_saver(context, false); @@ -443,7 +442,7 @@ // Note that we can't reuse this variable below because the bgColor might // be changed. bool should_paint_background_color = - is_bottom_layer && color.AlphaAsInteger(); + is_bottom_layer && !color.IsFullyTransparent(); if (image || should_paint_background_color) { color = Color::kWhite; image = nullptr; @@ -478,7 +477,7 @@ // artifacts in order to run the animation on the compositor. should_paint_color = is_bottom_layer && - (color.AlphaAsInteger() || composite_bgcolor_animation) && + (!color.IsFullyTransparent() || composite_bgcolor_animation) && (!should_paint_image || !layer.ImageOccludesNextLayers(doc, style)); should_paint_color_with_paint_worklet_image = should_paint_color && composite_bgcolor_animation;
diff --git a/third_party/blink/renderer/core/paint/ng/ng_highlight_painter.cc b/third_party/blink/renderer/core/paint/ng/ng_highlight_painter.cc index 39a1ede..b42ab55 100644 --- a/third_party/blink/renderer/core/paint/ng/ng_highlight_painter.cc +++ b/third_party/blink/renderer/core/paint/ng/ng_highlight_painter.cc
@@ -75,7 +75,7 @@ const PhysicalRect& rect, const Color color, const AutoDarkMode& auto_dark_mode) { - if (!color.AlphaAsInteger()) { + if (color.IsFullyTransparent()) { return; } if (rect.size.IsEmpty()) @@ -100,7 +100,7 @@ Color text_color) { const Color color = HighlightPaintingUtils::HighlightBackgroundColor( document, style, node, absl::nullopt, kPseudoIdSelection); - if (!color.AlphaAsInteger()) { + if (color.IsFullyTransparent()) { return Color(); } @@ -195,10 +195,10 @@ if (pseudo_style->TextStrokeWidth() != originating_style.TextStrokeWidth()) return true; // If there is a background color. - if (HighlightPaintingUtils::ResolveColor( - document, originating_style, pseudo_style.get(), pseudo, - GetCSSPropertyBackgroundColor(), {}) - .AlphaAsInteger() > 0) { + if (!HighlightPaintingUtils::ResolveColor( + document, originating_style, pseudo_style.get(), pseudo, + GetCSSPropertyBackgroundColor(), {}) + .IsFullyTransparent()) { return true; } // If the ‘text-shadow’ is not ‘none’.
diff --git a/third_party/blink/renderer/core/paint/ng/ng_table_painters.cc b/third_party/blink/renderer/core/paint/ng/ng_table_painters.cc index 385c5b7..c4ff0d6 100644 --- a/third_party/blink/renderer/core/paint/ng/ng_table_painters.cc +++ b/third_party/blink/renderer/core/paint/ng/ng_table_painters.cc
@@ -883,7 +883,7 @@ Color color = table_part.StyleRef().VisitedDependentColor( GetCSSPropertyBackgroundColor()); const FillLayer& background_layers = table_part.StyleRef().BackgroundLayers(); - if (background_layers.AnyLayerHasImage() || color.AlphaAsInteger()) { + if (background_layers.AnyLayerHasImage() || !color.IsFullyTransparent()) { BackgroundImageGeometry geometry( layout_table_cell, table_cell_paint_offset - table_part_paint_rect.offset, table_part,
diff --git a/third_party/blink/renderer/core/paint/outline_painter.cc b/third_party/blink/renderer/core/paint/outline_painter.cc index 8660a5fd..dbf5f09 100644 --- a/third_party/blink/renderer/core/paint/outline_painter.cc +++ b/third_party/blink/renderer/core/paint/outline_painter.cc
@@ -456,11 +456,11 @@ return; } - bool use_alpha_layer = color_.HasTransparency() && + bool use_alpha_layer = !color_.IsOpaque() && outline_style_ != EBorderStyle::kSolid && outline_style_ != EBorderStyle::kDouble; if (use_alpha_layer) { - context_.BeginLayer(color_.AlphaAsInteger() / 255.0); + context_.BeginLayer(color_.Alpha()); color_ = Color::FromRGB(color_.Red(), color_.Green(), color_.Blue()); }
diff --git a/third_party/blink/renderer/core/paint/paint_property_tree_builder.cc b/third_party/blink/renderer/core/paint/paint_property_tree_builder.cc index 5e2523d..eb77674 100644 --- a/third_party/blink/renderer/core/paint/paint_property_tree_builder.cc +++ b/third_party/blink/renderer/core/paint/paint_property_tree_builder.cc
@@ -110,7 +110,11 @@ } PaintPropertyTreeBuilderContext::PaintPropertyTreeBuilderContext() - : composited_scrolling_preference( + : force_subtree_update_reasons(0), + has_svg_hidden_container_ancestor(false), + was_layout_shift_root(false), + global_main_thread_scrolling_reasons(0), + composited_scrolling_preference( static_cast<unsigned>(CompositedScrollingPreference::kDefault)) {} PaintPropertyTreeBuilderContext::~PaintPropertyTreeBuilderContext() {
diff --git a/third_party/blink/renderer/core/paint/paint_property_tree_builder.h b/third_party/blink/renderer/core/paint/paint_property_tree_builder.h index aed8e84..1884fd6 100644 --- a/third_party/blink/renderer/core/paint/paint_property_tree_builder.h +++ b/third_party/blink/renderer/core/paint/paint_property_tree_builder.h
@@ -213,19 +213,19 @@ // True if a change has forced all properties in a subtree to be updated. This // can be set due to paint offset changes or when the structure of the // property tree changes (i.e., a node is added or removed). - unsigned force_subtree_update_reasons : 2 = 0u; + unsigned force_subtree_update_reasons : 2; // True if the current subtree is underneath a LayoutSVGHiddenContainer // ancestor. - unsigned has_svg_hidden_container_ancestor : 1 = false; + unsigned has_svg_hidden_container_ancestor : 1; // Whether this object was a layout shift root during the previous render // (not this one). - unsigned was_layout_shift_root : 1 = false; + unsigned was_layout_shift_root : 1; // Main thread scrolling reasons that apply to all scrollers in the current // LocalFrameView subtree. - unsigned global_main_thread_scrolling_reasons : 5 = 0; + unsigned global_main_thread_scrolling_reasons : 5; static constexpr MainThreadScrollingReasons kGlobalMainThreadScrollingReasons = cc::MainThreadScrollingReason::kHasBackgroundAttachmentFixedObjects |
diff --git a/third_party/blink/renderer/core/paint/theme_painter_default.cc b/third_party/blink/renderer/core/paint/theme_painter_default.cc index 6ed18e0..194372d9 100644 --- a/third_party/blink/renderer/core/paint/theme_painter_default.cc +++ b/third_party/blink/renderer/core/paint/theme_painter_default.cc
@@ -181,7 +181,7 @@ mojom::blink::ColorScheme color_scheme = style.UsedColorScheme(); LayoutTheme& layout_theme = LayoutTheme::GetTheme(); if (layout_theme.IsAccentColorCustomized(color_scheme)) { - return layout_theme.GetAccentColor(color_scheme).Rgb(); + return layout_theme.GetSystemAccentColor(color_scheme).Rgb(); } return absl::nullopt; @@ -310,7 +310,7 @@ // FIXME: the normal Aura theme doesn't care about this, so we should // investigate if we really need fillContentArea. extra_params.menu_list.fill_content_area = - !style.HasBackgroundImage() && background_color.AlphaAsInteger(); + !style.HasBackgroundImage() && !background_color.IsFullyTransparent(); SetupMenuListArrow(document, style, rect, extra_params);
diff --git a/third_party/blink/renderer/core/paint/view_painter.cc b/third_party/blink/renderer/core/paint/view_painter.cc index ba7a0f4..b41fa73 100644 --- a/third_party/blink/renderer/core/paint/view_painter.cc +++ b/third_party/blink/renderer/core/paint/view_painter.cc
@@ -252,7 +252,7 @@ const LocalFrameView& frame_view = *layout_view_.GetFrameView(); bool paints_base_background = frame_view.ShouldPaintBaseBackgroundColor() && - (frame_view.BaseBackgroundColor().AlphaAsInteger() > 0); + !frame_view.BaseBackgroundColor().IsFullyTransparent(); Color base_background_color = paints_base_background ? frame_view.BaseBackgroundColor() : Color(); if (document.Printing() && base_background_color == Color::kWhite) { @@ -324,7 +324,7 @@ if (!background_renderable) { if (!painted_separate_backdrop) { - if (base_background_color.AlphaAsInteger()) { + if (!base_background_color.IsFullyTransparent()) { context.FillRect( pixel_snapped_background_rect, base_background_color, auto_dark_mode, @@ -357,7 +357,7 @@ // We are going to clear the canvas with transparent pixels, isolation group // can be skipped. - if (!base_background_color.AlphaAsInteger() && should_clear_canvas) { + if (base_background_color.IsFullyTransparent() && should_clear_canvas) { should_draw_background_in_separate_buffer = false; } } @@ -368,7 +368,7 @@ // mode. An extra BeginLayer will result in incorrect blend isolation if // it is added on top of any effect on the root element. if (should_draw_background_in_separate_buffer && !painted_separate_effect) { - if (base_background_color.AlphaAsInteger()) { + if (!base_background_color.IsFullyTransparent()) { context.FillRect( paint_rect, base_background_color, auto_dark_mode, should_clear_canvas ? SkBlendMode::kSrc : SkBlendMode::kSrcOver); @@ -384,7 +384,7 @@ if (combined_background_color != frame_view.BaseBackgroundColor()) context.GetPaintController().SetFirstPainted(); - if (combined_background_color.AlphaAsInteger()) { + if (!combined_background_color.IsFullyTransparent()) { context.FillRect( paint_rect, combined_background_color, auto_dark_mode, (should_draw_background_in_separate_buffer || should_clear_canvas)
diff --git a/third_party/blink/renderer/core/scroll/scrollable_area.cc b/third_party/blink/renderer/core/scroll/scrollable_area.cc index b9dfca0d..736e311 100644 --- a/third_party/blink/renderer/core/scroll/scrollable_area.cc +++ b/third_party/blink/renderer/core/scroll/scrollable_area.cc
@@ -671,7 +671,7 @@ if (GetLayoutBox()) { Color background_color = GetLayoutBox()->StyleRef().VisitedDependentColor( GetCSSPropertyBackgroundColor()); - if (background_color.AlphaAsInteger()) { + if (!background_color.IsFullyTransparent()) { double hue, saturation, lightness; background_color.GetHSL(hue, saturation, lightness); overlay_theme = lightness <= 0.5 ? kScrollbarOverlayColorThemeLight
diff --git a/third_party/blink/renderer/core/style/border_edge.cc b/third_party/blink/renderer/core/style/border_edge.cc index 7035ba5..d141ef4 100644 --- a/third_party/blink/renderer/core/style/border_edge.cc +++ b/third_party/blink/renderer/core/style/border_edge.cc
@@ -30,7 +30,7 @@ } bool BorderEdge::HasVisibleColorAndStyle() const { - return style_ > EBorderStyle::kHidden && color_.AlphaAsInteger() > 0; + return style_ > EBorderStyle::kHidden && !color_.IsFullyTransparent(); } bool BorderEdge::ShouldRender() const { @@ -42,8 +42,7 @@ } bool BorderEdge::ObscuresBackgroundEdge() const { - if (!is_present_ || color_.HasTransparency() || - style_ == EBorderStyle::kHidden) { + if (!is_present_ || !color_.IsOpaque() || style_ == EBorderStyle::kHidden) { return false; } @@ -55,8 +54,7 @@ } bool BorderEdge::ObscuresBackground() const { - if (!is_present_ || color_.HasTransparency() || - style_ == EBorderStyle::kHidden) { + if (!is_present_ || !color_.IsOpaque() || style_ == EBorderStyle::kHidden) { return false; }
diff --git a/third_party/blink/renderer/core/style/computed_style.cc b/third_party/blink/renderer/core/style/computed_style.cc index 4cde86d..09dfa724 100644 --- a/third_party/blink/renderer/core/style/computed_style.cc +++ b/third_party/blink/renderer/core/style/computed_style.cc
@@ -2257,8 +2257,8 @@ StyleColor text_stroke_style_color = visited_link ? InternalVisitedTextStrokeColor() : TextStrokeColor(); if (!text_stroke_style_color.IsCurrentColor() && - text_stroke_style_color.Resolve(blink::Color(), UsedColorScheme()) - .AlphaAsInteger()) { + !text_stroke_style_color.Resolve(blink::Color(), UsedColorScheme()) + .IsFullyTransparent()) { return text_stroke_style_color; } } @@ -2273,7 +2273,7 @@ blink::Color color = GetCSSPropertyBackgroundColor().ColorIncludingFallback( false, *this, /*is_current_color=*/nullptr); - if (color.AlphaAsInteger()) { + if (!color.IsFullyTransparent()) { return true; } // When background color animation is running on the compositor thread, we
diff --git a/third_party/blink/renderer/core/style/computed_style.h b/third_party/blink/renderer/core/style/computed_style.h index c3bff2b..c9a5aa86 100644 --- a/third_party/blink/renderer/core/style/computed_style.h +++ b/third_party/blink/renderer/core/style/computed_style.h
@@ -1007,9 +1007,9 @@ return !HasAutoColumnCount() || !HasAutoColumnWidth(); } bool ColumnRuleIsTransparent() const { - return !ColumnRuleColor() - .Resolve(GetCurrentColor(), UsedColorScheme()) - .AlphaAsInteger(); + return ColumnRuleColor() + .Resolve(GetCurrentColor(), UsedColorScheme()) + .IsFullyTransparent(); } bool ColumnRuleEquivalent(const ComputedStyle& other_style) const; bool HasColumnRule() const {
diff --git a/third_party/blink/renderer/core/svg/graphics/svg_image.cc b/third_party/blink/renderer/core/svg/graphics/svg_image.cc index 86ea7b6..759fdc3 100644 --- a/third_party/blink/renderer/core/svg/graphics/svg_image.cc +++ b/third_party/blink/renderer/core/svg/graphics/svg_image.cc
@@ -70,10 +70,8 @@ #include "third_party/blink/renderer/platform/graphics/graphics_context.h" #include "third_party/blink/renderer/platform/graphics/image_observer.h" #include "third_party/blink/renderer/platform/graphics/paint/cull_rect.h" -#include "third_party/blink/renderer/platform/graphics/paint/drawing_recorder.h" #include "third_party/blink/renderer/platform/graphics/paint/paint_canvas.h" #include "third_party/blink/renderer/platform/graphics/paint/paint_record.h" -#include "third_party/blink/renderer/platform/graphics/paint/paint_record_builder.h" #include "third_party/blink/renderer/platform/graphics/paint/paint_shader.h" #include "third_party/blink/renderer/platform/heap/garbage_collected.h" #include "third_party/blink/renderer/platform/instrumentation/histogram.h" @@ -395,20 +393,17 @@ pattern_transform.setTranslate(tiling_info.phase.x() + spaced_tile.x(), tiling_info.phase.y() + spaced_tile.y()); - auto* builder = MakeGarbageCollected<PaintRecordBuilder>(context); - { - DrawingRecorder recorder(builder->Context(), *builder, - DisplayItem::Type::kSVGImage); - // When generating an expanded tile, make sure we don't draw into the - // spacing area. - if (!tiling_info.spacing.IsZero()) - builder->Context().Clip(tile); - DrawForContainer(draw_info, builder->Context().Canvas(), cc::PaintFlags(), - tile, tiling_info.image_rect); + PaintRecorder recorder; + cc::PaintCanvas* tile_canvas = recorder.beginRecording(); + // When generating an expanded tile, make sure we don't draw into the + // spacing area. + if (!tiling_info.spacing.IsZero()) { + tile_canvas->clipRect(gfx::RectFToSkRect(tile)); } - + DrawForContainer(draw_info, tile_canvas, cc::PaintFlags(), tile, + tiling_info.image_rect); sk_sp<PaintShader> tile_shader = PaintShader::MakePaintRecord( - builder->EndRecording(), gfx::RectFToSkRect(spaced_tile), + recorder.finishRecordingAsPicture(), gfx::RectFToSkRect(spaced_tile), SkTileMode::kRepeat, SkTileMode::kRepeat, &pattern_transform); // If the shader could not be instantiated (e.g. non-invertible matrix),
diff --git a/third_party/blink/renderer/core/svg/svg_animated_color.cc b/third_party/blink/renderer/core/svg/svg_animated_color.cc index 287bc8f6..1606aff 100644 --- a/third_party/blink/renderer/core/svg/svg_animated_color.cc +++ b/third_party/blink/renderer/core/svg/svg_animated_color.cc
@@ -101,6 +101,7 @@ Color to_at_end_of_duration_color = to_at_end_of_duration_style_color.Resolve(fallback_color, color_scheme); + // TODO(crbug.com/1399566): Use float color and don't clobber colorspace. float animated_red = ComputeAnimatedNumber( parameters, percentage, repeat_count, from_color.Red(), to_color.Red(), to_at_end_of_duration_color.Red());
diff --git a/third_party/blink/renderer/modules/accessibility/ax_layout_object.cc b/third_party/blink/renderer/modules/accessibility/ax_layout_object.cc index 2a37a4aa..b054bb0 100644 --- a/third_party/blink/renderer/modules/accessibility/ax_layout_object.cc +++ b/third_party/blink/renderer/modules/accessibility/ax_layout_object.cc
@@ -1177,7 +1177,7 @@ Color cell_color = computed_style->VisitedDependentColor( GetCSSPropertyBackgroundColor()); if (has_cell_spacing && table_bg_color != cell_color && - cell_color.AlphaAsInteger() != 1) { + !cell_color.IsFullyTransparent()) { background_difference_cell_count++; }
diff --git a/third_party/blink/renderer/modules/accessibility/ax_node_object.cc b/third_party/blink/renderer/modules/accessibility/ax_node_object.cc index 67dd289..469deee 100644 --- a/third_party/blink/renderer/modules/accessibility/ax_node_object.cc +++ b/third_party/blink/renderer/modules/accessibility/ax_node_object.cc
@@ -2279,6 +2279,27 @@ return ax_target; } +const AtomicString& AXNodeObject::EffectiveTarget() const { + // The "target" attribute defines the target browser context and is supported + // on <a>, <area>, <base>, and <form>. Valid values are: "frame_name", "self", + // "blank", "top", and "parent", where "frame_name" is the value of the "name" + // attribute on any enclosing iframe. + // + // <area> is a subclass of <a>, while <base> provides the document's base + // target that any <a>'s or any <area>'s target can override. + // `HtmlAnchorElement::GetEffectiveTarget()` will take <base> into account. + // + // <form> is out of scope, because it affects the target to which the form is + // submitted, and could also be overridden by a "formTarget" attribute on e.g. + // a form's submit button. However, screen reader users have no need to know + // to which target (browser context) a form would be submitted. + const auto* anchor = DynamicTo<HTMLAnchorElement>(GetNode()); + if (anchor) { + return anchor->GetEffectiveTarget(); + } + return AXObject::EffectiveTarget(); +} + AccessibilityOrientation AXNodeObject::Orientation() const { const AtomicString& aria_orientation = GetAOMPropertyOrARIAAttribute(AOMStringProperty::kOrientation);
diff --git a/third_party/blink/renderer/modules/accessibility/ax_node_object.h b/third_party/blink/renderer/modules/accessibility/ax_node_object.h index f52e3a500..24c584f 100644 --- a/third_party/blink/renderer/modules/accessibility/ax_node_object.h +++ b/third_party/blink/renderer/modules/accessibility/ax_node_object.h
@@ -141,6 +141,7 @@ unsigned HierarchicalLevel() const final; void SerializeMarkerAttributes(ui::AXNodeData* node_data) const override; AXObject* InPageLinkTarget() const override; + const AtomicString& EffectiveTarget() const override; AccessibilityOrientation Orientation() const override; AXObject* GetChildFigcaption() const override;
diff --git a/third_party/blink/renderer/modules/accessibility/ax_object.cc b/third_party/blink/renderer/modules/accessibility/ax_object.cc index ec6b1cb..532e17d 100644 --- a/third_party/blink/renderer/modules/accessibility/ax_object.cc +++ b/third_party/blink/renderer/modules/accessibility/ax_object.cc
@@ -1772,6 +1772,13 @@ node_data->AddIntAttribute( ax::mojom::blink::IntAttribute::kInPageLinkTargetId, target_id); } + + // `ax::mojom::blink::StringAttribute::kLinkTarget` is only valid on <a> and + // <area> elements. <area> elements should link to something in order to be + // considered, see `AXImageMap::Role()`. + TruncateAndAddStringAttribute( + node_data, ax::mojom::blink::StringAttribute::kLinkTarget, + EffectiveTarget()); } if (node_data->role == ax::mojom::blink::Role::kRadioButton) { @@ -4441,6 +4448,14 @@ HasAttribute(html_names::kTitleAttr); } +AXObject* AXObject::InPageLinkTarget() const { + return nullptr; +} + +const AtomicString& AXObject::EffectiveTarget() const { + return g_null_atom; +} + AccessibilityOrientation AXObject::Orientation() const { // In ARIA 1.1, the default value for aria-orientation changed from // horizontal to undefined.
diff --git a/third_party/blink/renderer/modules/accessibility/ax_object.h b/third_party/blink/renderer/modules/accessibility/ax_object.h index ea708a4..359ae2e 100644 --- a/third_party/blink/renderer/modules/accessibility/ax_object.h +++ b/third_party/blink/renderer/modules/accessibility/ax_object.h
@@ -633,7 +633,10 @@ // <a href="#foo">, this will return the AXObject for the target. // The object returned should be unignored. If necessary, it will return // a descendant of the actual target. - virtual AXObject* InPageLinkTarget() const { return nullptr; } + virtual AXObject* InPageLinkTarget() const; + // Returns the value of the "target" attribute, e.g. <a href="example.com" + // target="blank">. + virtual const AtomicString& EffectiveTarget() const; virtual AccessibilityOrientation Orientation() const; virtual ax::mojom::blink::ListStyle GetListStyle() const { return ax::mojom::blink::ListStyle::kNone;
diff --git a/third_party/blink/renderer/modules/environment_integrity/BUILD.gn b/third_party/blink/renderer/modules/environment_integrity/BUILD.gn index d2b820d..3899bef 100644 --- a/third_party/blink/renderer/modules/environment_integrity/BUILD.gn +++ b/third_party/blink/renderer/modules/environment_integrity/BUILD.gn
@@ -6,6 +6,8 @@ blink_modules_sources("environment_integrity") { sources = [ + "environment_integrity.cc", + "environment_integrity.h", "navigator_environment_integrity.cc", "navigator_environment_integrity.h", ]
diff --git a/third_party/blink/renderer/modules/environment_integrity/environment_integrity.cc b/third_party/blink/renderer/modules/environment_integrity/environment_integrity.cc new file mode 100644 index 0000000..4a46192e --- /dev/null +++ b/third_party/blink/renderer/modules/environment_integrity/environment_integrity.cc
@@ -0,0 +1,38 @@ +// Copyright 2023 The Chromium Authors +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "third_party/blink/renderer/modules/environment_integrity/environment_integrity.h" + +#include "third_party/blink/renderer/core/typed_arrays/dom_array_buffer.h" +#include "third_party/blink/renderer/platform/bindings/script_state.h" +#include "third_party/blink/renderer/platform/wtf/text/base64.h" +#include "third_party/blink/renderer/platform/wtf/text/string_builder.h" +#include "third_party/blink/renderer/platform/wtf/text/wtf_string.h" + +namespace blink { + +namespace { + +base::span<const uint8_t> DOMArrayBufferToSpan(DOMArrayBuffer* buffer) { + return base::make_span(static_cast<const uint8_t*>(buffer->Data()), + buffer->ByteLength()); +} + +} // namespace + +EnvironmentIntegrity::EnvironmentIntegrity(DOMArrayBuffer* attestation_token) + : attestation_token_(attestation_token) {} + +EnvironmentIntegrity::~EnvironmentIntegrity() = default; + +String EnvironmentIntegrity::encode(ScriptState* script_state) { + return WTF::Base64Encode(DOMArrayBufferToSpan(attestation_token_.Get())); +} + +void EnvironmentIntegrity::Trace(Visitor* visitor) const { + visitor->Trace(attestation_token_); + ScriptWrappable::Trace(visitor); +} + +} // namespace blink
diff --git a/third_party/blink/renderer/modules/environment_integrity/environment_integrity.h b/third_party/blink/renderer/modules/environment_integrity/environment_integrity.h new file mode 100644 index 0000000..0c8cc2a --- /dev/null +++ b/third_party/blink/renderer/modules/environment_integrity/environment_integrity.h
@@ -0,0 +1,38 @@ +// Copyright 2023 The Chromium Authors +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef THIRD_PARTY_BLINK_RENDERER_MODULES_ENVIRONMENT_INTEGRITY_ENVIRONMENT_INTEGRITY_H_ +#define THIRD_PARTY_BLINK_RENDERER_MODULES_ENVIRONMENT_INTEGRITY_ENVIRONMENT_INTEGRITY_H_ + +#include "third_party/blink/renderer/core/typed_arrays/dom_array_buffer.h" +#include "third_party/blink/renderer/platform/bindings/script_state.h" +#include "third_party/blink/renderer/platform/bindings/script_wrappable.h" +#include "third_party/blink/renderer/platform/heap/member.h" +#include "third_party/blink/renderer/platform/wtf/text/wtf_string.h" + +namespace blink { + +class EnvironmentIntegrity : public ScriptWrappable { + DEFINE_WRAPPERTYPEINFO(); + + public: + explicit EnvironmentIntegrity(DOMArrayBuffer* attestation_token); + ~EnvironmentIntegrity() override; + + EnvironmentIntegrity(const EnvironmentIntegrity&) = delete; + EnvironmentIntegrity& operator=(const EnvironmentIntegrity&) = delete; + + String encode(ScriptState*); + + DOMArrayBuffer* attestationToken() const { return attestation_token_.Get(); } + + void Trace(Visitor*) const override; + + private: + const Member<DOMArrayBuffer> attestation_token_; +}; + +} // namespace blink + +#endif // THIRD_PARTY_BLINK_RENDERER_MODULES_ENVIRONMENT_INTEGRITY_ENVIRONMENT_INTEGRITY_H_
diff --git a/third_party/blink/renderer/modules/environment_integrity/environment_integrity.idl b/third_party/blink/renderer/modules/environment_integrity/environment_integrity.idl new file mode 100644 index 0000000..a5dcf6d1 --- /dev/null +++ b/third_party/blink/renderer/modules/environment_integrity/environment_integrity.idl
@@ -0,0 +1,12 @@ +// Copyright 2023 The Chromium Authors +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +[ + SecureContext, + RuntimeEnabled=WebEnvironmentIntegrity +] interface EnvironmentIntegrity { + readonly attribute ArrayBuffer attestationToken; + // Returns a base64 encoded string of 'attestationToken'. + [CallWith=ScriptState] DOMString encode(); +};
diff --git a/third_party/blink/renderer/modules/environment_integrity/navigator_environment_integrity.cc b/third_party/blink/renderer/modules/environment_integrity/navigator_environment_integrity.cc index 7ebcb49..f4149dc 100644 --- a/third_party/blink/renderer/modules/environment_integrity/navigator_environment_integrity.cc +++ b/third_party/blink/renderer/modules/environment_integrity/navigator_environment_integrity.cc
@@ -4,8 +4,10 @@ #include "third_party/blink/renderer/modules/environment_integrity/navigator_environment_integrity.h" +#include "build/build_config.h" #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/modules/environment_integrity/environment_integrity.h" #include "third_party/blink/renderer/platform/bindings/script_state.h" #include "third_party/blink/renderer/platform/heap/garbage_collected.h" #include "third_party/blink/renderer/platform/wtf/text/wtf_string.h" @@ -39,8 +41,17 @@ script_state, exception_state.GetContext()); ScriptPromise promise = resolver->Promise(); +#if BUILDFLAG(IS_ANDROID) + Vector<uint8_t> empty_vec; + DOMArrayBuffer* buffer = + DOMArrayBuffer::Create(empty_vec.data(), empty_vec.size()); + EnvironmentIntegrity* environment_integrity = + MakeGarbageCollected<EnvironmentIntegrity>(std::move(buffer)); + resolver->Resolve(environment_integrity); +#else resolver->RejectWithDOMException(DOMExceptionCode::kNotSupportedError, "Operation not supported"); +#endif return promise; }
diff --git a/third_party/blink/renderer/modules/environment_integrity/navigator_environment_integrity.idl b/third_party/blink/renderer/modules/environment_integrity/navigator_environment_integrity.idl index 3a55cc3..c562729 100644 --- a/third_party/blink/renderer/modules/environment_integrity/navigator_environment_integrity.idl +++ b/third_party/blink/renderer/modules/environment_integrity/navigator_environment_integrity.idl
@@ -11,6 +11,6 @@ ] partial interface Navigator { [CallWith=ScriptState, RaisesException] - Promise<DOMString> getEnvironmentIntegrity(DOMString contentBinding); + Promise<EnvironmentIntegrity> getEnvironmentIntegrity(DOMString contentBinding); };
diff --git a/third_party/blink/renderer/modules/file_system_access/file_system_directory_handle.idl b/third_party/blink/renderer/modules/file_system_access/file_system_directory_handle.idl index fe8351bd..11dc7134b 100644 --- a/third_party/blink/renderer/modules/file_system_access/file_system_directory_handle.idl +++ b/third_party/blink/renderer/modules/file_system_access/file_system_directory_handle.idl
@@ -17,10 +17,27 @@ [RaisesException] FileSystemDirectoryIterator keys(); [RaisesException] FileSystemDirectoryIterator values(); - [CallWith=ScriptState,RaisesException] Promise<FileSystemFileHandle> getFileHandle(USVString name, optional FileSystemGetFileOptions options = {}); - [CallWith=ScriptState,RaisesException] Promise<FileSystemDirectoryHandle> getDirectoryHandle(USVString name, optional FileSystemGetDirectoryOptions options = {}); + [ + CallWith=ScriptState, + RaisesException + ] Promise<FileSystemFileHandle> getFileHandle(USVString name, + optional FileSystemGetFileOptions options = {}); + [ + CallWith=ScriptState, + RaisesException + ] Promise<FileSystemDirectoryHandle> getDirectoryHandle(USVString name, + optional FileSystemGetDirectoryOptions options = {}); - [CallWith=ScriptState,RaisesException] Promise<void> removeEntry(USVString name, optional FileSystemRemoveOptions options = {}); + [ + CallWith=ScriptState, + RaisesException, + Measure + ] Promise<void> removeEntry(USVString name, + optional FileSystemRemoveOptions options = {}); - [CallWith=ScriptState, Measure,RaisesException] Promise<sequence<USVString>?> resolve(FileSystemHandle possibleChild); + [ + CallWith=ScriptState, + RaisesException, + Measure + ] Promise<sequence<USVString>?> resolve(FileSystemHandle possibleChild); };
diff --git a/third_party/blink/renderer/modules/file_system_access/file_system_file_handle.idl b/third_party/blink/renderer/modules/file_system_access/file_system_file_handle.idl index 8689e90..5e46c48 100644 --- a/third_party/blink/renderer/modules/file_system_access/file_system_file_handle.idl +++ b/third_party/blink/renderer/modules/file_system_access/file_system_file_handle.idl
@@ -9,33 +9,43 @@ Serializable, RuntimeEnabled=FileSystemAccess ] interface FileSystemFileHandle : FileSystemHandle { - [CallWith=ScriptState, RaisesException] - Promise<FileSystemWritableFileStream> createWritable( + [ + CallWith=ScriptState, + RaisesException, + Measure + ] Promise<FileSystemWritableFileStream> createWritable( optional FileSystemCreateWritableOptions options = {}); - [CallWith=ScriptState, RaisesException] Promise<File> getFile(); - [ CallWith=ScriptState, RaisesException, - Exposed=DedicatedWorker, - RuntimeEnabled=FileSystemAccessAccessHandle, Measure + ] Promise<File> getFile(); + + [ + CallWith=ScriptState, + RaisesException, + Measure, + Exposed=DedicatedWorker, + RuntimeEnabled=FileSystemAccessAccessHandle ] Promise<FileSystemSyncAccessHandle> createSyncAccessHandle(); [ CallWith=ScriptState, RaisesException, + MeasureAs=FileSystemAccessMoveRename, RuntimeEnabled=FileSystemAccessAccessHandle ] Promise<void> move(USVString new_entry_name); [ CallWith=ScriptState, RaisesException, + MeasureAs=FileSystemAccessMoveReparent, RuntimeEnabled=FileSystemAccessAccessHandle ] Promise<void> move(FileSystemDirectoryHandle destination_directory); [ CallWith=ScriptState, RaisesException, + MeasureAs=FileSystemAccessMoveReparentAndRename, RuntimeEnabled=FileSystemAccessAccessHandle ] Promise<void> move(FileSystemDirectoryHandle destination_directory, USVString new_entry_name);
diff --git a/third_party/blink/renderer/modules/file_system_access/file_system_handle.idl b/third_party/blink/renderer/modules/file_system_access/file_system_handle.idl index 1146c685..6454fda7 100644 --- a/third_party/blink/renderer/modules/file_system_access/file_system_handle.idl +++ b/third_party/blink/renderer/modules/file_system_access/file_system_handle.idl
@@ -30,38 +30,40 @@ ] Promise<PermissionState> requestPermission( optional FileSystemHandlePermissionDescriptor descriptor = {}); + // TODO(https://crbug.com/1250534): Measure these methods once directory + // moves are supported. [ CallWith=ScriptState, RaisesException, RuntimeEnabled=FileSystemAccessAPIExperimental - ] Promise<void> move(USVString new_entry_name); + ] Promise<void> move(USVString new_entry_name); [ CallWith=ScriptState, RaisesException, RuntimeEnabled=FileSystemAccessAPIExperimental - ] Promise<void> move(FileSystemDirectoryHandle destination_directory); + ] Promise<void> move(FileSystemDirectoryHandle destination_directory); [ CallWith=ScriptState, RaisesException, RuntimeEnabled=FileSystemAccessAPIExperimental - ] Promise<void> move(FileSystemDirectoryHandle destination_directory, - USVString new_entry_name); + ] Promise<void> move(FileSystemDirectoryHandle destination_directory, + USVString new_entry_name); [ CallWith=ScriptState, - RaisesException - ] - Promise<void> remove(optional FileSystemRemoveOptions options = {}); + RaisesException, + Measure + ] Promise<void> remove(optional FileSystemRemoveOptions options = {}); [ CallWith=ScriptState, RaisesException, Measure - ] - Promise<boolean> isSameEntry(FileSystemHandle other); + ] Promise<boolean> isSameEntry(FileSystemHandle other); [ CallWith=ScriptState, RaisesException, + Measure, RuntimeEnabled=FileSystemAccessAPIExperimental ] Promise<USVString> getUniqueId(); };
diff --git a/third_party/blink/renderer/modules/file_system_access/file_system_writable_file_stream.idl b/third_party/blink/renderer/modules/file_system_access/file_system_writable_file_stream.idl index 77b6abd..a224817 100644 --- a/third_party/blink/renderer/modules/file_system_access/file_system_writable_file_stream.idl +++ b/third_party/blink/renderer/modules/file_system_access/file_system_writable_file_stream.idl
@@ -7,8 +7,19 @@ Exposed=(Window,Worker), SecureContext, RuntimeEnabled=FileSystemAccess - ] interface FileSystemWritableFileStream : WritableStream { - [CallWith=ScriptState, RaisesException] Promise<void> write((BufferSource or Blob or USVString or WriteParams) data); - [CallWith=ScriptState, RaisesException] Promise<void> truncate(unsigned long long size); - [CallWith=ScriptState, RaisesException] Promise<void> seek(unsigned long long offset); - }; +] interface FileSystemWritableFileStream : WritableStream { + [ + CallWith=ScriptState, + RaisesException + ] Promise<void> write((BufferSource or Blob or USVString or WriteParams) data); + + [ + CallWith=ScriptState, + RaisesException + ] Promise<void> truncate(unsigned long long size); + + [ + CallWith=ScriptState, + RaisesException + ] Promise<void> seek(unsigned long long offset); +};
diff --git a/third_party/blink/renderer/platform/graphics/color.cc b/third_party/blink/renderer/platform/graphics/color.cc index 7b98ce6..fc87d83 100644 --- a/third_party/blink/renderer/platform/graphics/color.cc +++ b/third_party/blink/renderer/platform/graphics/color.cc
@@ -761,7 +761,7 @@ } bool Color::SetFromString(const String& name) { - // TODO(https://crbug.com/1333988): Implement CSS Color level 4 parsing. + // TODO(https://crbug.com/1434423): Implement CSS Color level 4 parsing. if (name[0] != '#') return SetNamedColor(name); if (name.Is8Bit()) @@ -900,7 +900,7 @@ return SerializeAsCSSColor(); } - if (HasTransparency()) { + if (!IsOpaque()) { return String::Format("#%02X%02X%02X%02X", Red(), Green(), Blue(), AlphaAsInteger()); } @@ -962,33 +962,36 @@ } Color Color::Blend(const Color& source) const { - // TODO(https://crbug.com/1333988): Implement CSS Color level 4 blending. + // TODO(https://crbug.com/1434423): CSS Color level 4 blending is implemented. + // Remove this function. if (IsFullyTransparent() || source.IsOpaque()) { return source; } - if (!source.AlphaAsInteger()) { + if (source.IsFullyTransparent()) { return *this; } - int d = 255 * (AlphaAsInteger() + source.AlphaAsInteger()) - - AlphaAsInteger() * source.AlphaAsInteger(); + int source_alpha = source.AlphaAsInteger(); + int alpha = AlphaAsInteger(); + + int d = 255 * (alpha + source_alpha) - alpha * source_alpha; int a = d / 255; - int r = (Red() * AlphaAsInteger() * (255 - source.AlphaAsInteger()) + - 255 * source.AlphaAsInteger() * source.Red()) / + int r = (Red() * alpha * (255 - source_alpha) + + 255 * source_alpha * source.Red()) / d; - int g = (Green() * AlphaAsInteger() * (255 - source.AlphaAsInteger()) + - 255 * source.AlphaAsInteger() * source.Green()) / + int g = (Green() * alpha * (255 - source_alpha) + + 255 * source_alpha * source.Green()) / d; - int b = (Blue() * AlphaAsInteger() * (255 - source.AlphaAsInteger()) + - 255 * source.AlphaAsInteger() * source.Blue()) / + int b = (Blue() * alpha * (255 - source_alpha) + + 255 * source_alpha * source.Blue()) / d; return Color(r, g, b, a); } Color Color::BlendWithWhite() const { // If the color contains alpha already, we leave it alone. - if (HasTransparency()) { + if (!IsOpaque()) { return *this; } @@ -1011,17 +1014,19 @@ } void Color::GetRGBA(float& r, float& g, float& b, float& a) const { + // TODO(crbug.com/1399566): Check for colorspace. r = Red() / 255.0f; g = Green() / 255.0f; b = Blue() / 255.0f; - a = AlphaAsInteger() / 255.0f; + a = Alpha(); } void Color::GetRGBA(double& r, double& g, double& b, double& a) const { + // TODO(crbug.com/1399566): Check for colorspace. r = Red() / 255.0; g = Green() / 255.0; b = Blue() / 255.0; - a = AlphaAsInteger() / 255.0; + a = Alpha(); } // Hue, max and min are returned in range of 0.0 to 1.0.
diff --git a/third_party/blink/renderer/platform/graphics/color.h b/third_party/blink/renderer/platform/graphics/color.h index 6e5de2f..4f1582f 100644 --- a/third_party/blink/renderer/platform/graphics/color.h +++ b/third_party/blink/renderer/platform/graphics/color.h
@@ -264,7 +264,6 @@ bool IsFullyTransparent() const { return Alpha() <= 0.0f; } bool IsOpaque() const { return Alpha() >= 1.0f; } - bool HasTransparency() const { return !IsOpaque(); } float Param0() const { return param0_; } float Param1() const { return param1_; }
diff --git a/third_party/blink/renderer/platform/graphics/compositing/layers_as_json.cc b/third_party/blink/renderer/platform/graphics/compositing/layers_as_json.cc index f73c240..0a9bd119 100644 --- a/third_party/blink/renderer/platform/graphics/compositing/layers_as_json.cc +++ b/third_party/blink/renderer/platform/graphics/compositing/layers_as_json.cc
@@ -73,7 +73,7 @@ if (layer.should_check_backface_visibility()) json->SetString("backfaceVisibility", "hidden"); - if (Color::FromSkColor4f(layer.background_color()).AlphaAsInteger() && + if (!Color::FromSkColor4f(layer.background_color()).IsFullyTransparent() && ((flags & kLayerTreeIncludesDebugInfo) || // Omit backgroundColor for these layers because it's not interesting // and we want to avoid platform differences and changes with CLs
diff --git a/third_party/blink/renderer/platform/graphics/draw_looper_builder.cc b/third_party/blink/renderer/platform/graphics/draw_looper_builder.cc index 5b92fdc7..1f2cbed 100644 --- a/third_party/blink/renderer/platform/graphics/draw_looper_builder.cc +++ b/third_party/blink/renderer/platform/graphics/draw_looper_builder.cc
@@ -64,7 +64,7 @@ DCHECK_GE(blur, 0); // Detect when there's no effective shadow. - if (!color.AlphaAsInteger()) { + if (color.IsFullyTransparent()) { return; }
diff --git a/third_party/blink/renderer/platform/loader/BUILD.gn b/third_party/blink/renderer/platform/loader/BUILD.gn index 3e32bc63..94a2c22 100644 --- a/third_party/blink/renderer/platform/loader/BUILD.gn +++ b/third_party/blink/renderer/platform/loader/BUILD.gn
@@ -176,7 +176,6 @@ deps = [ ":make_platform_loader_generated_delivery_type_names", ":make_platform_loader_generated_fetch_initiator_type_names", - "//base", "//components/link_header_util", "//components/variations/net:net", "//net", @@ -198,10 +197,6 @@ ] allow_circular_includes_from = [ "//third_party/blink/renderer/platform/network:network" ] - - if (is_apple) { - deps += [ "//base:base_arc" ] - } } source_set("unit_tests") {
diff --git a/third_party/blink/renderer/platform/runtime_enabled_features.json5 b/third_party/blink/renderer/platform/runtime_enabled_features.json5 index 3e2d5a2..a806b509 100644 --- a/third_party/blink/renderer/platform/runtime_enabled_features.json5 +++ b/third_party/blink/renderer/platform/runtime_enabled_features.json5
@@ -1118,6 +1118,10 @@ status: "experimental", }, { + name: "CSSSystemAccentColor", + status: "experimental", + }, + { // TODO(https://crbug.com/1411581): // https://w3c.github.io/csswg-drafts/css-inline-3/#propdef-leading-trim name: "CSSTextBoxTrim", @@ -1337,6 +1341,10 @@ status: "experimental", base_feature: "none", }, + { + name: "DisableSelectAllForEmptyText", + status: "stable", + }, // This feature should only be enabled if // DisableThirdPartyStoragePartitioning is enabled, but as // DisableThirdPartyStoragePartitioning will be linked to a deprecation
diff --git a/third_party/blink/tools/blinkpy/presubmit/audit_non_blink_usage.py b/third_party/blink/tools/blinkpy/presubmit/audit_non_blink_usage.py index a8aaf1d2..a6044599 100755 --- a/third_party/blink/tools/blinkpy/presubmit/audit_non_blink_usage.py +++ b/third_party/blink/tools/blinkpy/presubmit/audit_non_blink_usage.py
@@ -169,6 +169,7 @@ # //base/functional/callback.h is allowed, but you need to use # WTF::Bind or WTF::BindRepeating to create callbacks in Blink. + 'base::BarrierCallback', 'base::BarrierClosure', 'base::NullCallback', 'base::OnceCallback',
diff --git a/third_party/blink/web_tests/MSANExpectations b/third_party/blink/web_tests/MSANExpectations index 1aba6419..c5cd621 100644 --- a/third_party/blink/web_tests/MSANExpectations +++ b/third_party/blink/web_tests/MSANExpectations
@@ -113,3 +113,5 @@ crbug.com/1419916 [ Linux ] virtual/oopr-canvas2d/fast/canvas/canvas-fillPath-shadow.html [ Crash ] crbug.com/1419916 [ Linux ] virtual/oopr-canvas2d/fast/canvas/canvas-fillPath-alpha-shadow.html [ Crash ] crbug.com/1419916 [ Linux ] virtual/oopr-canvas2d/fast/canvas/canvas-fillPath-gradient-shadow.html [ Crash ] +crbug.com/1441427 [ Linux ] virtual/oopr-canvas2d/fast/canvas/OffscreenCanvas-clearRect-overdraw.html [ Timeout ] +crbug.com/1441427 [ Linux ] virtual/gpu/fast/canvas/OffscreenCanvas-clearRect-overdraw.html [ Timeout ]
diff --git a/third_party/blink/web_tests/TestExpectations b/third_party/blink/web_tests/TestExpectations index e67d078..b7e13ad 100644 --- a/third_party/blink/web_tests/TestExpectations +++ b/third_party/blink/web_tests/TestExpectations
@@ -543,8 +543,6 @@ crbug.com/915926 fast/events/touch/multi-touch-user-gesture.html [ Failure Pass ] -crbug.com/1303091 [ Linux ] compositing/overflow/paint-neg-z-order-descendants-into-scrolling-contents-layer.html [ Failure Pass ] - # New OffscreenCanvas Tests that are breaking LayoutTest crbug.com/980969 http/tests/input/discard-events-to-unstable-iframe.html [ Failure Pass ] @@ -5191,7 +5189,6 @@ crbug.com/1249176 [ Mac12-arm64 ] css3/blending/svg-blend-multiply.html [ Failure ] crbug.com/1249176 [ Mac13-arm64 ] css3/blending/svg-blend-multiply.html [ Failure ] crbug.com/1249176 [ Mac12-arm64 ] external/wpt/html/canvas/element/manual/drawing-images-to-the-canvas/image-orientation/drawImage-from-blob.tentative.html [ Failure ] -crbug.com/1249176 [ Mac11-arm64 ] external/wpt/largest-contentful-paint/image-src-change.html [ Failure ] crbug.com/1249176 [ Mac11-arm64 ] http/tests/images/document-policy-oversized-images-forced-layout.php [ Failure ] crbug.com/1249176 [ Mac11-arm64 ] virtual/threaded/http/tests/devtools/tracing/timeline-paint/paint-profiler-update.js [ Failure ] crbug.com/1249176 [ Mac12-arm64 ] virtual/threaded/http/tests/devtools/tracing/timeline-paint/paint-profiler-update.js [ Failure Pass ] @@ -6018,6 +6015,7 @@ crbug.com/1434123 media/video-source-type.html [ Failure Pass ] crbug.com/1434123 media/video-source-type-params.html [ Failure Pass ] crbug.com/1266821 [ Mac10.14 ] compositing/reflections/reflection-in-composited.html [ Timeout ] +crbug.com/1418393 [ Debug Linux ] external/wpt/performance-timeline/not-restored-reasons/performance-navigation-timing-attributes.tentative.window.html [ Failure ] # Suppress http/tests/inspector-protocol/network/navigate-iframe-in2out.js test cluster crbug.com/1395412 [ Mac ] virtual/partitioned-cookies/http/tests/inspector-protocol/network/navigate-iframe-in2out.js [ Failure ]
diff --git a/third_party/blink/web_tests/compositing/overflow/paint-neg-z-order-descendants-into-scrolling-contents-layer.html b/third_party/blink/web_tests/compositing/overflow/paint-neg-z-order-descendants-into-scrolling-contents-layer.html index 34a21ef..5a06903 100644 --- a/third_party/blink/web_tests/compositing/overflow/paint-neg-z-order-descendants-into-scrolling-contents-layer.html +++ b/third_party/blink/web_tests/compositing/overflow/paint-neg-z-order-descendants-into-scrolling-contents-layer.html
@@ -38,7 +38,6 @@ function doTest() { var textarea = document.getElementById('container'); - textarea.focus(); textarea.selectionStart = textarea.selectionEnd = 0; runAfterLayoutAndPaint(endTest); }
diff --git a/third_party/blink/web_tests/editing/selection/select_all/select_all_contenteditable_empty_string.html b/third_party/blink/web_tests/editing/selection/select_all/select_all_contenteditable_empty_string.html new file mode 100644 index 0000000..7a5381d1 --- /dev/null +++ b/third_party/blink/web_tests/editing/selection/select_all/select_all_contenteditable_empty_string.html
@@ -0,0 +1,12 @@ +<!doctype html> +<script src="../../../resources/testharness.js"></script> +<script src="../../../resources/testharnessreport.js"></script> +<div id="div" contenteditable="true"></div> +<script> +test(function() { + var div = document.getElementById('div'); + div.appendChild(document.createTextNode('')); + div.focus(); + assert_false(document.queryCommandEnabled('SelectAll')); +}, 'SelectAll is not enabled if the contenteditable contains only empty string'); +</script>
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 ed56e70..b0c9a09 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
@@ -138488,7 +138488,7 @@ ] ], "image-set-type-first-match-rendering.html": [ - "7e6ea8fa1f785ccde919b85ce2922c78c886acbe", + "eafe5bfb2cc80f18174f4a9f4f2a08963cc95e5d", [ null, [ @@ -272102,16 +272102,6 @@ } }, "support": { - ".cache": { - "gitignore2.json": [ - "77cc0f9907dfbb638badda5f1d0a42e864a96985", - [] - ], - "mtime.json": [ - "870fae931b1edc95a2627598516c6ca556f65df5", - [] - ] - }, ".gitignore": [ "d93e645d547894b50149d3726de2654957b6e06f", [] @@ -356989,11 +356979,11 @@ }, "resources": { "reporting-common.js": [ - "19f6410cbf809eefe299b08e73356d8443c04049", + "70bb4897f5082d84bd26f618dd8212d8f17e0862", [] ], "test-access-property.js": [ - "fe01e9128c51bd0ee65ba212967dcc989ac1bf1e", + "a405202431e6f06c998a6316a6b2c2d613ebfe8c", [] ], "try-access.js": [ @@ -357070,6 +357060,14 @@ "b3c24c3f82d2dbf07eefa9fa2e88fcf3817473d2", [] ], + "access-reporting-openee-rp-ro.https-expected.txt": [ + "0d4d312cf505711ee11be920b0bb9d3b965f04c9", + [] + ], + "access-reporting-opener-rp-ro.https-expected.txt": [ + "da251b50de98778e4326efa63eedd702d47d0774", + [] + ], "coop-rp-in-navigation-chain.https.html.headers": [ "073ce7adfbd81cb7c0b2f91f96c8349b6677f26c", [] @@ -357233,6 +357231,38 @@ "popup-with-same-site.https.html.ini": [ "05d2d2984d8a6e34589a66c6dfc67391763fdead", [] + ], + "reporting-from-rp-ro.https-expected.txt": [ + "ea3108eb21ec47915e61e5d4b61c42d46a37754a", + [] + ], + "reporting-from-rp-ro.https.html.sub.headers": [ + "424ad3e8de0297a2e66dd53914f0e5faa8651bff", + [] + ], + "reporting-from-rp.https-expected.txt": [ + "840f72a3863b12bd0de8ac511cb5b050d4cce94e", + [] + ], + "reporting-from-rp.https.html.sub.headers": [ + "6339ea34c7045eabe7457cf0c170edd35ea2ba76", + [] + ], + "reporting-to-rp-ro.https-expected.txt": [ + "6022ac8fc7fb2591a889c9addee99de46885e32b", + [] + ], + "reporting-to-rp-ro.https.html.headers": [ + "16903320bb50789e0a64f9620540f1cc8c0902fd", + [] + ], + "reporting-to-rp.https-expected.txt": [ + "6d598760c826b564a96fcff06b344d0b02b4c2ce", + [] + ], + "reporting-to-rp.https.html.headers": [ + "16903320bb50789e0a64f9620540f1cc8c0902fd", + [] ] } } @@ -471059,6 +471089,13 @@ {} ] ], + "offset-path-interpolation-006.html": [ + "a19908e4fffc2383a940e04ef0c00c486085cfee", + [ + null, + {} + ] + ], "offset-position-composition.html": [ "0ee517a73a8e9e673a83a0f81bbdea98d6a3d808", [ @@ -540409,6 +540446,36 @@ ] } ] + ], + "websocket.https.window.js": [ + "7d0dd95d84b7a9e16bf3e27e9d23627f4d3adffa", + [ + "html/cross-origin-embedder-policy/credentialless/websocket.https.window.html", + { + "script_metadata": [ + [ + "TIMEOUT", + "long" + ], + [ + "script", + "/common/get-host-info.sub.js" + ], + [ + "script", + "/common/utils.js" + ], + [ + "script", + "/common/dispatcher/dispatcher.js" + ], + [ + "script", + "./resources/common.js" + ] + ] + } + ] ] }, "cross-origin-isolated-permission-iframe.https.window.js": [ @@ -542186,6 +542253,38 @@ ], "tentative": { "restrict-properties": { + "access-reporting-closed.https.html": [ + "1c315b35d7fa81188aabf59c1c3196a5d5d2a2ea", + [ + null, + {} + ] + ], + "access-reporting-openee-rp-ro.https.html": [ + "7a96f4f5762721378036b47d248c3ae1ef21dd2f", + [ + null, + { + "timeout": "long" + } + ] + ], + "access-reporting-opener-rp-ro.https.html": [ + "9e1e85b16a5876c3e78656b8300c2fcc9e3e3ab1", + [ + null, + { + "timeout": "long" + } + ] + ], + "access-reporting-post-message.https.html": [ + "4c8e96f57933f74d0ff3f76cafe498c20bef7353", + [ + null, + {} + ] + ], "coop-rp-in-navigation-chain.https.html": [ "e5c877517488f755e08f69233439a817dd444164", [ @@ -542418,6 +542517,51 @@ "timeout": "long" } ] + ], + "reporting-bcg-reuse.https.html": [ + "8428d0cf60ae1c5f4f002cee4ad5108c69875d53", + [ + null, + { + "timeout": "long" + } + ] + ], + "reporting-from-rp-ro.https.html": [ + "60322bffe7a1c7d8d536b35504e925b09ff0c6bd", + [ + null, + { + "timeout": "long" + } + ] + ], + "reporting-from-rp.https.html": [ + "5deb115d94ef2894e6551ca89f8d4966d2d438df", + [ + null, + { + "timeout": "long" + } + ] + ], + "reporting-to-rp-ro.https.html": [ + "cf1385e766374d7fafae07eed9a857d8b9c381a3", + [ + null, + { + "timeout": "long" + } + ] + ], + "reporting-to-rp.https.html": [ + "9ff374c1c787348115e5d10d624be64ea4040323", + [ + null, + { + "timeout": "long" + } + ] ] } }
diff --git a/third_party/blink/web_tests/external/wpt/css/css-color/parsing/color-valid-system-color-expected.txt b/third_party/blink/web_tests/external/wpt/css/css-color/parsing/color-valid-system-color-expected.txt deleted file mode 100644 index 0ab1033..0000000 --- a/third_party/blink/web_tests/external/wpt/css/css-color/parsing/color-valid-system-color-expected.txt +++ /dev/null
@@ -1,22 +0,0 @@ -This is a testharness.js-based test. -PASS e.style['color'] = "ActiveText" should set the property value -PASS e.style['color'] = "ButtonBorder" should set the property value -PASS e.style['color'] = "ButtonFace" should set the property value -PASS e.style['color'] = "ButtonText" should set the property value -PASS e.style['color'] = "Canvas" should set the property value -PASS e.style['color'] = "CanvasText" should set the property value -PASS e.style['color'] = "Field" should set the property value -PASS e.style['color'] = "FieldText" should set the property value -PASS e.style['color'] = "GrayText" should set the property value -PASS e.style['color'] = "Highlight" should set the property value -PASS e.style['color'] = "HighlightText" should set the property value -PASS e.style['color'] = "LinkText" should set the property value -PASS e.style['color'] = "Mark" should set the property value -PASS e.style['color'] = "MarkText" should set the property value -PASS e.style['color'] = "VisitedText" should set the property value -PASS e.style['color'] = "SelectedItem" should set the property value -PASS e.style['color'] = "SelectedItemText" should set the property value -FAIL e.style['color'] = "AccentColor" should set the property value assert_not_equals: property should be set got disallowed value "" -FAIL e.style['color'] = "AccentColorText" should set the property value assert_not_equals: property should be set got disallowed value "" -Harness: the test ran to completion. -
diff --git a/third_party/blink/web_tests/external/wpt/css/css-view-transitions/exit-transition-with-anonymous-layout-object-ref.html b/third_party/blink/web_tests/external/wpt/css/css-view-transitions/exit-transition-with-anonymous-layout-object-ref.html new file mode 100644 index 0000000..10e04ac5 --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/css/css-view-transitions/exit-transition-with-anonymous-layout-object-ref.html
@@ -0,0 +1,20 @@ +<!DOCTYPE html> +<html> +<title>View transitions: exit transition with layout objects that don't have a node (ref)</title> +<link rel="help" href="https://drafts.csswg.org/css-view-transitions-1/"> +<link rel="author" href="mailto:khushalsagar@chromium.org"> + +<style> +body { + width: 100vw; + height: 100vh; + background: pink; +} + +#target { + width: 100px; + height: 100px; + background: blue; +} +</style> +<div id="target"></div>
diff --git a/third_party/blink/web_tests/external/wpt/css/css-view-transitions/exit-transition-with-anonymous-layout-object.html b/third_party/blink/web_tests/external/wpt/css/css-view-transitions/exit-transition-with-anonymous-layout-object.html new file mode 100644 index 0000000..ea2d17b --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/css/css-view-transitions/exit-transition-with-anonymous-layout-object.html
@@ -0,0 +1,64 @@ +<!DOCTYPE html> +<html class=reftest-wait> +<title>View transitions: exit transition with layout objects that don't have a node</title> +<link rel="help" href="https://drafts.csswg.org/css-view-transitions-1/"> +<link rel="author" href="mailto:khushalsagar@chromium.org"> +<link rel="match" href="exit-transition-with-anonymous-layout-object-ref.html"> + +<script src="/common/reftest-wait.js"></script> +<style> +body { + width: 100vw; + height: 100vh; +} + +#target { + width: 100px; + height: 100px; + background: blue; + view-transition-name: target; +} + +#hidden { + width: 10px; + height: 10px; + background: grey; + view-transition-name: hidden; +} + +fieldset { + width: 100px; + height: 100px; + background: lightgreen; + overflow: clip; +} + +html::view-transition { background: pink; } +html::view-transition-group(root) { visibility: hidden; } +html::view-transition-group(hidden) { animation-duration: 300s; } +html::view-transition-image-pair(hidden) { animation: unset; opacity: 0; } +html::view-transition-old(target) { + animation: unset; + opacity: 1; +} +</style> +<div id="target"></div> +<fieldset id="anonymous">hi</fieldset> +<div id=hidden class=hidden></div> + +<script> +failIfNot(document.startViewTransition, "Missing document.startViewTransition"); + +async function runTest() { + let t = document.startViewTransition(() => { + target.style.viewTransitionName = "none"; + }); + await t.ready; + anonymous.style.position = "relative"; + requestAnimationFrame(() => requestAnimationFrame(() => + requestAnimationFrame(() => requestAnimationFrame(takeScreenshot)) + )); +} +onload = () => requestAnimationFrame(() => requestAnimationFrame(runTest)); +</script> +
diff --git a/third_party/blink/web_tests/external/wpt/html/cross-origin-embedder-policy/credentialless/websocket.https.window.js b/third_party/blink/web_tests/external/wpt/html/cross-origin-embedder-policy/credentialless/websocket.https.window.js new file mode 100644 index 0000000..7d0dd95d --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/html/cross-origin-embedder-policy/credentialless/websocket.https.window.js
@@ -0,0 +1,77 @@ +// META: TIMEOUT=long +// META: script=/common/get-host-info.sub.js +// META: script=/common/utils.js +// META: script=/common/dispatcher/dispatcher.js +// META: script=./resources/common.js + +promise_test_parallel(async test => { + const same_origin = get_host_info().HTTPS_ORIGIN; + const cross_origin = get_host_info().HTTPS_REMOTE_ORIGIN; + const cookie_key = "coep_credentialless_websocket"; + const cookie_same_origin = "same_origin"; + const cookie_cross_origin = "cross_origin"; + + await Promise.all([ + setCookie(same_origin, cookie_key, cookie_same_origin + + cookie_same_site_none), + setCookie(cross_origin, cookie_key, cookie_cross_origin + + cookie_same_site_none), + ]); + + // One window with COEP:none. (control) + const w_control_token = token(); + const w_control_url = same_origin + executor_path + + coep_none + `&uuid=${w_control_token}` + const w_control = window.open(w_control_url); + add_completion_callback(() => w_control.close()); + + // One window with COEP:credentialless. (experiment) + const w_credentialless_token = token(); + const w_credentialless_url = same_origin + executor_path + + coep_credentialless + `&uuid=${w_credentialless_token}`; + const w_credentialless = window.open(w_credentialless_url); + add_completion_callback(() => w_credentialless.close()); + + let WebSocketTest = function( + description, origin, + expected_cookies_control, + expected_cookies_credentialless) + { + promise_test_parallel(async test => { + const token_1 = token(); + const token_2 = token(); + + const origin_for_websocket = origin.replace("https", "wss"); + + send(w_control_token, ` + var ws = new WebSocket("${showRequestHeaders(origin_for_websocket, token_1)}"); + `); + + send(w_credentialless_token, ` + var ws = new WebSocket("${showRequestHeaders(origin_for_websocket, token_2)}"); + `); + + const headers_control = JSON.parse(await receive(token_1)); + const headers_credentialless = JSON.parse(await receive(token_2)); + + assert_equals(parseCookies(headers_control)[cookie_key], + expected_cookies_control, + "coep:none => "); + assert_equals(parseCookies(headers_credentialless)[cookie_key], + expected_cookies_credentialless, + "coep:credentialless => "); + }, `WebSocket ${description}`) + }; + + // Same-origin request always contains Cookies: + WebSocketTest("same-origin", + same_origin, + cookie_same_origin, + cookie_same_origin); + + // Cross-origin request also always contains Cookies: + WebSocketTest("cross-origin", + cross_origin, + cookie_cross_origin, + cookie_cross_origin); +}, "Main");
diff --git a/third_party/blink/web_tests/external/wpt/html/semantics/popovers/popover-focus-child-dialog.html b/third_party/blink/web_tests/external/wpt/html/semantics/popovers/popover-focus-child-dialog.html deleted file mode 100644 index 051eef1..0000000 --- a/third_party/blink/web_tests/external/wpt/html/semantics/popovers/popover-focus-child-dialog.html +++ /dev/null
@@ -1,45 +0,0 @@ -<!DOCTYPE html> -<link rel=author href="mailto:jarhar@chromium.org"> -<link rel=help href="https://chromium-review.googlesource.com/c/chromium/src/+/4021969"> -<script src="/resources/testharness.js"></script> -<script src="/resources/testharnessreport.js"></script> - -<div id=popover1 popover> - <dialog id=childdialog autofocus> - <button autofocus>hello world</button> - </dialog> -</div> - -<div id=popover2 popover=manual> - <div id=childpopover popover=manual autofocus> - <button autofocus>hello world</button> - </div> -</div> - -<script> -test(t => { - t.add_cleanup(() => childdialog.close()); - t.add_cleanup(() => popover1.hidePopover()); - - childdialog.showModal(); - document.activeElement.blur(); - popover1.showPopover(); - - assert_true(popover1.matches(':popover-open'), 'The popover should be open.'); - assert_true(childdialog.hasAttribute('open'), 'The dialog should be open.'); - assert_equals(document.activeElement, document.body, 'Nothing should have gotten focused.'); -}, 'Popovers should not initially focus child dialog elements.'); - -test(t => { - t.add_cleanup(() => childpopover.hidePopover()); - t.add_cleanup(() => popover2.hidePopover()); - - childpopover.showPopover(); - document.activeElement.blur(); - popover2.showPopover(); - - assert_true(popover2.matches(':popover-open'), 'The parent popover should be open.'); - assert_true(childpopover.matches(':popover-open'), 'The child popover should be open.'); - assert_equals(document.activeElement, document.body, 'Nothing should have gotten focused.'); -}, 'Popovers should not initially focus child popover elements.'); -</script>
diff --git a/third_party/omnibox_proto/README.chromium b/third_party/omnibox_proto/README.chromium index dd5fccb..062295d0 100644 --- a/third_party/omnibox_proto/README.chromium +++ b/third_party/omnibox_proto/README.chromium
@@ -1,8 +1,8 @@ Name: Omnibox Protos Short Name: omnibox_proto URL: This is the canonical public repository -Version: 528512105 -Date: 2023/05/01 UTC +Version: 531232084 +Date: 2023/05/11 UTC License: BSD Security Critical: Yes
diff --git a/third_party/omnibox_proto/types.proto b/third_party/omnibox_proto/types.proto index 95b54df..ae15ccb 100644 --- a/third_party/omnibox_proto/types.proto +++ b/third_party/omnibox_proto/types.proto
@@ -20,7 +20,9 @@ TYPE_PROFILE = 44; TYPE_ENTITY = 46; TYPE_NATIVE_CHROME = 69; + TYPE_PERSONALIZED_NAVIGATION = 83; TYPE_CHROME_QUERY_TILES = 171; + TYPE_CATEGORICAL_QUERY = 185; } // Suggestion subtypes supported by the Chrome Omnibox.
diff --git a/third_party/webgpu-cts/ts_sources.txt b/third_party/webgpu-cts/ts_sources.txt index fdbd4aa..fdf8209 100644 --- a/third_party/webgpu-cts/ts_sources.txt +++ b/third_party/webgpu-cts/ts_sources.txt
@@ -62,14 +62,15 @@ src/demo/file_depth_2/in_single_child_dir/r.spec.ts src/stress/listing.ts src/webgpu/constants.ts +src/webgpu/capability_info.ts +src/stress/adapter/device_allocation.spec.ts src/webgpu/util/constants.ts src/webgpu/util/conversion.ts src/webgpu/util/math.ts src/webgpu/util/unions.ts src/webgpu/util/texture/base.ts src/webgpu/util/texture/layout.ts -src/webgpu/capability_info.ts -src/stress/adapter/device_allocation.spec.ts +src/webgpu/format_info.ts src/webgpu/util/buffer.ts src/webgpu/util/pretty_diff_tables.ts src/webgpu/util/check_contents.ts
diff --git a/tools/binary_size/libsupersize/apk.py b/tools/binary_size/libsupersize/apk.py index 4a13c4c..a36496b 100644 --- a/tools/binary_size/libsupersize/apk.py +++ b/tools/binary_size/libsupersize/apk.py
@@ -132,7 +132,8 @@ raw_symbols.append(placeholder_sym) if isinstance(chunk, arsc_parser.ArscResTableTypeSpec): - metrics['COUNT/' + chunk.type_str] = chunk.entry_count + metrics[f'{models.METRICS_COUNT}/{chunk.type_str}'] = ( + chunk.entry_count) overhead -= chunk.size if overhead > 0:
diff --git a/tools/binary_size/libsupersize/apkanalyzer.py b/tools/binary_size/libsupersize/apkanalyzer.py index d07657f..61d368c 100644 --- a/tools/binary_size/libsupersize/apkanalyzer.py +++ b/tools/binary_size/libsupersize/apkanalyzer.py
@@ -607,6 +607,6 @@ map_item_sizes = dexfile.ComputeMapItemSizes() metrics = {} for item in map_item_sizes: - metrics['SIZE/' + item['name']] = item['byte_size'] - metrics['COUNT/' + item['name']] = item['size'] + metrics[f'{models.METRICS_SIZE}/' + item['name']] = item['byte_size'] + metrics[f'{models.METRICS_COUNT}/' + item['name']] = item['size'] return section_ranges, dex_other_symbols, {dex_path: metrics}
diff --git a/tools/binary_size/libsupersize/models.py b/tools/binary_size/libsupersize/models.py index 847f68ed..0119c35 100644 --- a/tools/binary_size/libsupersize/models.py +++ b/tools/binary_size/libsupersize/models.py
@@ -21,6 +21,10 @@ BUILD_CONFIG_URL = 'url' BUILD_CONFIG_OUT_DIRECTORY = 'out_directory' +METRICS_COUNT = 'COUNT' +METRICS_COUNT_RELOCATIONS = 'Relocations' +METRICS_SIZE = 'SIZE' + METADATA_APK_FILENAME = 'apk_file_name' # Path relative to output_directory. METADATA_APK_SIZE = 'apk_size' # File size of apk in bytes. METADATA_APK_SPLIT_NAME = 'apk_split_name' # Name of the split if applicable. @@ -33,7 +37,6 @@ METADATA_ELF_FILENAME = 'elf_file_name' # Path relative to output_directory. METADATA_ELF_MTIME = 'elf_mtime' # int timestamp in utc. METADATA_ELF_BUILD_ID = 'elf_build_id' -METADATA_ELF_RELOCATIONS_COUNT = 'elf_relocations_count' METADATA_PROGUARD_MAPPING_FILENAME = 'proguard_mapping_file_name' # New sections should also be added to the SuperSize UI.
diff --git a/tools/binary_size/libsupersize/native.py b/tools/binary_size/libsupersize/native.py index 9ff2f25..ddf9fac 100644 --- a/tools/binary_size/libsupersize/native.py +++ b/tools/binary_size/libsupersize/native.py
@@ -695,9 +695,6 @@ timestamp = calendar.timegm(timestamp_obj.timetuple()) native_metadata[models.METADATA_ELF_MTIME] = timestamp - relocations_count = _CountRelocationsFromElf(native_spec.elf_path) - native_metadata[models.METADATA_ELF_RELOCATIONS_COUNT] = relocations_count - if native_spec.map_path: native_metadata[models.METADATA_MAP_FILENAME] = shorten_path( native_spec.map_path) @@ -807,10 +804,15 @@ if elf_info: section_ranges = elf_info.section_ranges.copy() if native_spec.elf_path: - metrics_by_file[posixpath.basename(native_spec.elf_path)] = { - 'SIZE/' + k: size + key = posixpath.basename(native_spec.elf_path) + metrics_by_file[key] = { + f'{models.METRICS_SIZE}/{k}': size for (k, (offset, size)) in section_ranges.items() } + relocations_count = _CountRelocationsFromElf(native_spec.elf_path) + metrics_by_file[key][ + f'{models.METRICS_COUNT}/{models.METRICS_COUNT_RELOCATIONS}'] = ( + relocations_count) source_path = '' if native_spec.apk_so_path:
diff --git a/tools/binary_size/libsupersize/testdata/ArchiveContainers.golden b/tools/binary_size/libsupersize/testdata/ArchiveContainers.golden index ff7a1781..6efa8d0 100644 --- a/tools/binary_size/libsupersize/testdata/ArchiveContainers.golden +++ b/tools/binary_size/libsupersize/testdata/ArchiveContainers.golden
@@ -11,7 +11,6 @@ elf_build_id=WhatAnAmazingBuildId elf_file_name=elf elf_mtime={redacted} -elf_relocations_count=394087 map_file_name=../../../test.map Container2: elf_algorithm=linker_map @@ -19,7 +18,6 @@ elf_build_id=WhatAnAmazingBuildId elf_file_name=elf elf_mtime={redacted} -elf_relocations_count=394087 map_file_name=../../../test.map Container1:/smalltest.so (x86) apk_file_name=test.apk @@ -446,9 +444,9 @@ <Container1:>.other@0(size_without_padding=0,padding=818,full_name=Overhead: APK file,object_path=,source_path=,flags={},num_aliases=1,component=) MetricsByFile: Container1:/test.so (armeabi-v7a) -elf={'SIZE/.ARM.attributes': 60, 'SIZE/.ARM.exidx': 1536456, 'SIZE/.ARM.extab': 183632, 'SIZE/.bss': 1300456, 'SIZE/.data': 101768, 'SIZE/.data.rel.ro': 1065224, 'SIZE/.data.rel.ro.local': 790024, 'SIZE/.dynamic': 304, 'SIZE/.dynstr': 4025, 'SIZE/.dynsym': 6496, 'SIZE/.fini_array': 8, 'SIZE/.gnu.version': 812, 'SIZE/.gnu.version_d': 28, 'SIZE/.gnu.version_r': 96, 'SIZE/.got': 42956, 'SIZE/.hash': 2684, 'SIZE/.init_array': 8, 'SIZE/.interp': 19, 'SIZE/.note.gnu.build-id': 36, 'SIZE/.note.gnu.gold-version': 28, 'SIZE/.plt': 4244, 'SIZE/.rel.dyn': 2655384, 'SIZE/.rel.plt': 2816, 'SIZE/.rodata': 5927652, 'SIZE/.shstrtab': 436, 'SIZE/.strtab': 34841854, 'SIZE/.symtab': 17166112, 'SIZE/.text': 35982248} +elf={'COUNT/Relocations': 394087, 'SIZE/.ARM.attributes': 60, 'SIZE/.ARM.exidx': 1536456, 'SIZE/.ARM.extab': 183632, 'SIZE/.bss': 1300456, 'SIZE/.data': 101768, 'SIZE/.data.rel.ro': 1065224, 'SIZE/.data.rel.ro.local': 790024, 'SIZE/.dynamic': 304, 'SIZE/.dynstr': 4025, 'SIZE/.dynsym': 6496, 'SIZE/.fini_array': 8, 'SIZE/.gnu.version': 812, 'SIZE/.gnu.version_d': 28, 'SIZE/.gnu.version_r': 96, 'SIZE/.got': 42956, 'SIZE/.hash': 2684, 'SIZE/.init_array': 8, 'SIZE/.interp': 19, 'SIZE/.note.gnu.build-id': 36, 'SIZE/.note.gnu.gold-version': 28, 'SIZE/.plt': 4244, 'SIZE/.rel.dyn': 2655384, 'SIZE/.rel.plt': 2816, 'SIZE/.rodata': 5927652, 'SIZE/.shstrtab': 436, 'SIZE/.strtab': 34841854, 'SIZE/.symtab': 17166112, 'SIZE/.text': 35982248} Container2: -elf={'SIZE/.ARM.attributes': 60, 'SIZE/.ARM.exidx': 1536456, 'SIZE/.ARM.extab': 183632, 'SIZE/.bss': 1300456, 'SIZE/.data': 101768, 'SIZE/.data.rel.ro': 1065224, 'SIZE/.data.rel.ro.local': 790024, 'SIZE/.dynamic': 304, 'SIZE/.dynstr': 4025, 'SIZE/.dynsym': 6496, 'SIZE/.fini_array': 8, 'SIZE/.gnu.version': 812, 'SIZE/.gnu.version_d': 28, 'SIZE/.gnu.version_r': 96, 'SIZE/.got': 42956, 'SIZE/.hash': 2684, 'SIZE/.init_array': 8, 'SIZE/.interp': 19, 'SIZE/.note.gnu.build-id': 36, 'SIZE/.note.gnu.gold-version': 28, 'SIZE/.plt': 4244, 'SIZE/.rel.dyn': 2655384, 'SIZE/.rel.plt': 2816, 'SIZE/.rodata': 5927652, 'SIZE/.shstrtab': 436, 'SIZE/.strtab': 34841854, 'SIZE/.symtab': 17166112, 'SIZE/.text': 35982248} +elf={'COUNT/Relocations': 394087, 'SIZE/.ARM.attributes': 60, 'SIZE/.ARM.exidx': 1536456, 'SIZE/.ARM.extab': 183632, 'SIZE/.bss': 1300456, 'SIZE/.data': 101768, 'SIZE/.data.rel.ro': 1065224, 'SIZE/.data.rel.ro.local': 790024, 'SIZE/.dynamic': 304, 'SIZE/.dynstr': 4025, 'SIZE/.dynsym': 6496, 'SIZE/.fini_array': 8, 'SIZE/.gnu.version': 812, 'SIZE/.gnu.version_d': 28, 'SIZE/.gnu.version_r': 96, 'SIZE/.got': 42956, 'SIZE/.hash': 2684, 'SIZE/.init_array': 8, 'SIZE/.interp': 19, 'SIZE/.note.gnu.build-id': 36, 'SIZE/.note.gnu.gold-version': 28, 'SIZE/.plt': 4244, 'SIZE/.rel.dyn': 2655384, 'SIZE/.rel.plt': 2816, 'SIZE/.rodata': 5927652, 'SIZE/.shstrtab': 436, 'SIZE/.strtab': 34841854, 'SIZE/.symtab': 17166112, 'SIZE/.text': 35982248} Container1:/smalltest.so (x86) Container1: classes.dex={'COUNT/ANNOTATION': 1, 'COUNT/ANNOTATIONS_DIRECTORY': 1, 'COUNT/ANNOTATION_SET': 2, 'COUNT/CLASS_DATA': 2, 'COUNT/CLASS_DEF': 2, 'COUNT/CODE': 8, 'COUNT/DEBUG_INFO': 8, 'COUNT/ENCODED_ARRAY': 1, 'COUNT/FIELD_ID': 2, 'COUNT/HEADER': 1, 'COUNT/MAP': 1, 'COUNT/METHOD_ID': 14, 'COUNT/PROTO_ID': 10, 'COUNT/STRING_DATA': 40, 'COUNT/STRING_ID': 40, 'COUNT/TYPE': 6, 'COUNT/TYPE_ID': 13, 'SIZE/ANNOTATION': 8, 'SIZE/ANNOTATIONS_DIRECTORY': 24, 'SIZE/ANNOTATION_SET': 12, 'SIZE/CLASS_DATA': 48, 'SIZE/CLASS_DEF': 64, 'SIZE/CODE': 432, 'SIZE/DEBUG_INFO': 72, 'SIZE/ENCODED_ARRAY': 4, 'SIZE/FIELD_ID': 16, 'SIZE/HEADER': 112, 'SIZE/MAP': 208, 'SIZE/METHOD_ID': 112, 'SIZE/PROTO_ID': 120, 'SIZE/STRING_DATA': 522, 'SIZE/STRING_ID': 160, 'SIZE/TYPE': 50, 'SIZE/TYPE_ID': 52}
diff --git a/tools/binary_size/libsupersize/testdata/Archive_Apk.golden b/tools/binary_size/libsupersize/testdata/Archive_Apk.golden index 7078a12..78d2c8be 100644 --- a/tools/binary_size/libsupersize/testdata/Archive_Apk.golden +++ b/tools/binary_size/libsupersize/testdata/Archive_Apk.golden
@@ -8,7 +8,6 @@ elf_build_id=WhatAnAmazingBuildId elf_file_name=elf elf_mtime={redacted} -elf_relocations_count=394087 map_file_name=../../../test.map apk_file_name=test.apk elf_algorithm=sections
diff --git a/tools/binary_size/libsupersize/testdata/Archive_Elf.golden b/tools/binary_size/libsupersize/testdata/Archive_Elf.golden index 340d44d..b66bcde 100644 --- a/tools/binary_size/libsupersize/testdata/Archive_Elf.golden +++ b/tools/binary_size/libsupersize/testdata/Archive_Elf.golden
@@ -3,7 +3,6 @@ elf_build_id=WhatAnAmazingBuildId elf_file_name=elf elf_mtime={redacted} -elf_relocations_count=394087 git_revision=abc123 gn_args=var1=true var2="foo" map_file_name=../../../test.map
diff --git a/tools/binary_size/libsupersize/testdata/Archive_Elf_No_Map.golden b/tools/binary_size/libsupersize/testdata/Archive_Elf_No_Map.golden index c7d973a..e1e7aa2 100644 --- a/tools/binary_size/libsupersize/testdata/Archive_Elf_No_Map.golden +++ b/tools/binary_size/libsupersize/testdata/Archive_Elf_No_Map.golden
@@ -3,7 +3,6 @@ elf_build_id=WhatAnAmazingBuildId elf_file_name=elf elf_mtime={redacted} -elf_relocations_count=394087 git_revision=abc123 gn_args=var1=true var2="foo" out_directory=out/Release
diff --git a/tools/binary_size/libsupersize/testdata/Archive_MinimalApks.golden b/tools/binary_size/libsupersize/testdata/Archive_MinimalApks.golden index 041fd977..b0b476f 100644 --- a/tools/binary_size/libsupersize/testdata/Archive_MinimalApks.golden +++ b/tools/binary_size/libsupersize/testdata/Archive_MinimalApks.golden
@@ -9,7 +9,6 @@ elf_build_id=WhatAnAmazingBuildId elf_file_name=elf elf_mtime={redacted} -elf_relocations_count=394087 map_file_name=../../../test.map apk_file_name=Bundle.minimal.apks apk_split_name=base
diff --git a/tools/binary_size/libsupersize/testdata/Archive_Pak_Files.golden b/tools/binary_size/libsupersize/testdata/Archive_Pak_Files.golden index 8af2c6f8f..333c73a 100644 --- a/tools/binary_size/libsupersize/testdata/Archive_Pak_Files.golden +++ b/tools/binary_size/libsupersize/testdata/Archive_Pak_Files.golden
@@ -3,7 +3,6 @@ elf_build_id=WhatAnAmazingBuildId elf_file_name=elf elf_mtime={redacted} -elf_relocations_count=394087 git_revision=abc123 gn_args=var1=true var2="foo" map_file_name=../../../test.map
diff --git a/tools/binary_size/libsupersize/testdata/Console.golden b/tools/binary_size/libsupersize/testdata/Console.golden index 3a1c94f..2c4f95e 100644 --- a/tools/binary_size/libsupersize/testdata/Console.golden +++ b/tools/binary_size/libsupersize/testdata/Console.golden
@@ -68,7 +68,6 @@ elf_build_id=WhatAnAmazingBuildId elf_file_name=elf elf_mtime={redacted} - elf_relocations_count=394087 git_revision=abc123 gn_args=var1=true var2="foo" map_file_name=../../../test.map
diff --git a/tools/binary_size/libsupersize/testdata/Diff_NullDiff.golden b/tools/binary_size/libsupersize/testdata/Diff_NullDiff.golden index 8306a05c..b098aa9 100644 --- a/tools/binary_size/libsupersize/testdata/Diff_NullDiff.golden +++ b/tools/binary_size/libsupersize/testdata/Diff_NullDiff.golden
@@ -4,7 +4,6 @@ elf_build_id=WhatAnAmazingBuildId elf_file_name=elf elf_mtime={redacted} - elf_relocations_count=394087 git_revision=abc123 gn_args=var1=true var2="foo" map_file_name=../../../test.map
diff --git a/tools/binary_size/libsupersize/testdata/FullDescription.golden b/tools/binary_size/libsupersize/testdata/FullDescription.golden index 00c23faa..ceac241f 100644 --- a/tools/binary_size/libsupersize/testdata/FullDescription.golden +++ b/tools/binary_size/libsupersize/testdata/FullDescription.golden
@@ -4,7 +4,6 @@ elf_build_id=WhatAnAmazingBuildId elf_file_name=elf elf_mtime={redacted} - elf_relocations_count=394087 git_revision=abc123 gn_args=var1=true var2="foo" map_file_name=../../../test.map
diff --git a/tools/cast3p/cast_core.version b/tools/cast3p/cast_core.version index f2492b6..9bcbf7f0 100644 --- a/tools/cast3p/cast_core.version +++ b/tools/cast3p/cast_core.version
@@ -1 +1 @@ -cast_20230306_0602_RC12 +cast_20230512_0201_RC00
diff --git a/tools/mb/mb_config.pyl b/tools/mb/mb_config.pyl index 2022f81..a791bf6 100644 --- a/tools/mb/mb_config.pyl +++ b/tools/mb/mb_config.pyl
@@ -1363,17 +1363,14 @@ 'win-swangle-try-x86': 'angle_deqp_release_trybot_x86_reclient', }, - # crbug.com/1417003: `-Werror` is removed for these to work around the - # existence of C++20-only code in Chromium, while we're forcing -std=c++17. - # Tons of build failures slow down these builders significantly. 'tryserver.chromium.tricium': { - 'android-clang-tidy-rel': 'android_release_trybot_reclient_cxx17_no_werror', - 'fuchsia-clang-tidy-rel': 'release_trybot_fuchsia_reclient_cxx17_no_werror', - 'linux-chromeos-clang-tidy-rel': 'chromeos_with_codecs_release_trybot_reclient_cxx17_no_werror', - 'linux-clang-tidy-rel': 'release_trybot_reclient_cxx17_no_werror', - 'linux-lacros-clang-tidy-rel': 'lacros_on_linux_release_trybot_reclient_cxx17_no_werror', - 'mac-clang-tidy-rel': 'release_trybot_reclient_cxx17_no_werror', - 'win10-clang-tidy-rel': 'release_trybot_reclient_cxx17_no_werror', + 'android-clang-tidy-rel': 'android_release_trybot_reclient', + 'fuchsia-clang-tidy-rel': 'release_trybot_fuchsia_reclient', + 'linux-chromeos-clang-tidy-rel': 'chromeos_with_codecs_release_trybot_reclient', + 'linux-clang-tidy-rel': 'release_trybot_reclient', + 'linux-lacros-clang-tidy-rel': 'lacros_on_linux_release_trybot_reclient', + 'mac-clang-tidy-rel': 'release_trybot_reclient', + 'win10-clang-tidy-rel': 'release_trybot_reclient', }, 'tryserver.chromium.updater': { @@ -1765,10 +1762,6 @@ 'android', 'release_trybot_reclient', 'strip_debug_info', ], - 'android_release_trybot_reclient_cxx17_no_werror': [ - 'android', 'release_trybot_reclient', 'strip_debug_info', 'force_cxx17', 'no_werror', - ], - 'android_release_trybot_x64_coverage_fastbuild_webview_trichrome_reclient': [ 'android', 'release_trybot_reclient', 'strip_debug_info', 'x64', 'android_fastbuild', 'use_java_coverage', 'partial_code_coverage_instrumentation', @@ -2345,8 +2338,8 @@ 'chromeos_with_codecs', 'release_trybot_reclient', 'no_symbols', 'invert_fieldtrials', ], - 'chromeos_with_codecs_release_trybot_reclient_cxx17_no_werror': [ - 'chromeos_with_codecs', 'release_trybot_reclient', 'no_symbols', 'force_cxx17', 'no_werror', + 'chromeos_with_codecs_release_trybot_reclient': [ + 'chromeos_with_codecs', 'release_trybot_reclient', 'no_symbols', ], 'chromeos_with_codecs_with_lacros_release_bot_reclient': [ @@ -3010,10 +3003,6 @@ 'lacros_on_linux_release_trybot_reclient', ], - 'lacros_on_linux_release_trybot_reclient_cxx17_no_werror': [ - 'lacros_on_linux_release_trybot_reclient', 'force_cxx17', 'no_werror', 'no_werror', - ], - 'lacros_on_linux_tot_debug': [ 'lacros_on_linux', 'debug', 'also_build_ash_chrome', 'clang_tot', ], @@ -3591,10 +3580,6 @@ 'release_trybot_reclient', 'fuchsia', ], - 'release_trybot_fuchsia_reclient_cxx17_no_werror': [ - 'release_trybot_reclient', 'fuchsia', 'force_cxx17', 'no_werror', - ], - 'release_trybot_minimal_symbols_reclient': [ 'release_trybot_minimal_symbols_reclient', ], @@ -3611,10 +3596,6 @@ 'release_trybot_reclient', ], - 'release_trybot_reclient_cxx17_no_werror': [ - 'release_trybot_reclient', 'force_cxx17', 'no_werror', - ], - 'release_trybot_reclient_x64': [ 'release_trybot_reclient', 'x64', ], @@ -4208,10 +4189,6 @@ 'gn_args': 'ffmpeg_branding="ChromeOS"', }, - 'force_cxx17': { - 'gn_args': 'use_cxx17=true', - }, - 'fuchsia': { 'gn_args': 'target_os="fuchsia"', }, @@ -4443,10 +4420,6 @@ 'gn_args': 'symbol_level=0', }, - 'no_werror': { - 'gn_args': 'treat_warnings_as_errors=false', - }, - 'no_widevine_cdm_host_verification': { 'gn_args': 'ignore_missing_widevine_signing_cert=true', },
diff --git a/tools/mb/mb_config_expectations/tryserver.chromium.tricium.json b/tools/mb/mb_config_expectations/tryserver.chromium.tricium.json index 98c62d3..4a4c95f 100644 --- a/tools/mb/mb_config_expectations/tryserver.chromium.tricium.json +++ b/tools/mb/mb_config_expectations/tryserver.chromium.tricium.json
@@ -10,8 +10,6 @@ "strip_debug_info": true, "symbol_level": 0, "target_os": "android", - "treat_warnings_as_errors": false, - "use_cxx17": true, "use_remoteexec": true } }, @@ -22,8 +20,6 @@ "is_debug": false, "symbol_level": 0, "target_os": "fuchsia", - "treat_warnings_as_errors": false, - "use_cxx17": true, "use_remoteexec": true } }, @@ -36,8 +32,6 @@ "proprietary_codecs": true, "symbol_level": 0, "target_os": "chromeos", - "treat_warnings_as_errors": false, - "use_cxx17": true, "use_remoteexec": true } }, @@ -47,8 +41,6 @@ "is_component_build": false, "is_debug": false, "symbol_level": 0, - "treat_warnings_as_errors": false, - "use_cxx17": true, "use_remoteexec": true } }, @@ -61,8 +53,6 @@ "is_debug": false, "symbol_level": 0, "target_os": "chromeos", - "treat_warnings_as_errors": false, - "use_cxx17": true, "use_remoteexec": true } }, @@ -72,8 +62,6 @@ "is_component_build": false, "is_debug": false, "symbol_level": 0, - "treat_warnings_as_errors": false, - "use_cxx17": true, "use_remoteexec": true } }, @@ -83,8 +71,6 @@ "is_component_build": false, "is_debug": false, "symbol_level": 0, - "treat_warnings_as_errors": false, - "use_cxx17": true, "use_remoteexec": true } }
diff --git a/tools/metrics/histograms/enums.xml b/tools/metrics/histograms/enums.xml index 711cb487..1aa0e1e 100644 --- a/tools/metrics/histograms/enums.xml +++ b/tools/metrics/histograms/enums.xml
@@ -42403,6 +42403,14 @@ <int value="4561" label="LinkRelPreloadAsFont"/> <int value="4562" label="CrossWindowAccessToBrowserGeneratedDocument"/> <int value="4563" label="SpeculationRulesNoVarySearchHint"/> + <int value="4564" label="FileSystemAccessMoveRename"/> + <int value="4565" label="FileSystemAccessMoveReparent"/> + <int value="4566" label="FileSystemAccessMoveReparentAndRename"/> + <int value="4567" label="V8FileSystemDirectoryHandle_RemoveEntry_Method"/> + <int value="4568" label="V8FileSystemFileHandle_CreateWritable_Method"/> + <int value="4569" label="V8FileSystemFileHandle_GetFile_Method"/> + <int value="4570" label="V8FileSystemHandle_GetUniqueId_Method"/> + <int value="4571" label="V8FileSystemHandle_Remove_Method"/> </enum> <enum name="FeaturePolicyAllowlistType"> @@ -64350,6 +64358,7 @@ <int value="996701528" label="SystemKeyboardLock:enabled"/> <int value="996987392" label="SearchNavigationPrefetch:disabled"/> <int value="998748600" label="SyncErrorInfoBarAndroid:disabled"/> + <int value="998857679" label="DiscardExceptionsImprovements:enabled"/> <int value="1000045846" label="OverlayNewLayout:disabled"/> <int value="1000587036" label="OfflinePagesDescriptiveFailStatus:disabled"/> <int value="1000630368" label="lacros-stability"/> @@ -64721,6 +64730,7 @@ <int value="1196670943" label="WebAuthFlowInBrowserTab:enabled"/> <int value="1196834473" label="disable-smart-virtual-keyboard"/> <int value="1197336536" label="printing-ppd-channel"/> + <int value="1198604672" label="DiscardExceptionsImprovements:disabled"/> <int value="1198839129" label="OfflinePagesLivePageSharing:enabled"/> <int value="1199276782" label="HighEfficiencyMultistateMode:enabled"/> <int value="1200407724" label="WebUITabStripContextMenuAfterTap:disabled"/>
diff --git a/tools/metrics/histograms/metadata/enterprise/histograms.xml b/tools/metrics/histograms/metadata/enterprise/histograms.xml index 60e76a2..b64d455 100644 --- a/tools/metrics/histograms/metadata/enterprise/histograms.xml +++ b/tools/metrics/histograms/metadata/enterprise/histograms.xml
@@ -2917,15 +2917,6 @@ </summary> </histogram> -<histogram name="EnterpriseCheck.NetGetJoinInformationAddress" - enum="BooleanEnabled" expires_after="2020-06-18"> - <owner>rogerta@chromium.org</owner> - <summary> - Whether we could obtain the address of the NetGetJoinInformation function. - This check is performed once at start-up on Windows. - </summary> -</histogram> - <histogram name="EnterpriseCheck.OSType" enum="OsSuite" expires_after="2024-01-10"> <owner>ydago@chromium.org</owner>
diff --git a/tools/metrics/histograms/metadata/ios/histograms.xml b/tools/metrics/histograms/metadata/ios/histograms.xml index 7f81b7b..eff7f318 100644 --- a/tools/metrics/histograms/metadata/ios/histograms.xml +++ b/tools/metrics/histograms/metadata/ios/histograms.xml
@@ -1129,6 +1129,18 @@ </summary> </histogram> +<histogram name="IOS.IsEnabled.Password.BottomSheet" enum="Boolean" + expires_after="2024-05-08"> + <owner>sugoi@chromium.org</owner> + <owner>veronguyen@google.com</owner> + <owner>tmartino@chromium.org</owner> + <summary> + At the moment of trying to enable the bottom sheet at page load time, track + whether the bottom sheet is enabled or whether it has been disabled due to + the number of dismisses. + </summary> +</histogram> + <histogram name="IOS.JavascriptContentBlockFailure" enum="IOSJavascriptContentBlockType" expires_after="2020-12-31"> <owner>rkgibson@google.com</owner> @@ -1963,6 +1975,17 @@ </summary> </histogram> +<histogram name="IOS.ResetDismissCount.Password.BottomSheet" units="dismisses" + expires_after="2024-05-08"> + <owner>sugoi@chromium.org</owner> + <owner>veronguyen@google.com</owner> + <owner>tmartino@chromium.org</owner> + <summary> + Tracks the number of times in a row the Password Bottom Sheet had been + dismissed at the moment the dismiss count was reset to 0 (between 1 and 3). + </summary> +</histogram> + <histogram name="IOS.RestoreNavigationItemCount" units="rank" expires_after="2023-09-12"> <owner>gambard@chromium.org</owner>
diff --git a/tools/perf/core/perfetto_binary_roller/binary_deps.json b/tools/perf/core/perfetto_binary_roller/binary_deps.json index cef10f8..154614e 100644 --- a/tools/perf/core/perfetto_binary_roller/binary_deps.json +++ b/tools/perf/core/perfetto_binary_roller/binary_deps.json
@@ -14,15 +14,15 @@ }, "mac": { "hash": "a30c7e0da4ee9a75bc53542310a26cfed58c0725", - "full_remote_path": "chromium-telemetry/perfetto_binaries/trace_processor_shell/mac/8636689446ccacc31a106573931c8bad825e9dc1/trace_processor_shell" + "full_remote_path": "chromium-telemetry/perfetto_binaries/trace_processor_shell/mac/edd765afa06f3b0c0d117e9e1e7ab12b441ed765/trace_processor_shell" }, "mac_arm64": { "hash": "c32364e05e22cdf82ee0866aedd11c0e2050809c", "full_remote_path": "perfetto-luci-artifacts/v34.0/mac-arm64/trace_processor_shell" }, "linux": { - "hash": "912b6a52ba7675a84edec2fac3c928b962e8460a", - "full_remote_path": "chromium-telemetry/perfetto_binaries/trace_processor_shell/linux/8636689446ccacc31a106573931c8bad825e9dc1/trace_processor_shell" + "hash": "d79dc368361818d7f1c42ddeb9964ebce65e5ab2", + "full_remote_path": "chromium-telemetry/perfetto_binaries/trace_processor_shell/linux/a6abd9944464ff392ea57c6e3e82784e603987ec/trace_processor_shell" } }, "power_profile.sql": {
diff --git a/ui/accessibility/android/java/src/org/chromium/ui/accessibility/AccessibilityState.java b/ui/accessibility/android/java/src/org/chromium/ui/accessibility/AccessibilityState.java index 89a3890..34985581 100644 --- a/ui/accessibility/android/java/src/org/chromium/ui/accessibility/AccessibilityState.java +++ b/ui/accessibility/android/java/src/org/chromium/ui/accessibility/AccessibilityState.java
@@ -4,6 +4,7 @@ package org.chromium.ui.accessibility; +import static android.accessibilityservice.AccessibilityServiceInfo.CAPABILITY_CAN_PERFORM_GESTURES; import static android.accessibilityservice.AccessibilityServiceInfo.FEEDBACK_SPOKEN; import static android.accessibilityservice.AccessibilityServiceInfo.FLAG_REQUEST_TOUCH_EXPLORATION_MODE; @@ -89,6 +90,9 @@ // True when the user has touch exploration enabled. False otherwise. public final boolean isTouchExplorationEnabled; + // True when a service that requested to perform gestures is enabled. False otherwise. + public final boolean isPerformGesturesEnabled; + // True when at least one accessibility service is enabled. False otherwise. public final boolean isAnyAccessibilityServiceEnabled; @@ -110,11 +114,12 @@ public final boolean isOnlyPasswordManagersEnabled; public State(boolean isScreenReaderEnabled, boolean isTouchExplorationEnabled, - boolean isAnyAccessibilityServiceEnabled, boolean isAccessibilityToolPresent, - boolean isSpokenFeedbackServicePresent, boolean isTextShowPasswordEnabled, - boolean isOnlyPasswordManagersEnabled) { + boolean isPerformGesturesEnabled, boolean isAnyAccessibilityServiceEnabled, + boolean isAccessibilityToolPresent, boolean isSpokenFeedbackServicePresent, + boolean isTextShowPasswordEnabled, boolean isOnlyPasswordManagersEnabled) { this.isScreenReaderEnabled = isScreenReaderEnabled; this.isTouchExplorationEnabled = isTouchExplorationEnabled; + this.isPerformGesturesEnabled = isPerformGesturesEnabled; this.isAnyAccessibilityServiceEnabled = isAnyAccessibilityServiceEnabled; this.isAccessibilityToolPresent = isAccessibilityToolPresent; this.isSpokenFeedbackServicePresent = isSpokenFeedbackServicePresent; @@ -209,6 +214,11 @@ return sState.isTouchExplorationEnabled; } + public static boolean isPerformGesturesEnabled() { + if (!sInitialized) updateAccessibilityServices(); + return sState.isPerformGesturesEnabled; + } + public static boolean isAnyAccessibilityServiceEnabled() { if (!sInitialized) updateAccessibilityServices(); return sState.isAnyAccessibilityServiceEnabled; @@ -242,7 +252,7 @@ static void updateAccessibilityServices() { if (!sInitialized) { - sState = new State(false, false, false, false, false, false, false); + sState = new State(false, false, false, false, false, false, false, false); } sInitialized = true; sEventTypeMask = 0; @@ -438,10 +448,12 @@ boolean isSpokenFeedbackServicePresent = (0 != (sFeedbackTypeMask & FEEDBACK_SPOKEN)); boolean isTouchExplorationEnabled = (0 != (sFlagsMask & FLAG_REQUEST_TOUCH_EXPLORATION_MODE)); + boolean isPerformGesturesEnabled = + (0 != (sCapabilitiesMask & CAPABILITY_CAN_PERFORM_GESTURES)); updateAndNotifyStateChange(new State(isScreenReaderEnabled, isTouchExplorationEnabled, - isAnyAccessibilityServiceEnabled, isAccessibilityToolPresent, - isSpokenFeedbackServicePresent, isTextShowPasswordEnabled, - isOnlyPasswordManagersEnabled)); + isPerformGesturesEnabled, isAnyAccessibilityServiceEnabled, + isAccessibilityToolPresent, isSpokenFeedbackServicePresent, + isTextShowPasswordEnabled, isOnlyPasswordManagersEnabled)); } private static void updateAndNotifyStateChange(State newState) { @@ -629,6 +641,7 @@ State newState = new State( enabled, sState.isTouchExplorationEnabled, + sState.isPerformGesturesEnabled, sState.isAnyAccessibilityServiceEnabled, sState.isAccessibilityToolPresent, sState.isSpokenFeedbackServicePresent, @@ -645,6 +658,24 @@ State newState = new State( sState.isScreenReaderEnabled, enabled, + sState.isPerformGesturesEnabled, + sState.isAnyAccessibilityServiceEnabled, + sState.isAccessibilityToolPresent, + sState.isSpokenFeedbackServicePresent, + sState.isTextShowPasswordEnabled, + sState.isOnlyPasswordManagersEnabled); + + updateAndNotifyStateChange(newState); + } + + @VisibleForTesting + public static void setIsPerformGesturesEnabledForTesting(boolean enabled) { + if (!sInitialized) updateAccessibilityServices(); + + State newState = new State( + sState.isScreenReaderEnabled, + sState.isTouchExplorationEnabled, + enabled, sState.isAnyAccessibilityServiceEnabled, sState.isAccessibilityToolPresent, sState.isSpokenFeedbackServicePresent, @@ -661,6 +692,7 @@ State newState = new State( sState.isScreenReaderEnabled, sState.isTouchExplorationEnabled, + sState.isPerformGesturesEnabled, enabled, sState.isAccessibilityToolPresent, sState.isSpokenFeedbackServicePresent, @@ -677,6 +709,7 @@ State newState = new State( sState.isScreenReaderEnabled, sState.isTouchExplorationEnabled, + sState.isPerformGesturesEnabled, sState.isAnyAccessibilityServiceEnabled, enabled, sState.isSpokenFeedbackServicePresent, @@ -693,6 +726,7 @@ State newState = new State( sState.isScreenReaderEnabled, sState.isTouchExplorationEnabled, + sState.isPerformGesturesEnabled, sState.isAnyAccessibilityServiceEnabled, sState.isAccessibilityToolPresent, enabled, @@ -709,6 +743,7 @@ State newState = new State( sState.isScreenReaderEnabled, sState.isTouchExplorationEnabled, + sState.isPerformGesturesEnabled, sState.isAnyAccessibilityServiceEnabled, sState.isAccessibilityToolPresent, sState.isSpokenFeedbackServicePresent, @@ -725,6 +760,7 @@ State newState = new State( sState.isScreenReaderEnabled, sState.isTouchExplorationEnabled, + sState.isPerformGesturesEnabled, sState.isAnyAccessibilityServiceEnabled, sState.isAccessibilityToolPresent, sState.isSpokenFeedbackServicePresent,
diff --git a/ui/accessibility/ax_enum_util.cc b/ui/accessibility/ax_enum_util.cc index f26a9a4..2da56a9 100644 --- a/ui/accessibility/ax_enum_util.cc +++ b/ui/accessibility/ax_enum_util.cc
@@ -1297,6 +1297,8 @@ return "keyShortcuts"; case ax::mojom::StringAttribute::kLanguage: return "language"; + case ax::mojom::StringAttribute::kLinkTarget: + return "linkTarget"; case ax::mojom::StringAttribute::kName: return "name"; case ax::mojom::StringAttribute::kLiveRelevant:
diff --git a/ui/accessibility/ax_enums.mojom b/ui/accessibility/ax_enums.mojom index 035c6cf1b..fe740a5 100644 --- a/ui/accessibility/ax_enums.mojom +++ b/ui/accessibility/ax_enums.mojom
@@ -559,8 +559,8 @@ kSubtreeUpdateEnd, }; -// Next version: 3 -// Next value: 35 +// Next version: 4 +// Next value: 36 [Extensible, Stable, Uuid="e5a4cd0c-3152-4427-93d5-35ff7d0f1ae8"] enum StringAttribute { [Default]kNone = 0, @@ -593,6 +593,7 @@ kKeyShortcuts = 19, // Only present when different from parent. kLanguage = 20, + [MinVersion=3] kLinkTarget = 35, // E.g. "self", "blank", "top". [MinVersion=1] kLongClickLabel = 32, // Only for ARC kName = 21, kLiveRelevant = 22,
diff --git a/ui/accessibility/ax_node_data.cc b/ui/accessibility/ax_node_data.cc index 8b3a7ab1..2f811137 100644 --- a/ui/accessibility/ax_node_data.cc +++ b/ui/accessibility/ax_node_data.cc
@@ -1715,6 +1715,9 @@ case ax::mojom::StringAttribute::kLanguage: result += " language=" + value; break; + case ax::mojom::StringAttribute::kLinkTarget: + result += " link_target=" + value; + break; case ax::mojom::StringAttribute::kLiveRelevant: result += " relevant=" + value; break;
diff --git a/ui/accessibility/platform/ax_platform_node_base.cc b/ui/accessibility/platform/ax_platform_node_base.cc index 0da3f98..1af2c84 100644 --- a/ui/accessibility/platform/ax_platform_node_base.cc +++ b/ui/accessibility/platform/ax_platform_node_base.cc
@@ -1587,6 +1587,11 @@ std::string details_roles = ComputeDetailsRoles(); if (!details_roles.empty()) AddAttributeToList("details-roles", details_roles, attributes); + + if (ui::IsLink(GetRole())) { + AddAttributeToList(ax::mojom::StringAttribute::kLinkTarget, "link-target", + attributes); + } } void AXPlatformNodeBase::AddAttributeToList(
diff --git a/ui/base/l10n/l10n_util_mac.mm b/ui/base/l10n/l10n_util_mac.mm index 8722cb9..70ad12b 100644 --- a/ui/base/l10n/l10n_util_mac.mm +++ b/ui/base/l10n/l10n_util_mac.mm
@@ -4,9 +4,9 @@ #import <Foundation/Foundation.h> +#include "base/apple/bundle_locations.h" #include "base/check.h" #include "base/lazy_instance.h" -#include "base/mac/bundle_locations.h" #import "base/mac/scoped_nsobject.h" #include "base/strings/sys_string_conversions.h" #include "ui/base/l10n/l10n_util.h" @@ -49,7 +49,7 @@ // "Today" are in the same language as raw dates like "March 20, 1999" (Chrome // strings resources vs ICU generated strings). This also makes the Mac acts // like other Chrome platforms. - NSArray* languageList = [base::mac::OuterBundle() preferredLocalizations]; + NSArray* languageList = [base::apple::OuterBundle() preferredLocalizations]; NSString* firstLocale = languageList[0]; // Mac OS X uses "_" instead of "-", so swap to get a real locale value. std::string locale_value =
diff --git a/ui/base/resource/resource_bundle_ios.mm b/ui/base/resource/resource_bundle_ios.mm index ba3c71ae..4753ceb 100644 --- a/ui/base/resource/resource_bundle_ios.mm +++ b/ui/base/resource/resource_bundle_ios.mm
@@ -7,9 +7,9 @@ #import <QuartzCore/QuartzCore.h> #import <UIKit/UIKit.h> +#include "base/apple/bundle_locations.h" #include "base/files/file_path.h" #include "base/files/file_util.h" -#include "base/mac/bundle_locations.h" #include "base/mac/foundation_util.h" #include "base/mac/scoped_nsobject.h" #include "base/memory/ref_counted_memory.h" @@ -26,13 +26,13 @@ base::FilePath GetResourcesPakFilePath(NSString* name, NSString* mac_locale) { NSString *resource_path; if ([mac_locale length]) { - resource_path = [base::mac::FrameworkBundle() pathForResource:name - ofType:@"pak" - inDirectory:@"" - forLocalization:mac_locale]; + resource_path = [base::apple::FrameworkBundle() pathForResource:name + ofType:@"pak" + inDirectory:@"" + forLocalization:mac_locale]; } else { - resource_path = [base::mac::FrameworkBundle() pathForResource:name - ofType:@"pak"]; + resource_path = [base::apple::FrameworkBundle() pathForResource:name + ofType:@"pak"]; } if (!resource_path) { // Return just the name of the pak file.
diff --git a/ui/base/resource/resource_bundle_mac.mm b/ui/base/resource/resource_bundle_mac.mm index 7eaac0fe..ec44159 100644 --- a/ui/base/resource/resource_bundle_mac.mm +++ b/ui/base/resource/resource_bundle_mac.mm
@@ -7,10 +7,10 @@ #import <AppKit/AppKit.h> #include <stddef.h> +#include "base/apple/bundle_locations.h" #include "base/files/file_path.h" #include "base/files/file_util.h" #include "base/logging.h" -#include "base/mac/bundle_locations.h" #include "base/mac/scoped_nsobject.h" #include "base/memory/ref_counted_memory.h" #include "base/notreached.h" @@ -31,13 +31,13 @@ // as the already-running browser instead of using what NSBundle might pick // based on values at helper launch time. if ([mac_locale length]) { - resource_path = [base::mac::FrameworkBundle() pathForResource:name - ofType:@"pak" - inDirectory:@"" - forLocalization:mac_locale]; + resource_path = [base::apple::FrameworkBundle() pathForResource:name + ofType:@"pak" + inDirectory:@"" + forLocalization:mac_locale]; } else { - resource_path = [base::mac::FrameworkBundle() pathForResource:name - ofType:@"pak"]; + resource_path = [base::apple::FrameworkBundle() pathForResource:name + ofType:@"pak"]; } if (!resource_path) {
diff --git a/ui/base/test/run_all_unittests.cc b/ui/base/test/run_all_unittests.cc index fb79a08..a3183f9f 100644 --- a/ui/base/test/run_all_unittests.cc +++ b/ui/base/test/run_all_unittests.cc
@@ -13,7 +13,7 @@ #include "ui/base/ui_base_paths.h" #if BUILDFLAG(IS_MAC) -#include "base/mac/bundle_locations.h" +#include "base/apple/bundle_locations.h" #include "base/test/mock_chrome_application_mac.h" #endif @@ -56,7 +56,7 @@ // On Mac, a test Framework bundle is created that links locale.pak and // chrome_100_percent.pak at the appropriate places to ui_test.pak. - base::mac::SetOverrideFrameworkBundlePath( + base::apple::SetOverrideFrameworkBundlePath( exe_path.AppendASCII("ui_unittests Framework.framework")); ui::ResourceBundle::InitSharedInstanceWithLocale( "en-US", NULL, ui::ResourceBundle::LOAD_COMMON_RESOURCES); @@ -104,7 +104,7 @@ ui::ResourceBundle::CleanupSharedInstance(); #if BUILDFLAG(IS_MAC) - base::mac::SetOverrideFrameworkBundlePath({}); + base::apple::SetOverrideFrameworkBundlePath({}); #endif base::TestSuite::Shutdown(); }
diff --git a/ui/base/wayland/color_manager_util.cc b/ui/base/wayland/color_manager_util.cc index 2081f61..22d8362 100644 --- a/ui/base/wayland/color_manager_util.cc +++ b/ui/base/wayland/color_manager_util.cc
@@ -52,10 +52,6 @@ return it.first; } } - for (const auto& it : kTransferMap) { - if (color_space.IsTransferFunctionEqualTo(it.second)) - return it.first; - } - return ZCR_COLOR_MANAGER_V1_EOTF_NAMES_UNKNOWN; + return ToColorManagerEOTF(color_space.GetTransferID()); } } // namespace ui::wayland
diff --git a/ui/chromeos/styles/cros_sys_colors.json5 b/ui/chromeos/styles/cros_sys_colors.json5 index b7ee2f92..3d2d6f7 100644 --- a/ui/chromeos/styles/cros_sys_colors.json5 +++ b/ui/chromeos/styles/cros_sys_colors.json5
@@ -391,7 +391,7 @@ /* Effects */ 'hover-on-prominent': { - light: 'rgba($cros.ref.neutral10.rgb, 0.10)', + light: 'rgba($cros.ref.neutral99.rgb, 0.10)', dark: 'rgba($cros.ref.neutral10.rgb, 0.06)', }, 'hover-on-subtle': {
diff --git a/ui/color/color_id.h b/ui/color/color_id.h index ea088b2..3a8fbcc 100644 --- a/ui/color/color_id.h +++ b/ui/color/color_id.h
@@ -254,9 +254,13 @@ E_CPONLY(kColorButtonForegroundTonal) \ E_CPONLY(kColorButtonHoverBackgroundText) \ E_CPONLY(kColorMultitaskMenuNudgePulse) \ - E_CPONLY(kColorCheckboxBackgroundDisabled) \ + E_CPONLY(kColorCheckboxCheck) \ + E_CPONLY(kColorCheckboxCheckDisabled) \ + E_CPONLY(kColorCheckboxContainer) \ + E_CPONLY(kColorCheckboxContainerDisabled) \ + E_CPONLY(kColorCheckboxOutline) \ + E_CPONLY(kColorCheckboxOutlineDisabled) \ E_CPONLY(kColorCheckboxForegroundChecked) \ - E_CPONLY(kColorCheckboxForegroundDisabled) \ E_CPONLY(kColorCheckboxForegroundUnchecked) \ E_CPONLY(kColorComboboxBackground) \ E_CPONLY(kColorComboboxBackgroundDisabled) \
diff --git a/ui/color/material_ui_color_mixer.cc b/ui/color/material_ui_color_mixer.cc index 2e2465d8..ab08a8b 100644 --- a/ui/color/material_ui_color_mixer.cc +++ b/ui/color/material_ui_color_mixer.cc
@@ -41,10 +41,12 @@ mixer[kColorButtonForeground] = {kColorSysPrimary}; mixer[kColorButtonForegroundDisabled] = {kColorSysStateDisabled}; mixer[kColorButtonForegroundProminent] = {kColorSysOnPrimary}; - mixer[kColorCheckboxBackgroundDisabled] = {kColorSysStateDisabledContainer}; - mixer[kColorCheckboxForegroundChecked] = {kColorSysPrimary}; - mixer[kColorCheckboxForegroundDisabled] = {kColorSysStateDisabled}; - mixer[kColorCheckboxForegroundUnchecked] = {kColorSysOutline}; + mixer[kColorCheckboxCheck] = {kColorSysOnPrimary}; + mixer[kColorCheckboxCheckDisabled] = {kColorSysStateDisabled}; + mixer[kColorCheckboxContainer] = {kColorSysPrimary}; + mixer[kColorCheckboxContainerDisabled] = {kColorSysStateDisabledContainer}; + mixer[kColorCheckboxOutline] = {kColorSysOutline}; + mixer[kColorCheckboxOutlineDisabled] = {kColorSysStateDisabledContainer}; mixer[kColorComboboxBackground] = {kColorSysSurface}; mixer[kColorComboboxBackgroundDisabled] = {GetResultingPaintColor( {kColorSysStateDisabledContainer}, {kColorComboboxBackground})};
diff --git a/ui/gl/init/gl_initializer_mac.cc b/ui/gl/init/gl_initializer_mac.cc index c2e7ddcd..49418ea 100644 --- a/ui/gl/init/gl_initializer_mac.cc +++ b/ui/gl/init/gl_initializer_mac.cc
@@ -4,10 +4,10 @@ #include "ui/gl/init/gl_initializer.h" +#include "base/apple/bundle_locations.h" #include "base/base_paths.h" #include "base/files/file_path.h" #include "base/logging.h" -#include "base/mac/bundle_locations.h" #include "base/mac/foundation_util.h" #include "base/native_library.h" #include "base/path_service.h" @@ -44,7 +44,7 @@ // as app bundles. In that case, the .dylib is next to the executable. base::FilePath base_dir; if (base::mac::AmIBundled()) { - base_dir = base::mac::FrameworkBundlePath().Append("Libraries"); + base_dir = base::apple::FrameworkBundlePath().Append("Libraries"); } else { if (!base::PathService::Get(base::FILE_EXE, &base_dir)) { LOG(ERROR) << "PathService::Get failed.";
diff --git a/ui/ozone/platform/wayland/host/wayland_surface.cc b/ui/ozone/platform/wayland/host/wayland_surface.cc index 5f93e6ac..a6aa149 100644 --- a/ui/ozone/platform/wayland/host/wayland_surface.cc +++ b/ui/ozone/platform/wayland/host/wayland_surface.cc
@@ -20,6 +20,7 @@ #include "base/files/scoped_file.h" #include "base/logging.h" #include "base/ranges/algorithm.h" +#include "ui/gfx/color_space.h" #include "ui/gfx/geometry/rect.h" #include "ui/gfx/geometry/rect_conversions.h" #include "ui/gfx/geometry/size.h" @@ -939,6 +940,12 @@ if (!connection_->zcr_color_manager()) { return; } + if (!color_space.IsValid() && pending_state_.contains_video) { + // Not all video content contains colorspace information. + // In this case, default to Rec709. + // Maybe use Rec601 for SD video if it becomes an issue. + color_space = gfx::ColorSpace::CreateREC709(); + } if (!color_space.IsValid()) { return; }
diff --git a/ui/views/BUILD.gn b/ui/views/BUILD.gn index 11515d6..01bbf457 100644 --- a/ui/views/BUILD.gn +++ b/ui/views/BUILD.gn
@@ -24,7 +24,7 @@ sources = [ "checkbox_active.icon", - "checkbox_active_cr2023.icon", + "checkbox_check_cr2023.icon", "checkbox_normal.icon", "checkbox_normal_cr2023.icon", "close.icon",
diff --git a/ui/views/controls/button/checkbox.cc b/ui/views/controls/button/checkbox.cc index ec6d1bae..f19ef14c 100644 --- a/ui/views/controls/button/checkbox.cc +++ b/ui/views/controls/button/checkbox.cc
@@ -20,6 +20,7 @@ #include "ui/gfx/color_palette.h" #include "ui/gfx/color_utils.h" #include "ui/gfx/geometry/skia_conversions.h" +#include "ui/gfx/image/image_skia_operations.h" #include "ui/gfx/paint_vector_icon.h" #include "ui/native_theme/native_theme.h" #include "ui/views/accessibility/view_accessibility.h" @@ -43,6 +44,8 @@ namespace { constexpr gfx::Size kCheckboxInkDropSize = gfx::Size(24, 24); +constexpr float kCheckboxIconDipSize = 16; +constexpr int kCheckboxIconCornerRadius = 2; } class Checkbox::FocusRingHighlightPathGenerator @@ -194,7 +197,22 @@ icon_state |= IconState::CHECKED; if (for_state != STATE_DISABLED) icon_state |= IconState::ENABLED; - return gfx::CreateVectorIcon(GetVectorIcon(), 16, + + if (features::IsChromeRefresh2023()) { + const SkColor container_color = GetIconContainerColor(icon_state); + if (GetChecked()) { + const gfx::ImageSkia check_icon = gfx::CreateVectorIcon( + GetVectorIcon(), kCheckboxIconDipSize, GetIconImageColor(icon_state)); + + return gfx::ImageSkiaOperations::CreateImageWithRoundRectBackground( + kCheckboxIconDipSize, kCheckboxIconCornerRadius, container_color, + check_icon); + } + return gfx::CreateVectorIcon(GetVectorIcon(), kCheckboxIconDipSize, + container_color); + } + + return gfx::CreateVectorIcon(GetVectorIcon(), kCheckboxIconDipSize, GetIconImageColor(icon_state)); } @@ -237,9 +255,8 @@ // CR2023 is launched if (features::IsChromeRefresh2023()) { return (icon_state & IconState::ENABLED) - ? active_color - : GetColorProvider()->GetColor( - ui::kColorCheckboxForegroundDisabled); + ? GetColorProvider()->GetColor(ui::kColorCheckboxCheck) + : GetColorProvider()->GetColor(ui::kColorCheckboxCheckDisabled); } return (icon_state & IconState::ENABLED) @@ -248,9 +265,21 @@ gfx::kDisabledControlAlpha); } +SkColor Checkbox::GetIconContainerColor(int icon_state) const { + if (icon_state & IconState::CHECKED) { + return GetColorProvider()->GetColor( + (icon_state & IconState::ENABLED) + ? ui::kColorCheckboxContainer + : ui::kColorCheckboxContainerDisabled); + } + return GetColorProvider()->GetColor((icon_state & IconState::ENABLED) + ? ui::kColorCheckboxOutline + : ui::kColorCheckboxOutlineDisabled); +} + const gfx::VectorIcon& Checkbox::GetVectorIcon() const { if (features::IsChromeRefresh2023()) { - return GetChecked() ? kCheckboxActiveCr2023Icon : kCheckboxNormalCr2023Icon; + return GetChecked() ? kCheckboxCheckCr2023Icon : kCheckboxNormalCr2023Icon; } return GetChecked() ? kCheckboxActiveIcon : kCheckboxNormalIcon;
diff --git a/ui/views/controls/button/checkbox.h b/ui/views/controls/button/checkbox.h index eef47902..94da33f 100644 --- a/ui/views/controls/button/checkbox.h +++ b/ui/views/controls/button/checkbox.h
@@ -64,6 +64,7 @@ // |icon_state| is a bitmask using the IconState enum. virtual SkColor GetIconImageColor(int icon_state) const; + virtual SkColor GetIconContainerColor(int icon_state) const; // Gets the vector icon to use based on the current state of |checked_|. virtual const gfx::VectorIcon& GetVectorIcon() const;
diff --git a/ui/views/vector_icons/checkbox_active_cr2023.icon b/ui/views/vector_icons/checkbox_check_cr2023.icon similarity index 93% rename from ui/views/vector_icons/checkbox_active_cr2023.icon rename to ui/views/vector_icons/checkbox_check_cr2023.icon index 63db090..b72fd07 100644 --- a/ui/views/vector_icons/checkbox_active_cr2023.icon +++ b/ui/views/vector_icons/checkbox_check_cr2023.icon
@@ -7,8 +7,6 @@ CANVAS_DIMENSIONS, 16, NEW_PATH, -ROUND_RECT, 0, 0, 16, 16, 2, - MOVE_TO, 12.19f, 4.12f, LINE_TO, 6.18f, 10.13f, LINE_TO, 4.06f, 8.01f, @@ -18,4 +16,4 @@ R_LINE_TO, 0.35f, 0.35f, R_LINE_TO, 7.07f, -7.07f, R_LINE_TO, -1.06f, -1.06f, -CLOSE +CLOSE \ No newline at end of file
diff --git a/ui/views/widget/native_widget_mac.mm b/ui/views/widget/native_widget_mac.mm index 9684386..aace2ffd 100644 --- a/ui/views/widget/native_widget_mac.mm +++ b/ui/views/widget/native_widget_mac.mm
@@ -608,7 +608,7 @@ if (show_state == ui::SHOW_STATE_INACTIVE) { window_state = WindowVisibilityState::kShowInactive; } else if (show_state == ui::SHOW_STATE_MINIMIZED) { - window_state = WindowVisibilityState::kHideWindow; + window_state = WindowVisibilityState::kMiniaturizeWindow; } else if (show_state == ui::SHOW_STATE_DEFAULT) { window_state = delegate_->CanActivate() ? window_state
diff --git a/ui/views/widget/native_widget_mac_unittest.mm b/ui/views/widget/native_widget_mac_unittest.mm index 5e0b9fc..9db8cfe 100644 --- a/ui/views/widget/native_widget_mac_unittest.mm +++ b/ui/views/widget/native_widget_mac_unittest.mm
@@ -484,14 +484,14 @@ // Test minimized states triggered externally, implied visibility and restored // bounds whilst minimized. TEST_F(NativeWidgetMacTest, MiniaturizeExternally) { - Widget* widget = new Widget; + WidgetAutoclosePtr widget(new Widget); Widget::InitParams init_params(Widget::InitParams::TYPE_WINDOW); widget->Init(std::move(init_params)); - PaintCountView* view = new PaintCountView(); - widget->GetContentsView()->AddChildView(view); + auto* view = widget->GetContentsView()->AddChildView( + std::make_unique<PaintCountView>()); NSWindow* ns_window = widget->GetNativeWindow().GetNativeNSWindow(); - WidgetChangeObserver observer(widget); + WidgetChangeObserver observer(widget.get()); widget->SetBounds(gfx::Rect(100, 100, 300, 300)); @@ -500,7 +500,7 @@ { views::test::PropertyWaiter visibility_waiter( - base::BindRepeating(&Widget::IsVisible, base::Unretained(widget)), + base::BindRepeating(&Widget::IsVisible, base::Unretained(widget.get())), true); widget->Show(); EXPECT_TRUE(visibility_waiter.Wait()); @@ -521,7 +521,8 @@ // anything fancy to wait for it finish. { views::test::PropertyWaiter minimize_waiter( - base::BindRepeating(&Widget::IsMinimized, base::Unretained(widget)), + base::BindRepeating(&Widget::IsMinimized, + base::Unretained(widget.get())), true); [ns_window performMiniaturize:nil]; EXPECT_TRUE(minimize_waiter.Wait()); @@ -541,7 +542,8 @@ { views::test::PropertyWaiter deminimize_waiter( - base::BindRepeating(&Widget::IsMinimized, base::Unretained(widget)), + base::BindRepeating(&Widget::IsMinimized, + base::Unretained(widget.get())), false); [ns_window deminiaturize:nil]; EXPECT_TRUE(deminimize_waiter.Wait()); @@ -558,7 +560,8 @@ { views::test::PropertyWaiter minimize_waiter( - base::BindRepeating(&Widget::IsMinimized, base::Unretained(widget)), + base::BindRepeating(&Widget::IsMinimized, + base::Unretained(widget.get())), true); widget->Minimize(); EXPECT_TRUE(minimize_waiter.Wait()); @@ -573,7 +576,8 @@ { views::test::PropertyWaiter deminimize_waiter( - base::BindRepeating(&Widget::IsMinimized, base::Unretained(widget)), + base::BindRepeating(&Widget::IsMinimized, + base::Unretained(widget.get())), false); widget->Restore(); // If miniaturized, should deminiaturize. EXPECT_TRUE(deminimize_waiter.Wait()); @@ -588,7 +592,8 @@ { views::test::PropertyWaiter deminimize_waiter( - base::BindRepeating(&Widget::IsMinimized, base::Unretained(widget)), + base::BindRepeating(&Widget::IsMinimized, + base::Unretained(widget.get())), false); widget->Restore(); // If not miniaturized, does nothing. EXPECT_TRUE(deminimize_waiter.Wait()); @@ -600,8 +605,50 @@ EXPECT_EQ(2, observer.lost_visible_count()); EXPECT_EQ(restored_bounds, widget->GetRestoredBounds()); EXPECT_EQ(3, view->paint_count()); +} - widget->CloseNow(); +// Tests that NativeWidgetMac::Show(ui::SHOW_STATE_MINIMIZED) minimizes the +// widget (previously it ordered its window out). +TEST_F(NativeWidgetMacTest, MinimizeByNativeShow) { + WidgetAutoclosePtr widget(new Widget); + Widget::InitParams init_params(Widget::InitParams::TYPE_WINDOW); + widget->Init(std::move(init_params)); + + auto* view = widget->GetContentsView()->AddChildView( + std::make_unique<PaintCountView>()); + WidgetChangeObserver observer(widget.get()); + + widget->SetBounds(gfx::Rect(100, 100, 300, 300)); + + EXPECT_TRUE(view->IsDrawn()); + EXPECT_EQ(0, view->paint_count()); + + { + views::test::PropertyWaiter visibility_waiter( + base::BindRepeating(&Widget::IsVisible, base::Unretained(widget.get())), + true); + widget->Show(); + EXPECT_TRUE(visibility_waiter.Wait()); + } + + EXPECT_FALSE(widget->IsMinimized()); + EXPECT_TRUE(widget->IsVisible()); + + { + views::test::PropertyWaiter minimize_waiter( + base::BindRepeating(&Widget::IsMinimized, + base::Unretained(widget.get())), + true); + + NativeWidgetMac* native_widget = + static_cast<views::NativeWidgetMac*>(widget->native_widget()); + gfx::Rect restore_bounds(100, 100, 300, 300); + native_widget->Show(ui::SHOW_STATE_MINIMIZED, restore_bounds); + + EXPECT_TRUE(minimize_waiter.Wait()); + } + + EXPECT_TRUE(widget->IsMinimized()); } TEST_F(NativeWidgetMacTest, MiniaturizeFramelessWindow) {
diff --git a/ui/webui/webui_allowlist.cc b/ui/webui/webui_allowlist.cc index 231f078ab..f886022 100644 --- a/ui/webui/webui_allowlist.cc +++ b/ui/webui/webui_allowlist.cc
@@ -106,9 +106,8 @@ } std::unique_ptr<content_settings::RuleIterator> WebUIAllowlist::GetRuleIterator( - ContentSettingsType content_type) const NO_THREAD_SAFETY_ANALYSIS { - // NO_THREAD_SAFETY_ANALYSIS: GetRuleIterator immediately locks the lock. - return value_map_.GetRuleIterator(content_type, &lock_); + ContentSettingsType content_type) const { + return value_map_.GetRuleIterator(content_type); } void WebUIAllowlist::SetContentSettingsAndNotifyProvider( @@ -120,7 +119,7 @@ DCHECK_CALLED_ON_VALID_THREAD(thread_checker_); { - base::AutoLock auto_lock(lock_); + base::AutoLock auto_lock(value_map_.GetLock()); value_map_.SetValue(primary_pattern, secondary_pattern, type, base::Value(setting), /* metadata */ {}); @@ -135,4 +134,4 @@ provider_->NotifyContentSettingChange(primary_pattern, secondary_pattern, type); } -} \ No newline at end of file +}
diff --git a/ui/webui/webui_allowlist.h b/ui/webui/webui_allowlist.h index 6f8dd62..47ffc23 100644 --- a/ui/webui/webui_allowlist.h +++ b/ui/webui/webui_allowlist.h
@@ -82,8 +82,7 @@ THREAD_CHECKER(thread_checker_); - mutable base::Lock lock_; - content_settings::OriginIdentifierValueMap value_map_ GUARDED_BY(lock_); + content_settings::OriginIdentifierValueMap value_map_; raw_ptr<WebUIAllowlistProvider> provider_ GUARDED_BY_CONTEXT(thread_checker_) = nullptr;
diff --git a/weblayer/browser/java/BUILD.gn b/weblayer/browser/java/BUILD.gn index b05228e..766e456 100644 --- a/weblayer/browser/java/BUILD.gn +++ b/weblayer/browser/java/BUILD.gn
@@ -248,7 +248,7 @@ "//components/metrics:metrics_java", "//components/minidump_uploader:minidump_uploader_java", "//components/navigation_interception/android:navigation_interception_java", - "//components/omnibox/browser:browser_java", + "//components/omnibox/browser:scheme_classifier_java", "//components/page_info/android:java", "//components/payments/content/android:java", "//components/payments/content/android:service_java",