diff --git a/DEPS b/DEPS index 96c6e9b..322c40c 100644 --- a/DEPS +++ b/DEPS
@@ -145,11 +145,11 @@ # Three lines of non-changing comments so that # the commit queue can handle CLs rolling Skia # and whatever else without interference from each other. - 'skia_revision': '4d557e3df433400b55373b684123920b03f2f728', + 'skia_revision': '26cedb4c603b4f845d35711e35863742fcb1c8df', # 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': '46afc4f9a6008c3880fcc00783b4210cb467aa9a', + 'v8_revision': '63ed65e390e83916b19ee8f1152b8fb704ebd7a4', # Three lines of non-changing comments so that # the commit queue can handle CLs rolling swarming_client # and whatever else without interference from each other. @@ -157,11 +157,11 @@ # 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': 'eb0479e245f0b6ba5bbe00ef7299ecaa82f8c6e1', + 'angle_revision': 'e54c3e3aa01cc5e1d0bbec28d6db619b22960bd3', # Three lines of non-changing comments so that # the commit queue can handle CLs rolling SwiftShader # and whatever else without interference from each other. - 'swiftshader_revision': 'f046402b1480245c3c17e91131f11f066f53b289', + 'swiftshader_revision': 'e662bb437032ddfec2e154a420376351ac0bd54d', # Three lines of non-changing comments so that # the commit queue can handle CLs rolling PDFium # and whatever else without interference from each other. @@ -200,7 +200,7 @@ # Three lines of non-changing comments so that # the commit queue can handle CLs rolling HarfBuzz # and whatever else without interference from each other. - 'harfbuzz_revision': '2e7021da7d1726a37822e6a001b9218f82255bc8', + 'harfbuzz_revision': '60485ab0473630c585bb96fcdc14dbe415edf4f2', # Three lines of non-changing comments so that # the commit queue can handle CLs rolling Emoji Segmenter # and whatever else without interference from each other. @@ -208,7 +208,7 @@ # Three lines of non-changing comments so that # the commit queue can handle CLs rolling catapult # and whatever else without interference from each other. - 'catapult_revision': '30604c6c8ec1c53b63a2340d0a81acfb1cb12f99', + 'catapult_revision': 'e00548aa79c77afbe796d78ab7b97576b49d8159', # Three lines of non-changing comments so that # the commit queue can handle CLs rolling libFuzzer # and whatever else without interference from each other. @@ -264,7 +264,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. - 'spv_tools_revision': 'b029d3697ea34b82b4f77d63a45dcc181ff59a65', + 'spv_tools_revision': '22ce39c8e1ec6da68f60dc7c9ef47069676ba9c2', # Three lines of non-changing comments so that # the commit queue can handle CLs rolling feed # and whatever else without interference from each other. @@ -280,7 +280,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': 'ef2fac0b9447cb4cbb93616bc91508ffb6fef599', + 'dawn_revision': 'ebb05399c09af7814a21aa555800656b4f5021b2', # Three lines of non-changing comments so that # the commit queue can handle CLs rolling feed # and whatever else without interference from each other. @@ -814,7 +814,7 @@ # Build tools for Chrome OS. Note: This depends on third_party/pyelftools. 'src/third_party/chromite': { - 'url': Var('chromium_git') + '/chromiumos/chromite.git' + '@' + '24a749c4b23fbc61729ccf2ade3559a95f3164f6', + 'url': Var('chromium_git') + '/chromiumos/chromite.git' + '@' + 'bfed8088cbab538e1b0edc064363e4c0ae5be804', 'condition': 'checkout_linux', }, @@ -1212,7 +1212,7 @@ }, 'src/third_party/perfetto': - Var('android_git') + '/platform/external/perfetto.git' + '@' + '64c217c797c45107bba6768bb0ee6a210ffc11a8', + Var('android_git') + '/platform/external/perfetto.git' + '@' + 'f3b064fc4807e17c78a055d6f30d20f73082fe2a', 'src/third_party/perl': { 'url': Var('chromium_git') + '/chromium/deps/perl.git' + '@' + '6f3e5028eb65d0b4c5fdd792106ac4c84eee1eb3', @@ -1380,7 +1380,7 @@ Var('chromium_git') + '/external/khronosgroup/webgl.git' + '@' + 'abaae129d9a0c6e1e092067e0b105475df43352e', 'src/third_party/webrtc': - Var('webrtc_git') + '/src.git' + '@' + '5e4af85c479608e006e071f48eba819aefd0215c', + Var('webrtc_git') + '/src.git' + '@' + 'e4ba4ee837acb8dfc2045a1c63a39547da419d7e', 'src/third_party/xdg-utils': { 'url': Var('chromium_git') + '/chromium/deps/xdg-utils.git' + '@' + 'd80274d5869b17b8c9067a1022e4416ee7ed5e0d', @@ -1421,7 +1421,7 @@ Var('chromium_git') + '/v8/v8.git' + '@' + Var('v8_revision'), 'src-internal': { - 'url': 'https://chrome-internal.googlesource.com/chrome/src-internal.git@0f851e59ee6ed9a6dfa81383ed0aa884d957b5cd', + 'url': 'https://chrome-internal.googlesource.com/chrome/src-internal.git@794dd735e4f8881d05cecd3941b74b8b0448483c', 'condition': 'checkout_src_internal', },
diff --git a/PRESUBMIT.py b/PRESUBMIT.py index 7b8efc43..c6f66e3 100644 --- a/PRESUBMIT.py +++ b/PRESUBMIT.py
@@ -498,7 +498,7 @@ ( 'New code should not use NULL. Use nullptr instead.', ), - True, + False, (), ), # Make sure that gtest's FRIEND_TEST() macro is not used; the
diff --git a/apps/launcher.cc b/apps/launcher.cc index e7f1d8e..0b6d73b 100644 --- a/apps/launcher.cc +++ b/apps/launcher.cc
@@ -155,9 +155,9 @@ } void LaunchWithRelativePath(const base::FilePath& current_directory) { - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, - {base::TaskPriority::USER_VISIBLE, base::MayBlock(), + {base::ThreadPool(), base::TaskPriority::USER_VISIBLE, base::MayBlock(), base::TaskShutdownBehavior::SKIP_ON_SHUTDOWN}, base::BindOnce(&PlatformAppPathLauncher::MakePathAbsolute, this, current_directory)); @@ -173,7 +173,7 @@ it != entry_paths_.end(); ++it) { if (!DoMakePathAbsolute(current_directory, &*it)) { LOG(WARNING) << "Cannot make absolute path from " << it->value(); - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {BrowserThread::UI}, base::BindOnce(&PlatformAppPathLauncher::LaunchWithBasicData, this)); @@ -181,9 +181,8 @@ } } - base::PostTaskWithTraits( - FROM_HERE, {BrowserThread::UI}, - base::BindOnce(&PlatformAppPathLauncher::Launch, this)); + base::PostTask(FROM_HERE, {BrowserThread::UI}, + base::BindOnce(&PlatformAppPathLauncher::Launch, this)); } void OnFilesValid(std::unique_ptr<std::set<base::FilePath>> directory_paths) {
diff --git a/ash/accelerators/accelerator_controller_unittest.cc b/ash/accelerators/accelerator_controller_unittest.cc index 19eabc83..f203a613 100644 --- a/ash/accelerators/accelerator_controller_unittest.cc +++ b/ash/accelerators/accelerator_controller_unittest.cc
@@ -2031,7 +2031,7 @@ MediaControllerImpl* media_controller = Shell::Get()->media_controller(); media_controller->SetClient(client_.get()); media_controller->SetMediaSessionControllerForTest( - controller_->CreateMediaControllerPtr()); + controller_->CreateMediaControllerRemote()); media_controller->SetForceMediaClientKeyHandling( GetParam().force_key_handling); media_controller->FlushForTesting();
diff --git a/ash/login/login_screen_controller.cc b/ash/login/login_screen_controller.cc index eda11a8..38f7714a 100644 --- a/ash/login/login_screen_controller.cc +++ b/ash/login/login_screen_controller.cc
@@ -24,6 +24,7 @@ #include "ash/system/toast/toast_manager_impl.h" #include "ash/system/tray/system_tray_notifier.h" #include "base/bind.h" +#include "base/callback.h" #include "base/debug/alias.h" #include "base/strings/string_number_conversions.h" #include "base/strings/utf_string_conversions.h" @@ -391,6 +392,26 @@ ->GetScopedGuestButtonBlocker(); } +void LoginScreenController::RequestSecurityTokenPin( + SecurityTokenPinRequest request) { + if (!LockScreen::HasInstance()) { + // Corner case: the PIN request is made at inappropriate time, racing with + // the lock screen showing/hiding. + std::move(request.pin_ui_closed_callback).Run(); + return; + } + LockScreen::Get()->RequestSecurityTokenPin(std::move(request)); +} + +void LoginScreenController::ClearSecurityTokenPinRequest() { + if (!LockScreen::HasInstance()) { + // Corner case: the request is made at inappropriate time, racing with the + // lock screen showing/hiding. + return; + } + LockScreen::Get()->ClearSecurityTokenPinRequest(); +} + void LoginScreenController::ShowLockScreen() { OnShow(); LockScreen::Show(LockScreen::ScreenType::kLock);
diff --git a/ash/login/login_screen_controller.h b/ash/login/login_screen_controller.h index 8405746..122ca7f7 100644 --- a/ash/login/login_screen_controller.h +++ b/ash/login/login_screen_controller.h
@@ -124,6 +124,8 @@ void SetAllowLoginAsGuest(bool allow_guest) override; std::unique_ptr<ScopedGuestButtonBlocker> GetScopedGuestButtonBlocker() override; + void RequestSecurityTokenPin(SecurityTokenPinRequest request) override; + void ClearSecurityTokenPinRequest() override; // KioskAppMenu: void SetKioskApps(
diff --git a/ash/login/login_screen_test_api.cc b/ash/login/login_screen_test_api.cc index a892df6..618a38b 100644 --- a/ash/login/login_screen_test_api.cc +++ b/ash/login/login_screen_test_api.cc
@@ -153,6 +153,11 @@ } // static +bool LoginScreenTestApi::IsParentAccessButtonShown() { + return IsLoginShelfViewButtonShown(LoginShelfView::kParentAccess); +} + +// static void LoginScreenTestApi::SubmitPassword(const AccountId& account_id, const std::string& password) { // It'd be better to generate keyevents dynamically and dispatch them instead
diff --git a/ash/login/ui/lock_contents_view.cc b/ash/login/ui/lock_contents_view.cc index 87b16b7..4dc5329 100644 --- a/ash/login/ui/lock_contents_view.cc +++ b/ash/login/ui/lock_contents_view.cc
@@ -39,6 +39,7 @@ #include "ash/system/tray/system_tray_notifier.h" #include "ash/wm/tablet_mode/tablet_mode_controller.h" #include "base/bind.h" +#include "base/callback.h" #include "base/command_line.h" #include "base/strings/string16.h" #include "base/strings/utf_string_conversions.h" @@ -366,6 +367,11 @@ return view_->main_view_; } +void LockContentsView::TestApi::SimulateParentAccessValidationFinished( + bool access_granted) { + view_->OnParentAccessValidationFinished(access_granted); +} + LockContentsView::UserState::UserState(const LoginUserInfo& user_info) : account_id(user_info.basic_user_info.account_id) { fingerprint_state = user_info.fingerprint_state; @@ -558,14 +564,34 @@ if (!primary_big_view_) return; - if (show) + if (show) { primary_big_view_->ShowParentAccessView(); - else + Shell::Get()->login_screen_controller()->ShowParentAccessButton(false); + } else { primary_big_view_->HideParentAccessView(); + } Layout(); } +void LockContentsView::RequestSecurityTokenPin( + SecurityTokenPinRequest request) { + // TODO(crbug.com/983103): Pick up the user whose authentication triggered + // this PIN attempt, based on the account identifier supplied by the + // cryptohome. + if (primary_big_view_ && primary_big_view_->auth_user()) + primary_big_view_->auth_user()->RequestSecurityTokenPin(std::move(request)); + else + std::move(request.pin_ui_closed_callback).Run(); +} + +void LockContentsView::ClearSecurityTokenPinRequest() { + // Note that if the PIN UI used to be shown in a different primary big view, + // then it was already closed while switching the view. + if (primary_big_view_ && primary_big_view_->auth_user()) + primary_big_view_->auth_user()->ClearSecurityTokenPinRequest(); +} + void LockContentsView::Layout() { View::Layout(); LayoutTopHeader(); @@ -1819,6 +1845,8 @@ void LockContentsView::OnParentAccessValidationFinished(bool access_granted) { ShowParentAccessDialog(false); + Shell::Get()->login_screen_controller()->ShowParentAccessButton( + !access_granted); } keyboard::KeyboardUIController* LockContentsView::GetKeyboardControllerForView()
diff --git a/ash/login/ui/lock_contents_view.h b/ash/login/ui/lock_contents_view.h index 2f731894..6c34ce8 100644 --- a/ash/login/ui/lock_contents_view.h +++ b/ash/login/ui/lock_contents_view.h
@@ -22,6 +22,7 @@ #include "ash/public/cpp/login_types.h" #include "ash/public/cpp/system_tray_focus_observer.h" #include "ash/session/session_observer.h" +#include "base/callback_forward.h" #include "base/macros.h" #include "base/optional.h" #include "base/scoped_observer.h" @@ -90,6 +91,10 @@ LoginExpandedPublicAccountView* expanded_view() const; views::View* main_view() const; + // Simulates that parent access code validation finished with the result + // specified in |access_granted|. + void SimulateParentAccessValidationFinished(bool access_granted); + private: LockContentsView* const view_; }; @@ -126,6 +131,8 @@ void FocusNextUser(); void FocusPreviousUser(); void ShowParentAccessDialog(bool show); + void RequestSecurityTokenPin(SecurityTokenPinRequest request); + void ClearSecurityTokenPinRequest(); // views::View: void Layout() override;
diff --git a/ash/login/ui/lock_contents_view_unittest.cc b/ash/login/ui/lock_contents_view_unittest.cc index 520f30d..1fa0675e 100644 --- a/ash/login/ui/lock_contents_view_unittest.cc +++ b/ash/login/ui/lock_contents_view_unittest.cc
@@ -30,6 +30,7 @@ #include "ash/login/ui/views_utils.h" #include "ash/public/cpp/ash_features.h" #include "ash/public/cpp/ash_pref_names.h" +#include "ash/public/cpp/login_screen_test_api.h" #include "ash/public/mojom/tray_action.mojom.h" #include "ash/root_window_controller.h" #include "ash/session/session_controller_impl.h" @@ -1985,6 +1986,36 @@ ->HasFocus()); } +// Tests parent access shelf button is showing and hiding. +TEST_F(LockContentsViewUnitTest, ParentAccessButton) { + GetSessionControllerClient()->SetSessionState( + session_manager::SessionState::LOCKED); + + auto* contents = new LockContentsView( + mojom::TrayActionState::kAvailable, LockScreen::ScreenType::kLock, + DataDispatcher(), + std::make_unique<FakeLoginDetachableBaseModel>(DataDispatcher())); + LockContentsView::TestApi contents_test_api(contents); + AddChildUsers(1); + SetWidget(CreateWidgetWithContent(contents)); + + // Simulate initial state - button shown. + Shell::Get()->login_screen_controller()->ShowParentAccessButton(true); + EXPECT_TRUE(ash::LoginScreenTestApi::IsParentAccessButtonShown()); + + // Validation failed - show the button. + contents->ShowParentAccessDialog(true); + EXPECT_FALSE(ash::LoginScreenTestApi::IsParentAccessButtonShown()); + contents_test_api.SimulateParentAccessValidationFinished(false); + EXPECT_TRUE(ash::LoginScreenTestApi::IsParentAccessButtonShown()); + + // Validation succeeded - hide the button. + contents->ShowParentAccessDialog(true); + EXPECT_FALSE(ash::LoginScreenTestApi::IsParentAccessButtonShown()); + contents_test_api.SimulateParentAccessValidationFinished(true); + EXPECT_FALSE(ash::LoginScreenTestApi::IsParentAccessButtonShown()); +} + using LockContentsViewPowerManagerUnitTest = LockContentsViewUnitTest; // Ensures that a PowerManagerClient::Observer is added on LockScreen::Show()
diff --git a/ash/login/ui/lock_screen.cc b/ash/login/ui/lock_screen.cc index f6db4af..b6c68bb 100644 --- a/ash/login/ui/lock_screen.cc +++ b/ash/login/ui/lock_screen.cc
@@ -20,6 +20,7 @@ #include "ash/tray_action/tray_action.h" #include "ash/wallpaper/wallpaper_controller_impl.h" #include "base/bind.h" +#include "base/callback.h" #include "base/command_line.h" #include "chromeos/constants/chromeos_switches.h" #include "ui/display/display.h" @@ -149,6 +150,14 @@ contents_view_->ShowParentAccessDialog(true); } +void LockScreen::RequestSecurityTokenPin(SecurityTokenPinRequest request) { + contents_view_->RequestSecurityTokenPin(std::move(request)); +} + +void LockScreen::ClearSecurityTokenPinRequest() { + contents_view_->ClearSecurityTokenPinRequest(); +} + void LockScreen::OnLockScreenNoteStateChanged(mojom::TrayActionState state) { Shell::Get() ->login_screen_controller()
diff --git a/ash/login/ui/lock_screen.h b/ash/login/ui/lock_screen.h index 05761e2..9e0699a 100644 --- a/ash/login/ui/lock_screen.h +++ b/ash/login/ui/lock_screen.h
@@ -6,6 +6,7 @@ #define ASH_LOGIN_UI_LOCK_SCREEN_H_ #include "ash/ash_export.h" +#include "ash/public/cpp/login_types.h" #include "ash/session/session_observer.h" #include "ash/tray_action/tray_action_observer.h" #include "base/macros.h" @@ -63,6 +64,8 @@ void FocusNextUser(); void FocusPreviousUser(); void ShowParentAccessDialog(); + void RequestSecurityTokenPin(SecurityTokenPinRequest request); + void ClearSecurityTokenPinRequest(); // TrayActionObserver: void OnLockScreenNoteStateChanged(mojom::TrayActionState state) override;
diff --git a/ash/login/ui/lock_screen_media_controls_view.cc b/ash/login/ui/lock_screen_media_controls_view.cc index 593803e..2be0320 100644 --- a/ash/login/ui/lock_screen_media_controls_view.cc +++ b/ash/login/ui/lock_screen_media_controls_view.cc
@@ -265,22 +265,23 @@ // Connect to the MediaControllerManager and create a MediaController that // controls the active session so we can observe it. - media_session::mojom::MediaControllerManagerPtr controller_manager_ptr; - connector_->BindInterface(media_session::mojom::kServiceName, - mojo::MakeRequest(&controller_manager_ptr)); - controller_manager_ptr->CreateActiveMediaController( - mojo::MakeRequest(&media_controller_ptr_)); + mojo::Remote<media_session::mojom::MediaControllerManager> + controller_manager_remote; + connector_->Connect(media_session::mojom::kServiceName, + controller_manager_remote.BindNewPipeAndPassReceiver()); + controller_manager_remote->CreateActiveMediaController( + media_controller_remote_.BindNewPipeAndPassReceiver()); // Observe the active media controller for changes. - media_controller_ptr_->AddObserver( + media_controller_remote_->AddObserver( observer_receiver_.BindNewPipeAndPassRemote()); - media_controller_ptr_->ObserveImages( + media_controller_remote_->ObserveImages( media_session::mojom::MediaSessionImageType::kArtwork, kMinimumArtworkSize, kDesiredArtworkSize, artwork_observer_receiver_.BindNewPipeAndPassRemote()); - media_controller_ptr_->ObserveImages( + media_controller_remote_->ObserveImages( media_session::mojom::MediaSessionImageType::kSourceIcon, kMinimumIconSize, kDesiredIconSize, icon_observer_receiver_.BindNewPipeAndPassRemote()); @@ -474,7 +475,7 @@ media_session::PerformMediaSessionAction( media_message_center::GetActionFromButtonTag(*sender), - media_controller_ptr_); + media_controller_remote_); } void LockScreenMediaControlsView::OnGestureEvent(ui::GestureEvent* event) { @@ -512,7 +513,7 @@ } void LockScreenMediaControlsView::FlushForTesting() { - media_controller_ptr_.FlushForTesting(); + media_controller_remote_.FlushForTesting(); } void LockScreenMediaControlsView::CreateMediaButton( @@ -564,7 +565,7 @@ } void LockScreenMediaControlsView::Dismiss() { - media_controller_ptr_->Stop(); + media_controller_remote_->Stop(); hide_media_controls_.Run(); }
diff --git a/ash/login/ui/lock_screen_media_controls_view.h b/ash/login/ui/lock_screen_media_controls_view.h index 54c36de..dd2f1c5 100644 --- a/ash/login/ui/lock_screen_media_controls_view.h +++ b/ash/login/ui/lock_screen_media_controls_view.h
@@ -9,8 +9,8 @@ #include "ash/ash_export.h" #include "base/timer/timer.h" -#include "mojo/public/cpp/bindings/binding.h" #include "mojo/public/cpp/bindings/receiver.h" +#include "mojo/public/cpp/bindings/remote.h" #include "services/media_session/public/mojom/media_controller.mojom.h" #include "ui/compositor/layer_animation_observer.h" #include "ui/views/controls/button/button.h" @@ -104,8 +104,8 @@ void FlushForTesting(); void set_media_controller_for_testing( - media_session::mojom::MediaControllerPtr controller) { - media_controller_ptr_ = std::move(controller); + mojo::Remote<media_session::mojom::MediaController> controller) { + media_controller_remote_ = std::move(controller); } void set_timer_for_testing(std::unique_ptr<base::OneShotTimer> test_timer) { @@ -157,7 +157,7 @@ service_manager::Connector* const connector_; // Used to control the active session. - media_session::mojom::MediaControllerPtr media_controller_ptr_; + mojo::Remote<media_session::mojom::MediaController> media_controller_remote_; // Used to receive updates to the active media controller. mojo::Receiver<media_session::mojom::MediaControllerObserver>
diff --git a/ash/login/ui/lock_screen_media_controls_view_unittest.cc b/ash/login/ui/lock_screen_media_controls_view_unittest.cc index 0ab4a4f..494ce42 100644 --- a/ash/login/ui/lock_screen_media_controls_view_unittest.cc +++ b/ash/login/ui/lock_screen_media_controls_view_unittest.cc
@@ -106,7 +106,7 @@ // Inject the test media controller into the media controls view. media_controller_ = std::make_unique<TestMediaController>(); media_controls_view_->set_media_controller_for_testing( - media_controller_->CreateMediaControllerPtr()); + media_controller_->CreateMediaControllerRemote()); SimulateMediaSessionChanged( media_session::mojom::MediaPlaybackState::kPlaying);
diff --git a/ash/login/ui/login_auth_user_view.cc b/ash/login/ui/login_auth_user_view.cc index 9aab2e3..6ec1806 100644 --- a/ash/login/ui/login_auth_user_view.cc +++ b/ash/login/ui/login_auth_user_view.cc
@@ -6,6 +6,7 @@ #include <map> #include <memory> +#include <utility> #include "ash/login/login_screen_controller.h" #include "ash/login/resources/grit/login_resources.h" @@ -750,7 +751,11 @@ user_view_->UpdateForUser(user, false /*animate*/); } -LoginAuthUserView::~LoginAuthUserView() = default; +LoginAuthUserView::~LoginAuthUserView() { + // Abort the unfinished security token PIN request, if there's one, so that + // the callers can do all necessary cleanup. + AbortSecurityTokenPinRequest(); +} void LoginAuthUserView::SetAuthMethods(uint32_t auth_methods, bool can_use_pin) { @@ -766,12 +771,29 @@ bool has_external_binary = HasAuthMethod(AUTH_EXTERNAL_BINARY); bool has_challenge_response = HasAuthMethod(AUTH_CHALLENGE_RESPONSE); bool auth_disabled = HasAuthMethod(AUTH_DISABLED); + + if (auth_disabled) { + // The PIN UI cannot be displayed, so abort the security token PIN request, + // if there's one. + AbortSecurityTokenPinRequest(); + } + + if (security_token_pin_request_) { + // The security token PIN request is a special mode that uses the password + // and the PIN views, regardless of the user's auth methods. + has_password = true; + has_pin = true; + has_tap = false; + force_online_sign_in = false; + has_fingerprint = false; + has_external_binary = false; + has_challenge_response = false; + } + bool hide_auth = auth_disabled || force_online_sign_in; - // implication: if |has_pin| is true, then |can_use_pin| must also be true - DCHECK(!has_pin || can_use_pin); - // implication: if |can_use_pin| is false, then |has_pin| must also be false - DCHECK(can_use_pin || !has_pin); + // The pin UI should be used only when it's allowed. + DCHECK(!has_pin || can_use_pin || security_token_pin_request_); online_sign_in_message_->SetVisible(force_online_sign_in); disabled_auth_message_->SetVisible(auth_disabled); @@ -804,8 +826,12 @@ padding_below_password_view_->SetPreferredSize( gfx::Size(kNonEmptyWidthDp, padding_view_height)); - // Note: if both |has_tap| and |has_pin| are true, prefer tap placeholder. - if (has_tap) { + // Note: both |security_token_pin_request_| and |has_tap| must have higher + // priority than |has_pin| when determining the placeholder. + if (security_token_pin_request_) { + // TODO(crbug.com/983103): Put the localized string after the string review. + password_view_->SetPlaceholderText(base::UTF8ToUTF16("smart card PIN")); + } else if (has_tap) { password_view_->SetPlaceholderText( l10n_util::GetStringUTF16(IDS_ASH_LOGIN_POD_PASSWORD_TAP_PLACEHOLDER)); } else if (has_pin) { @@ -968,6 +994,10 @@ } void LoginAuthUserView::UpdateForUser(const LoginUserInfo& user) { + // Abort the security token PIN request associated with the previous user, if + // there was any. + AbortSecurityTokenPinRequest(); + user_view_->UpdateForUser(user, true /*animate*/); password_view_->UpdateForUser(user); password_view_->Clear(); @@ -989,6 +1019,31 @@ Layout(); } +void LoginAuthUserView::RequestSecurityTokenPin( + SecurityTokenPinRequest request) { + // The caller must prevent an overlapping PIN request before the previous one + // completed. + DCHECK(!security_token_pin_request_ || + !security_token_pin_request_->pin_entered_callback); + + security_token_pin_request_ = std::move(request); + password_view_->Clear(); + password_view_->SetReadOnly(false); + // Trigger SetAuthMethods() with the same parameters but after + // |on_security_token_pin_requested_| has been set, so that it updates the UI + // elements in order to show the security token PIN request. + SetAuthMethods(auth_methods_, can_use_pin_); +} + +void LoginAuthUserView::ClearSecurityTokenPinRequest() { + AbortSecurityTokenPinRequest(); + + // Revert the UI back to the normal user authentication controls. + password_view_->Clear(); + password_view_->SetReadOnly(false); + SetAuthMethods(auth_methods_, can_use_pin_); +} + const LoginUserInfo& LoginAuthUserView::current_user() const { return user_view_->current_user(); } @@ -1044,11 +1099,16 @@ } password_view_->SetReadOnly(true); - Shell::Get()->login_screen_controller()->AuthenticateUserWithPasswordOrPin( - current_user().basic_user_info.account_id, base::UTF16ToUTF8(password), - can_use_pin_, - base::BindOnce(&LoginAuthUserView::OnAuthComplete, - weak_factory_.GetWeakPtr())); + if (security_token_pin_request_) { + std::move(security_token_pin_request_->pin_entered_callback) + .Run(base::UTF16ToUTF8(password)); + } else { + Shell::Get()->login_screen_controller()->AuthenticateUserWithPasswordOrPin( + current_user().basic_user_info.account_id, base::UTF16ToUTF8(password), + can_use_pin_, + base::BindOnce(&LoginAuthUserView::OnAuthComplete, + weak_factory_.GetWeakPtr())); + } } void LoginAuthUserView::OnAuthComplete(base::Optional<bool> auth_success) { @@ -1127,4 +1187,11 @@ weak_factory_.GetWeakPtr())); } +void LoginAuthUserView::AbortSecurityTokenPinRequest() { + if (!security_token_pin_request_) + return; + std::move(security_token_pin_request_->pin_ui_closed_callback).Run(); + security_token_pin_request_.reset(); +} + } // namespace ash
diff --git a/ash/login/ui/login_auth_user_view.h b/ash/login/ui/login_auth_user_view.h index 9134f25..24282b33 100644 --- a/ash/login/ui/login_auth_user_view.h +++ b/ash/login/ui/login_auth_user_view.h
@@ -14,6 +14,7 @@ #include "ash/login/ui/non_accessible_view.h" #include "ash/public/cpp/login_types.h" #include "ash/public/cpp/session/user_info.h" +#include "base/callback.h" #include "base/memory/weak_ptr.h" #include "base/optional.h" #include "base/scoped_observer.h" @@ -133,6 +134,13 @@ // auth method is |AUTH_DISABLED|. void SetAuthDisabledMessage(const AuthDisabledData& auth_disabled_data); + // Called to request the user to enter the PIN of the security token (e.g., + // the smart card). + void RequestSecurityTokenPin(SecurityTokenPinRequest request); + + // Called to close the UI previously opened with RequestSecurityTokenPin(). + void ClearSecurityTokenPinRequest(); + const LoginUserInfo& current_user() const; LoginPasswordView* password_view() { return password_view_; } @@ -181,6 +189,9 @@ // starts the asynchronous authentication process against a security token. void AttemptAuthenticateWithChallengeResponse(); + // Aborts the current active security token PIN request, if there's one. + void AbortSecurityTokenPinRequest(); + AuthMethods auth_methods_ = AUTH_NONE; // True if the user's password might be a PIN. PIN is hashed differently from // password. The PIN keyboard may not always be visible even when the user @@ -209,6 +220,9 @@ // |ApplyAnimationPostLayout|. std::unique_ptr<AnimationState> cached_animation_state_; + // Parameters of the active security token PIN request, if there's one. + base::Optional<SecurityTokenPinRequest> security_token_pin_request_; + ScopedObserver<chromeos::PowerManagerClient, chromeos::PowerManagerClient::Observer> power_manager_client_observer_{this};
diff --git a/ash/media/media_controller_impl.cc b/ash/media/media_controller_impl.cc index e0662f15..edaaec0 100644 --- a/ash/media/media_controller_impl.cc +++ b/ash/media/media_controller_impl.cc
@@ -207,46 +207,49 @@ } void MediaControllerImpl::SetMediaSessionControllerForTest( - media_session::mojom::MediaControllerPtr controller) { - media_session_controller_ptr_ = std::move(controller); + mojo::Remote<media_session::mojom::MediaController> controller) { + media_session_controller_remote_ = std::move(controller); BindMediaControllerObserver(); } void MediaControllerImpl::FlushForTesting() { - if (media_session_controller_ptr_) - media_session_controller_ptr_.FlushForTesting(); + if (media_session_controller_remote_) + media_session_controller_remote_.FlushForTesting(); } media_session::mojom::MediaController* MediaControllerImpl::GetMediaSessionController() { // |connector_| can be null in tests. - if (connector_ && !media_session_controller_ptr_.is_bound()) { - media_session::mojom::MediaControllerManagerPtr controller_manager_ptr; - connector_->BindInterface(media_session::mojom::kServiceName, - &controller_manager_ptr); - controller_manager_ptr->CreateActiveMediaController( - mojo::MakeRequest(&media_session_controller_ptr_)); + if (connector_ && !media_session_controller_remote_.is_bound()) { + mojo::Remote<media_session::mojom::MediaControllerManager> + controller_manager_remote; + connector_->Connect(media_session::mojom::kServiceName, + controller_manager_remote.BindNewPipeAndPassReceiver()); + controller_manager_remote->CreateActiveMediaController( + media_session_controller_remote_.BindNewPipeAndPassReceiver()); - media_session_controller_ptr_.set_connection_error_handler( + media_session_controller_remote_.set_disconnect_handler( base::BindRepeating(&MediaControllerImpl::OnMediaSessionControllerError, base::Unretained(this))); BindMediaControllerObserver(); } - return media_session_controller_ptr_.get(); + return media_session_controller_remote_.is_bound() + ? media_session_controller_remote_.get() + : nullptr; } void MediaControllerImpl::OnMediaSessionControllerError() { - media_session_controller_ptr_.reset(); + media_session_controller_remote_.reset(); supported_media_session_action_ = false; } void MediaControllerImpl::BindMediaControllerObserver() { - if (!media_session_controller_ptr_.is_bound()) + if (!media_session_controller_remote_.is_bound()) return; - media_session_controller_ptr_->AddObserver( + media_session_controller_remote_->AddObserver( media_controller_observer_receiver_.BindNewPipeAndPassRemote()); }
diff --git a/ash/media/media_controller_impl.h b/ash/media/media_controller_impl.h index a611d77..588f604 100644 --- a/ash/media/media_controller_impl.h +++ b/ash/media/media_controller_impl.h
@@ -11,6 +11,7 @@ #include "base/observer_list.h" #include "components/account_id/account_id.h" #include "mojo/public/cpp/bindings/receiver.h" +#include "mojo/public/cpp/bindings/remote.h" #include "services/media_session/public/mojom/media_controller.mojom.h" class PrefRegistrySimple; @@ -104,7 +105,7 @@ MediaGlobalAccelerators_UpdateForceKeyHandling); void SetMediaSessionControllerForTest( - media_session::mojom::MediaControllerPtr controller); + mojo::Remote<media_session::mojom::MediaController> controller); void FlushForTesting(); @@ -136,7 +137,8 @@ bool media_controls_dismissed_ = false; // Mojo pointer to the active media session controller. - media_session::mojom::MediaControllerPtr media_session_controller_ptr_; + mojo::Remote<media_session::mojom::MediaController> + media_session_controller_remote_; service_manager::Connector* const connector_;
diff --git a/ash/media/media_controller_unittest.cc b/ash/media/media_controller_unittest.cc index 33a2039f..6084dcc 100644 --- a/ash/media/media_controller_unittest.cc +++ b/ash/media/media_controller_unittest.cc
@@ -31,7 +31,7 @@ MediaControllerImpl* media_controller = Shell::Get()->media_controller(); media_controller->SetMediaSessionControllerForTest( - controller_->CreateMediaControllerPtr()); + controller_->CreateMediaControllerRemote()); media_controller->FlushForTesting(); {
diff --git a/ash/media/media_notification_controller_impl.cc b/ash/media/media_notification_controller_impl.cc index 1d2a61a6..3c1028a 100644 --- a/ash/media/media_notification_controller_impl.cc +++ b/ash/media/media_notification_controller_impl.cc
@@ -121,13 +121,13 @@ if (!connector) return; - media_session::mojom::AudioFocusManagerPtr audio_focus_ptr; - connector->BindInterface(media_session::mojom::kServiceName, - mojo::MakeRequest(&audio_focus_ptr)); - connector->BindInterface(media_session::mojom::kServiceName, - mojo::MakeRequest(&controller_manager_ptr_)); + mojo::Remote<media_session::mojom::AudioFocusManager> audio_focus_remote; + connector->Connect(media_session::mojom::kServiceName, + audio_focus_remote.BindNewPipeAndPassReceiver()); + connector->Connect(media_session::mojom::kServiceName, + controller_manager_remote.BindNewPipeAndPassReceiver()); - audio_focus_ptr->AddObserver( + audio_focus_remote->AddObserver( audio_focus_observer_receiver_.BindNewPipeAndPassRemote()); } @@ -143,13 +143,13 @@ if (it != notifications_.end() && !it->second.frozen()) return; - media_session::mojom::MediaControllerPtr controller; + mojo::Remote<media_session::mojom::MediaController> controller; - // |controller_manager_ptr_| may be null in tests where connector is + // |controller_manager_remote| may be null in tests where connector is // unavailable. - if (controller_manager_ptr_) { - controller_manager_ptr_->CreateMediaControllerForSession( - mojo::MakeRequest(&controller), *session->request_id); + if (controller_manager_remote) { + controller_manager_remote->CreateMediaControllerForSession( + controller.BindNewPipeAndPassReceiver(), *session->request_id); } if (it != notifications_.end()) {
diff --git a/ash/media/media_notification_controller_impl.h b/ash/media/media_notification_controller_impl.h index 826d803b..6734363 100644 --- a/ash/media/media_notification_controller_impl.h +++ b/ash/media/media_notification_controller_impl.h
@@ -80,7 +80,8 @@ // concurrent number of media notifications displayed. void RecordConcurrentNotificationCount(); - media_session::mojom::MediaControllerManagerPtr controller_manager_ptr_; + mojo::Remote<media_session::mojom::MediaControllerManager> + controller_manager_remote; mojo::Receiver<media_session::mojom::AudioFocusObserver> audio_focus_observer_receiver_{this};
diff --git a/ash/public/cpp/login_screen.h b/ash/public/cpp/login_screen.h index cc112734..a33a3a0 100644 --- a/ash/public/cpp/login_screen.h +++ b/ash/public/cpp/login_screen.h
@@ -8,6 +8,7 @@ #include <string> #include "ash/public/cpp/ash_public_export.h" +#include "ash/public/cpp/login_types.h" #include "base/callback_forward.h" class AccountId; @@ -84,6 +85,13 @@ virtual std::unique_ptr<ScopedGuestButtonBlocker> GetScopedGuestButtonBlocker() = 0; + // Called to request the user to enter the PIN of the security token (e.g., + // the smart card). + virtual void RequestSecurityTokenPin(SecurityTokenPinRequest request) = 0; + + // Called to close the UI previously opened with RequestSecurityTokenPin(). + virtual void ClearSecurityTokenPinRequest() = 0; + protected: LoginScreen(); virtual ~LoginScreen();
diff --git a/ash/public/cpp/login_screen_test_api.h b/ash/public/cpp/login_screen_test_api.h index cfb9e2b..99071fa3 100644 --- a/ash/public/cpp/login_screen_test_api.h +++ b/ash/public/cpp/login_screen_test_api.h
@@ -23,6 +23,7 @@ static bool IsAuthErrorBubbleShown(); static bool IsGuestButtonShown(); static bool IsAddUserButtonShown(); + static bool IsParentAccessButtonShown(); static void SubmitPassword(const AccountId& account_id, const std::string& password); static int64_t GetUiUpdateCount();
diff --git a/ash/public/cpp/login_types.cc b/ash/public/cpp/login_types.cc index 00ff1382..c8b158ba 100644 --- a/ash/public/cpp/login_types.cc +++ b/ash/public/cpp/login_types.cc
@@ -72,4 +72,11 @@ AuthDisabledData& AuthDisabledData::operator=(AuthDisabledData&& other) = default; +SecurityTokenPinRequest::SecurityTokenPinRequest() = default; +SecurityTokenPinRequest::SecurityTokenPinRequest(SecurityTokenPinRequest&&) = + default; +SecurityTokenPinRequest& SecurityTokenPinRequest::operator=( + SecurityTokenPinRequest&&) = default; +SecurityTokenPinRequest::~SecurityTokenPinRequest() = default; + } // namespace ash
diff --git a/ash/public/cpp/login_types.h b/ash/public/cpp/login_types.h index 2ccd02b..3d9e211 100644 --- a/ash/public/cpp/login_types.h +++ b/ash/public/cpp/login_types.h
@@ -7,9 +7,11 @@ #include "ash/public/cpp/ash_public_export.h" #include "ash/public/cpp/session/user_info.h" +#include "base/callback.h" #include "base/time/time.h" #include "base/token.h" #include "chromeos/components/proximity_auth/public/mojom/auth_type.mojom-forward.h" +#include "chromeos/constants/security_token_pin_types.h" namespace ash { @@ -298,6 +300,39 @@ kChangeTimezone, }; +// Parameters and callbacks for a security token PIN request that is to be shown +// to the user. +struct ASH_PUBLIC_EXPORT SecurityTokenPinRequest { + SecurityTokenPinRequest(); + SecurityTokenPinRequest(SecurityTokenPinRequest&&); + SecurityTokenPinRequest& operator=(SecurityTokenPinRequest&&); + ~SecurityTokenPinRequest(); + + // Type of the code requested from the user. + chromeos::SecurityTokenPinCodeType code_type = + chromeos::SecurityTokenPinCodeType::kPin; + + // Whether the UI controls that allow user to enter the value should be + // enabled. MUST be |false| when |attempts_left| is zero. + bool enable_user_input = true; + + // An optional error to be displayed to the user. + chromeos::SecurityTokenPinErrorLabel error_label = + chromeos::SecurityTokenPinErrorLabel::kNone; + + // When non-negative, the UI should indicate this number to the user; + // otherwise must be equal to -1. + int attempts_left = -1; + + // Called when the user submits the input. Will not be called if the UI is + // closed before that happens. + base::OnceCallback<void(const std::string& user_input)> pin_entered_callback; + + // Called when the PIN request UI gets closed. Will not be called when the + // browser itself requests the UI to be closed. + base::OnceClosure pin_ui_closed_callback; +}; + } // namespace ash #endif // ASH_PUBLIC_CPP_LOGIN_TYPES_H_
diff --git a/build/fuchsia/linux.sdk.sha1 b/build/fuchsia/linux.sdk.sha1 index 39880c6..c7fed86 100644 --- a/build/fuchsia/linux.sdk.sha1 +++ b/build/fuchsia/linux.sdk.sha1
@@ -1 +1 @@ -8905658232335495936 \ No newline at end of file +8905602942646600496 \ No newline at end of file
diff --git a/build/fuchsia/mac.sdk.sha1 b/build/fuchsia/mac.sdk.sha1 index eb1e7fa..4893766 100644 --- a/build/fuchsia/mac.sdk.sha1 +++ b/build/fuchsia/mac.sdk.sha1
@@ -1 +1 @@ -8905658267152347024 \ No newline at end of file +8905605558660323920 \ No newline at end of file
diff --git a/chrome/android/BUILD.gn b/chrome/android/BUILD.gn index 5c7c0cb..54c56eb8 100644 --- a/chrome/android/BUILD.gn +++ b/chrome/android/BUILD.gn
@@ -325,6 +325,7 @@ "//components/safe_browsing/android:safe_browsing_java", "//components/search_engines/android:java", "//components/signin/core/browser/android:java", + "//components/signin/public/identity_manager/android:java", "//components/spellcheck/browser/android:java", "//components/sync/android:sync_java", "//components/url_formatter/android:url_formatter_java",
diff --git a/chrome/android/DEPS b/chrome/android/DEPS index 7aab1ad..33b8678 100644 --- a/chrome/android/DEPS +++ b/chrome/android/DEPS
@@ -6,6 +6,7 @@ "+components/invalidation", "+components/policy", "+components/signin/core/browser/android", + "+components/signin/public/identity_manager/android", "+components/spellcheck/browser", "+jni", "+media/base/android/java",
diff --git a/chrome/android/features/keyboard_accessory/internal/java/res/layout/keyboard_accessory_sheet_tab_credit_card_info.xml b/chrome/android/features/keyboard_accessory/internal/java/res/layout/keyboard_accessory_sheet_tab_credit_card_info.xml index ca6e3a5..a5bc4e4 100644 --- a/chrome/android/features/keyboard_accessory/internal/java/res/layout/keyboard_accessory_sheet_tab_credit_card_info.xml +++ b/chrome/android/features/keyboard_accessory/internal/java/res/layout/keyboard_accessory_sheet_tab_credit_card_info.xml
@@ -40,6 +40,7 @@ style="@style/InputChip" /> <LinearLayout + android:id="@+id/exp_group" android:gravity="center_vertical|start" android:fillViewport="true" android:layout_height="@dimen/keyboard_accessory_suggestion_height"
diff --git a/chrome/android/features/keyboard_accessory/internal/java/src/org/chromium/chrome/browser/keyboard_accessory/ManualFillingComponentBridge.java b/chrome/android/features/keyboard_accessory/internal/java/src/org/chromium/chrome/browser/keyboard_accessory/ManualFillingComponentBridge.java index 4a4b3dc..dd595a6 100644 --- a/chrome/android/features/keyboard_accessory/internal/java/src/org/chromium/chrome/browser/keyboard_accessory/ManualFillingComponentBridge.java +++ b/chrome/android/features/keyboard_accessory/internal/java/src/org/chromium/chrome/browser/keyboard_accessory/ManualFillingComponentBridge.java
@@ -119,8 +119,9 @@ } @CalledByNative - private static Object createAccessorySheetData(@AccessoryTabType int type, String title) { - return new AccessorySheetData(type, title); + private static Object createAccessorySheetData( + @AccessoryTabType int type, String title, String warning) { + return new AccessorySheetData(type, title, warning); } @CalledByNative
diff --git a/chrome/android/features/keyboard_accessory/internal/java/src/org/chromium/chrome/browser/keyboard_accessory/bar_component/KeyboardAccessoryMediator.java b/chrome/android/features/keyboard_accessory/internal/java/src/org/chromium/chrome/browser/keyboard_accessory/bar_component/KeyboardAccessoryMediator.java index f25981a..1324c79 100644 --- a/chrome/android/features/keyboard_accessory/internal/java/src/org/chromium/chrome/browser/keyboard_accessory/bar_component/KeyboardAccessoryMediator.java +++ b/chrome/android/features/keyboard_accessory/internal/java/src/org/chromium/chrome/browser/keyboard_accessory/bar_component/KeyboardAccessoryMediator.java
@@ -125,6 +125,8 @@ */ private boolean shouldShowSuggestion(AutofillSuggestion suggestion) { switch (suggestion.getSuggestionId()) { + case PopupItemId.ITEM_ID_INSECURE_CONTEXT_PAYMENT_DISABLED_MESSAGE: + // The insecure context warning has a replacement in the fallback sheet. case PopupItemId.ITEM_ID_SEPARATOR: case PopupItemId.ITEM_ID_CLEAR_FORM: case PopupItemId.ITEM_ID_CREDIT_CARD_SIGNIN_PROMO: @@ -134,9 +136,6 @@ case PopupItemId.ITEM_ID_SHOW_ACCOUNT_CARDS: case PopupItemId.ITEM_ID_AUTOFILL_OPTIONS: return false; - case PopupItemId.ITEM_ID_INSECURE_CONTEXT_PAYMENT_DISABLED_MESSAGE: - return ChromeFeatureList.isEnabled( - ChromeFeatureList.AUTOFILL_MANUAL_FALLBACK_ANDROID); case PopupItemId.ITEM_ID_AUTOCOMPLETE_ENTRY: case PopupItemId.ITEM_ID_PASSWORD_ENTRY: case PopupItemId.ITEM_ID_DATALIST_ENTRY:
diff --git a/chrome/android/features/keyboard_accessory/internal/java/src/org/chromium/chrome/browser/keyboard_accessory/sheet_tabs/AccessorySheetTabMediator.java b/chrome/android/features/keyboard_accessory/internal/java/src/org/chromium/chrome/browser/keyboard_accessory/sheet_tabs/AccessorySheetTabMediator.java index 3a2e238..2293d57 100644 --- a/chrome/android/features/keyboard_accessory/internal/java/src/org/chromium/chrome/browser/keyboard_accessory/sheet_tabs/AccessorySheetTabMediator.java +++ b/chrome/android/features/keyboard_accessory/internal/java/src/org/chromium/chrome/browser/keyboard_accessory/sheet_tabs/AccessorySheetTabMediator.java
@@ -64,6 +64,9 @@ if (shouldShowTitle(accessorySheetData.getUserInfoList())) { items.add(new AccessorySheetDataPiece(accessorySheetData.getTitle(), Type.TITLE)); } + if (!accessorySheetData.getWarning().isEmpty()) { + items.add(new AccessorySheetDataPiece(accessorySheetData.getWarning(), Type.WARNING)); + } for (UserInfo userInfo : accessorySheetData.getUserInfoList()) { items.add(new AccessorySheetDataPiece(userInfo, mUserInfoType)); }
diff --git a/chrome/android/features/keyboard_accessory/internal/java/src/org/chromium/chrome/browser/keyboard_accessory/sheet_tabs/AccessorySheetTabModel.java b/chrome/android/features/keyboard_accessory/internal/java/src/org/chromium/chrome/browser/keyboard_accessory/sheet_tabs/AccessorySheetTabModel.java index b293d4e..bb9f5d4 100644 --- a/chrome/android/features/keyboard_accessory/internal/java/src/org/chromium/chrome/browser/keyboard_accessory/sheet_tabs/AccessorySheetTabModel.java +++ b/chrome/android/features/keyboard_accessory/internal/java/src/org/chromium/chrome/browser/keyboard_accessory/sheet_tabs/AccessorySheetTabModel.java
@@ -25,7 +25,7 @@ */ static class AccessorySheetDataPiece { @IntDef({Type.TITLE, Type.PASSWORD_INFO, Type.ADDRESS_INFO, Type.CREDIT_CARD_INFO, - Type.TOUCH_TO_FILL_INFO, Type.FOOTER_COMMAND}) + Type.TOUCH_TO_FILL_INFO, Type.FOOTER_COMMAND, Type.WARNING}) @Retention(RetentionPolicy.SOURCE) @interface Type { /** @@ -52,6 +52,10 @@ * A command at the end of the accessory sheet tab. */ int FOOTER_COMMAND = 6; + /** + * An optional warning to be displayed at the beginning of a sheet. + */ + int WARNING = 7; } private Object mDataPiece;
diff --git a/chrome/android/features/keyboard_accessory/internal/java/src/org/chromium/chrome/browser/keyboard_accessory/sheet_tabs/CreditCardAccessoryInfoView.java b/chrome/android/features/keyboard_accessory/internal/java/src/org/chromium/chrome/browser/keyboard_accessory/sheet_tabs/CreditCardAccessoryInfoView.java index bde2085..2b02265 100644 --- a/chrome/android/features/keyboard_accessory/internal/java/src/org/chromium/chrome/browser/keyboard_accessory/sheet_tabs/CreditCardAccessoryInfoView.java +++ b/chrome/android/features/keyboard_accessory/internal/java/src/org/chromium/chrome/browser/keyboard_accessory/sheet_tabs/CreditCardAccessoryInfoView.java
@@ -23,6 +23,7 @@ class CreditCardAccessoryInfoView extends LinearLayout { private ImageView mIcon; private ChipView mCCNumber; + private LinearLayout mExpiryGroup; private ChipView mExpMonth; private ChipView mExpYear; private ChipView mCardholder; @@ -40,6 +41,7 @@ mIcon = findViewById(R.id.icon); mCCNumber = findViewById(R.id.cc_number); + mExpiryGroup = findViewById(R.id.exp_group); mExpMonth = findViewById(R.id.exp_month); mExpYear = findViewById(R.id.exp_year); mCardholder = findViewById(R.id.cardholder); @@ -69,4 +71,8 @@ public ChipView getCardholder() { return mCardholder; } + + public LinearLayout getExpiryGroup() { + return mExpiryGroup; + } }
diff --git a/chrome/android/features/keyboard_accessory/internal/java/src/org/chromium/chrome/browser/keyboard_accessory/sheet_tabs/CreditCardAccessorySheetViewBinder.java b/chrome/android/features/keyboard_accessory/internal/java/src/org/chromium/chrome/browser/keyboard_accessory/sheet_tabs/CreditCardAccessorySheetViewBinder.java index b15e3b2..dccacd7 100644 --- a/chrome/android/features/keyboard_accessory/internal/java/src/org/chromium/chrome/browser/keyboard_accessory/sheet_tabs/CreditCardAccessorySheetViewBinder.java +++ b/chrome/android/features/keyboard_accessory/internal/java/src/org/chromium/chrome/browser/keyboard_accessory/sheet_tabs/CreditCardAccessorySheetViewBinder.java
@@ -22,6 +22,7 @@ class CreditCardAccessorySheetViewBinder { static ElementViewHolder create(ViewGroup parent, @AccessorySheetDataPiece.Type int viewType) { switch (viewType) { + case AccessorySheetDataPiece.Type.WARNING: // Fallthrough to reuse title container. case AccessorySheetDataPiece.Type.TITLE: return new AccessorySheetTabViewBinder.TitleViewHolder( parent, R.layout.keyboard_accessory_sheet_tab_title); @@ -50,6 +51,11 @@ bindChipView(view.getExpYear(), info.getFields().get(2)); bindChipView(view.getCardholder(), info.getFields().get(3)); + view.getExpiryGroup().setVisibility(view.getExpYear().getVisibility() == View.VISIBLE + || view.getExpMonth().getVisibility() == View.VISIBLE + ? View.VISIBLE + : View.GONE); + view.setIcon(AppCompatResources.getDrawable( view.getContext(), getDrawableForOrigin(info.getOrigin()))); } @@ -57,11 +63,11 @@ private static void bindChipView(ChipView chip, UserInfoField field) { chip.getPrimaryTextView().setText(field.getDisplayText()); chip.getPrimaryTextView().setContentDescription(field.getA11yDescription()); - if (!field.isSelectable() || field.getDisplayText().isEmpty()) { - chip.setVisibility(View.GONE); + chip.setVisibility(field.getDisplayText().isEmpty() ? View.GONE : View.VISIBLE); + if (!field.isSelectable()) { + chip.setEnabled(false); return; } - chip.setVisibility(View.VISIBLE); chip.setOnClickListener(src -> field.triggerSelection()); chip.setClickable(true); chip.setEnabled(true);
diff --git a/chrome/android/features/keyboard_accessory/javatests/src/org/chromium/chrome/browser/keyboard_accessory/ManualFillingTestHelper.java b/chrome/android/features/keyboard_accessory/javatests/src/org/chromium/chrome/browser/keyboard_accessory/ManualFillingTestHelper.java index 66e5a29..6ef710b 100644 --- a/chrome/android/features/keyboard_accessory/javatests/src/org/chromium/chrome/browser/keyboard_accessory/ManualFillingTestHelper.java +++ b/chrome/android/features/keyboard_accessory/javatests/src/org/chromium/chrome/browser/keyboard_accessory/ManualFillingTestHelper.java
@@ -59,6 +59,7 @@ import org.chromium.content_public.browser.test.util.TestInputMethodManagerWrapper; import org.chromium.content_public.browser.test.util.TestThreadUtils; import org.chromium.net.test.EmbeddedTestServer; +import org.chromium.net.test.ServerCertificate; import org.chromium.ui.DropdownPopupWindowInterface; import java.util.concurrent.ExecutionException; @@ -100,8 +101,9 @@ public void loadTestPage(String url, boolean isRtl, boolean waitForNode, ChromeWindow.KeyboardVisibilityDelegateFactory keyboardDelegate) throws InterruptedException { - mEmbeddedTestServer = EmbeddedTestServer.createAndStartServer( - InstrumentationRegistry.getInstrumentation().getContext()); + mEmbeddedTestServer = EmbeddedTestServer.createAndStartHTTPSServer( + InstrumentationRegistry.getInstrumentation().getContext(), + ServerCertificate.CERT_OK); ChromeWindow.setKeyboardVisibilityDelegateFactory(keyboardDelegate); mActivityTestRule.startMainActivityWithURL(mEmbeddedTestServer.getURL(url)); setRtlForTesting(isRtl);
diff --git a/chrome/android/features/keyboard_accessory/javatests/src/org/chromium/chrome/browser/keyboard_accessory/sheet_tabs/CreditCardAccessorySheetViewTest.java b/chrome/android/features/keyboard_accessory/javatests/src/org/chromium/chrome/browser/keyboard_accessory/sheet_tabs/CreditCardAccessorySheetViewTest.java index c1cfbea..3b56510 100644 --- a/chrome/android/features/keyboard_accessory/javatests/src/org/chromium/chrome/browser/keyboard_accessory/sheet_tabs/CreditCardAccessorySheetViewTest.java +++ b/chrome/android/features/keyboard_accessory/javatests/src/org/chromium/chrome/browser/keyboard_accessory/sheet_tabs/CreditCardAccessorySheetViewTest.java
@@ -139,7 +139,33 @@ @Test @MediumTest - public void testEmptyChipsAreNotVisible() throws ExecutionException { + public void testAddingUnselectableFieldsRendersUnclickabeChips() throws ExecutionException { + assertThat(mView.get().getChildCount(), is(0)); + + TestThreadUtils.runOnUiThreadBlocking(() -> { + UserInfo infoWithUnclickableField = new UserInfo("", null); + infoWithUnclickableField.addField( + new UserInfoField("4111111111111111", "4111111111111111", "", false, null)); + infoWithUnclickableField.addField(new UserInfoField("", "", "month", false, null)); + infoWithUnclickableField.addField(new UserInfoField("", "", "year", false, null)); + infoWithUnclickableField.addField(new UserInfoField("", "", "name", false, null)); + mModel.add(new AccessorySheetDataPiece( + infoWithUnclickableField, AccessorySheetDataPiece.Type.CREDIT_CARD_INFO)); + mModel.add(new AccessorySheetDataPiece( + new KeyboardAccessoryData.FooterCommand("Manage credit cards", null), + AccessorySheetDataPiece.Type.FOOTER_COMMAND)); + }); + + CriteriaHelper.pollUiThread(Criteria.equals(2, () -> mView.get().getChildCount())); + + assertThat(getChipText(R.id.cc_number), is("4111111111111111")); + assertThat(findChipView(R.id.cc_number).isShown(), is(true)); + assertThat(findChipView(R.id.cc_number).isEnabled(), is(false)); + } + + @Test + @MediumTest + public void testEmptyChipsAreNotVisible() { final AtomicBoolean clicked = new AtomicBoolean(); assertThat(mView.get().getChildCount(), is(0)); @@ -158,6 +184,29 @@ assertThat(findChipView(R.id.cardholder).isShown(), is(false)); } + @Test + @MediumTest + public void testRendersWarning() { + final String kWarning = "Insecure, so filling is no."; + assertThat(mView.get().getChildCount(), is(0)); + + TestThreadUtils.runOnUiThreadBlocking(() -> { + mModel.add(new AccessorySheetDataPiece(kWarning, AccessorySheetDataPiece.Type.WARNING)); + mModel.add(new AccessorySheetDataPiece( + new KeyboardAccessoryData.FooterCommand("Manage credit cards", null), + AccessorySheetDataPiece.Type.FOOTER_COMMAND)); + }); + + CriteriaHelper.pollUiThread(Criteria.equals(2, () -> mView.get().getChildCount())); + + assertThat(mView.get().getChildAt(0), instanceOf(LinearLayout.class)); + LinearLayout warning = (LinearLayout) mView.get().getChildAt(0); + assertThat(warning.findViewById(R.id.tab_title), instanceOf(TextView.class)); + TextView warningText = warning.findViewById(R.id.tab_title); + assertThat(warningText.isShown(), is(true)); + assertThat(warningText.getText(), is(kWarning)); + } + private UserInfo createInfo( String number, String month, String year, String name, AtomicBoolean clickRecorder) { UserInfo info = new UserInfo("", null);
diff --git a/chrome/android/features/keyboard_accessory/junit/src/org/chromium/chrome/browser/keyboard_accessory/ManualFillingControllerTest.java b/chrome/android/features/keyboard_accessory/junit/src/org/chromium/chrome/browser/keyboard_accessory/ManualFillingControllerTest.java index 9950b18..739edd2 100644 --- a/chrome/android/features/keyboard_accessory/junit/src/org/chromium/chrome/browser/keyboard_accessory/ManualFillingControllerTest.java +++ b/chrome/android/features/keyboard_accessory/junit/src/org/chromium/chrome/browser/keyboard_accessory/ManualFillingControllerTest.java
@@ -200,7 +200,7 @@ */ void providePasswordSheet(String passwordString) { AccessorySheetData sheetData = - new AccessorySheetData(AccessoryTabType.PASSWORDS, "Passwords"); + new AccessorySheetData(AccessoryTabType.PASSWORDS, "Passwords", ""); UserInfo userInfo = new UserInfo("", null); userInfo.addField( new UserInfoField("(No username)", "No username", /*id=*/"", false, null));
diff --git a/chrome/android/features/keyboard_accessory/junit/src/org/chromium/chrome/browser/keyboard_accessory/sheet_tabs/AddressAccessorySheetControllerTest.java b/chrome/android/features/keyboard_accessory/junit/src/org/chromium/chrome/browser/keyboard_accessory/sheet_tabs/AddressAccessorySheetControllerTest.java index 3a09725..fda2f8c 100644 --- a/chrome/android/features/keyboard_accessory/junit/src/org/chromium/chrome/browser/keyboard_accessory/sheet_tabs/AddressAccessorySheetControllerTest.java +++ b/chrome/android/features/keyboard_accessory/junit/src/org/chromium/chrome/browser/keyboard_accessory/sheet_tabs/AddressAccessorySheetControllerTest.java
@@ -107,13 +107,13 @@ // If the coordinator receives a set of initial items, the model should report an insertion. testProvider.notifyObservers( - new AccessorySheetData(AccessoryTabType.ADDRESSES, "Addresses")); + new AccessorySheetData(AccessoryTabType.ADDRESSES, "Addresses", "")); verify(mMockItemListObserver).onItemRangeInserted(mSheetDataPieces, 0, 1); assertThat(mSheetDataPieces.size(), is(1)); // If the coordinator receives a new set of items, the model should report a change. testProvider.notifyObservers( - new AccessorySheetData(AccessoryTabType.ADDRESSES, "Other Addresses")); + new AccessorySheetData(AccessoryTabType.ADDRESSES, "Other Addresses", "")); verify(mMockItemListObserver).onItemRangeChanged(mSheetDataPieces, 0, 1, null); assertThat(mSheetDataPieces.size(), is(1)); @@ -131,7 +131,7 @@ public void testSplitsTabDataToList() { final PropertyProvider<AccessorySheetData> testProvider = new PropertyProvider<>(); final AccessorySheetData testData = - new AccessorySheetData(AccessoryTabType.ADDRESSES, "Addresses for this site"); + new AccessorySheetData(AccessoryTabType.ADDRESSES, "Addresses for this site", ""); testData.getUserInfoList().add(new UserInfo("", null)); testData.getUserInfoList().get(0).addField( new UserInfoField("Name", "Name", "", false, null)); @@ -150,7 +150,7 @@ public void testUsesTitleElementForEmptyState() { final PropertyProvider<AccessorySheetData> testProvider = new PropertyProvider<>(); final AccessorySheetData testData = - new AccessorySheetData(AccessoryTabType.ADDRESSES, "No addresses"); + new AccessorySheetData(AccessoryTabType.ADDRESSES, "No addresses", ""); mCoordinator.registerDataProvider(testProvider); testProvider.notifyObservers(testData); @@ -183,7 +183,7 @@ // If the tab is shown without interactive item, log "0" samples. AccessorySheetData accessorySheetData = - new AccessorySheetData(AccessoryTabType.ADDRESSES, "No addresses!"); + new AccessorySheetData(AccessoryTabType.ADDRESSES, "No addresses!", ""); testProvider.notifyObservers(accessorySheetData); mCoordinator.onTabShown(); @@ -203,7 +203,7 @@ // Add only two interactive items - the third one should not be recorded. AccessorySheetData accessorySheetData = - new AccessorySheetData(AccessoryTabType.ADDRESSES, "Addresses"); + new AccessorySheetData(AccessoryTabType.ADDRESSES, "Addresses", ""); accessorySheetData.getUserInfoList().add(new UserInfo("", null)); accessorySheetData.getUserInfoList().get(0).addField( new UserInfoField("Todd Tester", "Todd Tester", "0", false, result -> {}));
diff --git a/chrome/android/features/keyboard_accessory/junit/src/org/chromium/chrome/browser/keyboard_accessory/sheet_tabs/CreditCardAccessorySheetControllerTest.java b/chrome/android/features/keyboard_accessory/junit/src/org/chromium/chrome/browser/keyboard_accessory/sheet_tabs/CreditCardAccessorySheetControllerTest.java index 7e0427f..40e63a5 100644 --- a/chrome/android/features/keyboard_accessory/junit/src/org/chromium/chrome/browser/keyboard_accessory/sheet_tabs/CreditCardAccessorySheetControllerTest.java +++ b/chrome/android/features/keyboard_accessory/junit/src/org/chromium/chrome/browser/keyboard_accessory/sheet_tabs/CreditCardAccessorySheetControllerTest.java
@@ -108,13 +108,13 @@ // If the coordinator receives a set of initial items, the model should report an insertion. testProvider.notifyObservers( - new AccessorySheetData(AccessoryTabType.CREDIT_CARDS, "Payments")); + new AccessorySheetData(AccessoryTabType.CREDIT_CARDS, "Payments", "")); verify(mMockItemListObserver).onItemRangeInserted(mSheetDataPieces, 0, 1); assertThat(mSheetDataPieces.size(), is(1)); // If the coordinator receives a new set of items, the model should report a change. testProvider.notifyObservers( - new AccessorySheetData(AccessoryTabType.CREDIT_CARDS, "Other Payments")); + new AccessorySheetData(AccessoryTabType.CREDIT_CARDS, "Other Payments", "")); verify(mMockItemListObserver).onItemRangeChanged(mSheetDataPieces, 0, 1, null); assertThat(mSheetDataPieces.size(), is(1)); @@ -132,7 +132,7 @@ public void testSplitsTabDataToList() { final PropertyProvider<AccessorySheetData> testProvider = new PropertyProvider<>(); final AccessorySheetData testData = - new AccessorySheetData(AccessoryTabType.CREDIT_CARDS, "Payments"); + new AccessorySheetData(AccessoryTabType.CREDIT_CARDS, "Payments", ""); testData.getUserInfoList().add(new UserInfo("", null)); testData.getUserInfoList().get(0).addField( new UserInfoField("Todd", "Todd", "", false, field -> {})); @@ -151,7 +151,7 @@ public void testUsesTitleElementForEmptyState() { final PropertyProvider<AccessorySheetData> testProvider = new PropertyProvider<>(); final AccessorySheetData testData = - new AccessorySheetData(AccessoryTabType.CREDIT_CARDS, "Payments"); + new AccessorySheetData(AccessoryTabType.CREDIT_CARDS, "Payments", ""); mCoordinator.registerDataProvider(testProvider); testProvider.notifyObservers(testData); @@ -184,7 +184,7 @@ // If the tab is shown without interactive item, log "0" samples. AccessorySheetData accessorySheetData = - new AccessorySheetData(AccessoryTabType.CREDIT_CARDS, "Payments"); + new AccessorySheetData(AccessoryTabType.CREDIT_CARDS, "Payments", ""); testProvider.notifyObservers(accessorySheetData); mCoordinator.onTabShown(); @@ -204,7 +204,7 @@ // Add only two interactive items - the third one should not be recorded. AccessorySheetData accessorySheetData = - new AccessorySheetData(AccessoryTabType.CREDIT_CARDS, "Payments"); + new AccessorySheetData(AccessoryTabType.CREDIT_CARDS, "Payments", ""); accessorySheetData.getUserInfoList().add(new UserInfo("", null)); accessorySheetData.getUserInfoList().get(0).addField( new UserInfoField("Todd Tester", "Todd Tester", "0", false, result -> {}));
diff --git a/chrome/android/features/keyboard_accessory/junit/src/org/chromium/chrome/browser/keyboard_accessory/sheet_tabs/PasswordAccessorySheetControllerTest.java b/chrome/android/features/keyboard_accessory/junit/src/org/chromium/chrome/browser/keyboard_accessory/sheet_tabs/PasswordAccessorySheetControllerTest.java index f2d01868..d2f3895 100644 --- a/chrome/android/features/keyboard_accessory/junit/src/org/chromium/chrome/browser/keyboard_accessory/sheet_tabs/PasswordAccessorySheetControllerTest.java +++ b/chrome/android/features/keyboard_accessory/junit/src/org/chromium/chrome/browser/keyboard_accessory/sheet_tabs/PasswordAccessorySheetControllerTest.java
@@ -110,13 +110,13 @@ // If the coordinator receives a set of initial items, the model should report an insertion. testProvider.notifyObservers( - new AccessorySheetData(AccessoryTabType.PASSWORDS, "Passwords")); + new AccessorySheetData(AccessoryTabType.PASSWORDS, "Passwords", "")); verify(mMockItemListObserver).onItemRangeInserted(mSheetDataPieces, 0, 1); assertThat(mSheetDataPieces.size(), is(1)); // If the coordinator receives a new set of items, the model should report a change. testProvider.notifyObservers( - new AccessorySheetData(AccessoryTabType.PASSWORDS, "Other Passwords")); + new AccessorySheetData(AccessoryTabType.PASSWORDS, "Other Passwords", "")); verify(mMockItemListObserver).onItemRangeChanged(mSheetDataPieces, 0, 1, null); assertThat(mSheetDataPieces.size(), is(1)); @@ -135,7 +135,7 @@ setAutofillFeature(false); final PropertyProvider<AccessorySheetData> testProvider = new PropertyProvider<>(); final AccessorySheetData testData = - new AccessorySheetData(AccessoryTabType.PASSWORDS, "Passwords for this site"); + new AccessorySheetData(AccessoryTabType.PASSWORDS, "Passwords for this site", ""); testData.getUserInfoList().add(new UserInfo("", null)); testData.getUserInfoList().get(0).addField( new UserInfoField("Name", "Name", "", false, null)); @@ -160,7 +160,7 @@ setAutofillFeature(true); final PropertyProvider<AccessorySheetData> testProvider = new PropertyProvider<>(); final AccessorySheetData testData = - new AccessorySheetData(AccessoryTabType.PASSWORDS, "No passwords for this"); + new AccessorySheetData(AccessoryTabType.PASSWORDS, "No passwords for this", ""); mCoordinator.registerDataProvider(testProvider); // Providing only FooterCommands and no User Info shows the title as empty state: @@ -207,7 +207,7 @@ // If the tab is shown without interactive item, log "0" samples. AccessorySheetData accessorySheetData = - new AccessorySheetData(AccessoryTabType.PASSWORDS, "No passwords!"); + new AccessorySheetData(AccessoryTabType.PASSWORDS, "No passwords!", ""); accessorySheetData.getFooterCommands().add(new FooterCommand("Manage all passwords", null)); accessorySheetData.getFooterCommands().add(new FooterCommand("Generate password", null)); testProvider.notifyObservers(accessorySheetData);
diff --git a/chrome/android/features/keyboard_accessory/public/java/src/org/chromium/chrome/browser/keyboard_accessory/data/KeyboardAccessoryData.java b/chrome/android/features/keyboard_accessory/public/java/src/org/chromium/chrome/browser/keyboard_accessory/data/KeyboardAccessoryData.java index 4f9c350f7..b17600a9 100644 --- a/chrome/android/features/keyboard_accessory/public/java/src/org/chromium/chrome/browser/keyboard_accessory/data/KeyboardAccessoryData.java +++ b/chrome/android/features/keyboard_accessory/public/java/src/org/chromium/chrome/browser/keyboard_accessory/data/KeyboardAccessoryData.java
@@ -267,6 +267,7 @@ */ public final static class AccessorySheetData { private final String mTitle; + private final String mWarning; private final @AccessoryTabType int mSheetType; private final List<UserInfo> mUserInfoList = new ArrayList<>(); private final List<FooterCommand> mFooterCommands = new ArrayList<>(); @@ -274,10 +275,12 @@ /** * Creates the AccessorySheetData object. * @param title The title of accessory sheet tab. + * @param warning An optional warning to be displayed the beginning of the sheet. */ - public AccessorySheetData(@AccessoryTabType int sheetType, String title) { + public AccessorySheetData(@AccessoryTabType int sheetType, String title, String warning) { mSheetType = sheetType; mTitle = title; + mWarning = warning; } public @AccessoryTabType int getSheetType() { @@ -292,6 +295,13 @@ } /** + * Returns a warning to be displayed at the beginning of the sheet. Empty string otherwise. + */ + public String getWarning() { + return mWarning; + } + + /** * Returns the list of {@link UserInfo} to be shown on the accessory sheet. */ public List<UserInfo> getUserInfoList() {
diff --git a/chrome/android/java/res/values-v17/styles.xml b/chrome/android/java/res/values-v17/styles.xml index 26c624d..5ba4933 100644 --- a/chrome/android/java/res/values-v17/styles.xml +++ b/chrome/android/java/res/values-v17/styles.xml
@@ -972,7 +972,7 @@ <style name="OmniboxIcon" parent="LocationBarButton"> <item name="android:layout_width">@dimen/location_bar_start_icon_width</item> <item name="android:layout_height">match_parent</item> - <item name="android:layout_marginEnd">4dp</item> + <item name="android:layout_marginEnd">@dimen/location_bar_start_icon_margin_end</item> </style> <!-- Revamped context menu -->
diff --git a/chrome/android/java/res/values/dimens.xml b/chrome/android/java/res/values/dimens.xml index e13571c..7665b6f 100644 --- a/chrome/android/java/res/values/dimens.xml +++ b/chrome/android/java/res/values/dimens.xml
@@ -271,6 +271,7 @@ <dimen name="location_bar_icon_width">28dp</dimen> <dimen name="location_bar_action_icon_width">48dp</dimen> <dimen name="location_bar_start_icon_width">28dp</dimen> + <dimen name="location_bar_start_icon_margin_end">4dp</dimen> <dimen name="location_bar_lateral_padding">10dp</dimen> <!-- When the url action container is shown, the location bar end padding is built in to its actions, so the action container itself uses a negative offset to properly align with the end
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/ChromeFeatureList.java b/chrome/android/java/src/org/chromium/chrome/browser/ChromeFeatureList.java index f6232208..48343ca 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/ChromeFeatureList.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/ChromeFeatureList.java
@@ -322,7 +322,6 @@ public static final String TAB_SWITCHER_ON_RETURN = "TabSwitcherOnReturn"; public static final String TAB_TO_GTS_ANIMATION = "TabToGTSAnimation"; public static final String TOUCH_TO_FILL_ANDROID = "TouchToFillAndroid"; - public static final String TRANSLATE_ANDROID_MANUAL_TRIGGER = "TranslateAndroidManualTrigger"; public static final String TRUSTED_WEB_ACTIVITY = "TrustedWebActivity"; public static final String TRUSTED_WEB_ACTIVITY_POST_MESSAGE = "TrustedWebActivityPostMessage"; public static final String TRUSTED_WEB_ACTIVITY_NOTIFICATION_DELEGATION_ENROLMENT =
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/appmenu/AppMenuPropertiesDelegateImpl.java b/chrome/android/java/src/org/chromium/chrome/browser/appmenu/AppMenuPropertiesDelegateImpl.java index 812a662..40fa650 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/appmenu/AppMenuPropertiesDelegateImpl.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/appmenu/AppMenuPropertiesDelegateImpl.java
@@ -25,7 +25,6 @@ import org.chromium.base.metrics.RecordHistogram; import org.chromium.chrome.R; import org.chromium.chrome.browser.ActivityTabProvider; -import org.chromium.chrome.browser.ChromeFeatureList; import org.chromium.chrome.browser.ChromeSwitches; import org.chromium.chrome.browser.ShortcutHelper; import org.chromium.chrome.browser.banners.AppBannerManager; @@ -343,12 +342,8 @@ */ protected void prepareTranslateMenuItem(Menu menu, Tab currentTab) { boolean isTranslateVisible = isTranslateMenuItemVisible(currentTab); - if (ChromeFeatureList.isInitialized() - && ChromeFeatureList.isEnabled( - ChromeFeatureList.TRANSLATE_ANDROID_MANUAL_TRIGGER)) { - RecordHistogram.recordBooleanHistogram( - "Translate.MobileMenuTranslate.Shown", isTranslateVisible); - } + RecordHistogram.recordBooleanHistogram( + "Translate.MobileMenuTranslate.Shown", isTranslateVisible); menu.findItem(R.id.translate_id).setVisible(isTranslateVisible); } @@ -481,8 +476,6 @@ boolean isFileScheme = url.startsWith(UrlConstants.FILE_URL_PREFIX); boolean isContentScheme = url.startsWith(UrlConstants.CONTENT_URL_PREFIX); return !isChromeScheme && !isFileScheme && !isContentScheme && !TextUtils.isEmpty(url) - && tab.getWebContents() != null && ChromeFeatureList.isInitialized() - && ChromeFeatureList.isEnabled(ChromeFeatureList.TRANSLATE_ANDROID_MANUAL_TRIGGER) - && TranslateBridge.canManuallyTranslate(tab); + && tab.getWebContents() != null && TranslateBridge.canManuallyTranslate(tab); } }
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/omnibox/LocationBarLayout.java b/chrome/android/java/src/org/chromium/chrome/browser/omnibox/LocationBarLayout.java index 378c86a..d76a745 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/omnibox/LocationBarLayout.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/omnibox/LocationBarLayout.java
@@ -43,6 +43,7 @@ import org.chromium.chrome.browser.omnibox.UrlBar.ScrollType; import org.chromium.chrome.browser.omnibox.UrlBarCoordinator.SelectionState; import org.chromium.chrome.browser.omnibox.geo.GeolocationHeader; +import org.chromium.chrome.browser.omnibox.status.StatusView; import org.chromium.chrome.browser.omnibox.status.StatusViewCoordinator; import org.chromium.chrome.browser.omnibox.suggestions.AutocompleteCoordinator; import org.chromium.chrome.browser.omnibox.suggestions.AutocompleteCoordinatorFactory; @@ -56,6 +57,7 @@ import org.chromium.chrome.browser.toolbar.ToolbarDataProvider; import org.chromium.chrome.browser.toolbar.ToolbarManager; import org.chromium.chrome.browser.toolbar.top.ToolbarActionModeCallback; +import org.chromium.chrome.browser.ui.widget.CompositeTouchDelegate; import org.chromium.chrome.browser.util.AccessibilityUtil; import org.chromium.chrome.browser.util.ColorUtils; import org.chromium.components.search_engines.TemplateUrlService; @@ -111,6 +113,8 @@ protected LocationBarVoiceRecognitionHandler mVoiceRecognitionHandler; + protected CompositeTouchDelegate mCompositeTouchDelegate; + /** * Class to handle input from a hardware keyboard when the focus is on the URL bar. In * particular, handle navigating the suggestions list from the keyboard. @@ -144,6 +148,9 @@ public LocationBarLayout(Context context, AttributeSet attrs) { this(context, attrs, R.layout.location_bar); + + mCompositeTouchDelegate = new CompositeTouchDelegate(this); + setTouchDelegate(mCompositeTouchDelegate); } public LocationBarLayout(Context context, AttributeSet attrs, int layoutId) { @@ -207,8 +214,9 @@ setLayoutTransition(null); - mStatusViewCoordinator = - new StatusViewCoordinator(mIsTablet, findViewById(R.id.location_bar_status)); + StatusView statusView = findViewById(R.id.location_bar_status); + statusView.setCompositeTouchDelegate(mCompositeTouchDelegate); + mStatusViewCoordinator = new StatusViewCoordinator(mIsTablet, statusView); updateShouldAnimateIconChanges(); mUrlBar.setOnKeyListener(new UrlBarKeyListener());
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/omnibox/LocationBarPhone.java b/chrome/android/java/src/org/chromium/chrome/browser/omnibox/LocationBarPhone.java index d8619ae1..b220c0b 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/omnibox/LocationBarPhone.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/omnibox/LocationBarPhone.java
@@ -49,7 +49,7 @@ delegateArea.left -= ACTION_BUTTON_TOUCH_OVERFLOW_LEFT; TouchDelegate touchDelegate = new TouchDelegate(delegateArea, mUrlActionContainer); assert mUrlActionContainer.getParent() == this; - setTouchDelegate(touchDelegate); + mCompositeTouchDelegate.addDelegateForDescendantView(touchDelegate); } /**
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/omnibox/status/StatusView.java b/chrome/android/java/src/org/chromium/chrome/browser/omnibox/status/StatusView.java index 6dc3054..4a1e09f 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/omnibox/status/StatusView.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/omnibox/status/StatusView.java
@@ -8,6 +8,7 @@ import android.content.Context; import android.graphics.Bitmap; +import android.graphics.Rect; import android.graphics.drawable.BitmapDrawable; import android.graphics.drawable.Drawable; import android.graphics.drawable.TransitionDrawable; @@ -18,6 +19,7 @@ import android.support.v4.view.ViewCompat; import android.support.v7.content.res.AppCompatResources; import android.util.AttributeSet; +import android.view.TouchDelegate; import android.view.View; import android.view.ViewStub; import android.widget.ImageView; @@ -26,6 +28,7 @@ import org.chromium.base.ApiCompatibilityUtils; import org.chromium.chrome.R; +import org.chromium.chrome.browser.ui.widget.CompositeTouchDelegate; import org.chromium.chrome.browser.util.AccessibilityUtil; import org.chromium.ui.UiUtils; @@ -36,6 +39,8 @@ private @Nullable View mIncognitoBadge; private int mIncognitoBadgeEndPaddingWithIcon; private int mIncognitoBadgeEndPaddingWithoutIcon; + private int mTouchDelegateStartOffset; + private int mTouchDelegateEndOffset; private ImageView mIconView; private TextView mVerboseStatusTextView; @@ -52,6 +57,12 @@ private Bitmap mIconBitmap; + private TouchDelegate mTouchDelegate; + private CompositeTouchDelegate mCompositeTouchDelegate; + + private boolean mLastTouchDelegateRtlness; + private Rect mLastTouchDelegateRect; + public StatusView(Context context, AttributeSet attributes) { super(context, attributes); } @@ -61,6 +72,9 @@ super.onFinishInflate(); mIconView = findViewById(R.id.location_bar_status_icon); + mIconView.addOnLayoutChangeListener((v, left, top, right, bottom, oldLeft, oldTop, oldRight, + oldBottom) -> updateTouchDelegate()); + mVerboseStatusTextView = findViewById(R.id.location_bar_verbose_status); mSeparatorView = findViewById(R.id.location_bar_verbose_status_separator); mStatusExtraSpace = findViewById(R.id.location_bar_verbose_status_extra_space); @@ -69,6 +83,14 @@ } /** + * Set the composite touch delegate here to which this view's touch delegate will be added. + * @param compositeTouchDelegate The parent's CompositeTouchDelegate to be used. + */ + public void setCompositeTouchDelegate(CompositeTouchDelegate compositeTouchDelegate) { + mCompositeTouchDelegate = compositeTouchDelegate; + } + + /** * Start animating transition of status icon. */ private void animateStatusIcon() { @@ -121,7 +143,11 @@ mIconView.animate() .alpha(1.0f) .setDuration(URL_FOCUS_CHANGE_ANIMATION_DURATION_MS) - .withEndAction(() -> { mAnimatingStatusIconShow = false; }) + .withEndAction(() -> { + mAnimatingStatusIconShow = false; + // Wait until the icon is visible so the bounds will be properly set. + updateTouchDelegate(); + }) .start(); } else if (wantIconHidden && (!isIconHidden || mAnimatingStatusIconShow)) { // Action 2: animate hiding, if icon was either shown or showing. @@ -164,6 +190,10 @@ newImage.setCrossFadeEnabled(true); newImage.startTransition( mAnimationsEnabled ? URL_FOCUS_CHANGE_ANIMATION_DURATION_MS : 0); + + // Update the touch delegate only if the icons are swapped without animating the + // image view. + if (!mAnimatingStatusIconShow) updateTouchDelegate(); } else { mIconView.setImageDrawable(targetIcon); } @@ -327,6 +357,52 @@ mIncognitoBadge.getPaddingBottom()); } + /** + * Create a touch delegate to expand the clickable area for the padlock icon (see + * crbug.com/970031 for motivation/info). This method will be called when the icon is animating + * in and when layout changes. It's called on these intervals because (1) the layout could + * change and (2) the Rtl-ness of the view could change. There are checks in place to avoid + * doing unnecessary work, so if the rect is empty or equivalent to the one already in place, + * no work will be done. + */ + private void updateTouchDelegate() { + // Setup a touch delegate to increase the clickable area for the padlock. + // See for more information. + Rect touchDelegateBounds = new Rect(); + mIconView.getHitRect(touchDelegateBounds); + if (touchDelegateBounds.equals(new Rect())) return; + + boolean isRtl = getLayoutDirection() == LAYOUT_DIRECTION_RTL; + if (mTouchDelegateStartOffset == 0) { + mTouchDelegateStartOffset = + getResources().getDimensionPixelSize(R.dimen.location_bar_lateral_padding); + } + if (mTouchDelegateEndOffset == 0) { + mTouchDelegateEndOffset = getResources().getDimensionPixelSize( + R.dimen.location_bar_start_icon_margin_end); + } + touchDelegateBounds.left -= isRtl ? mTouchDelegateEndOffset : mTouchDelegateStartOffset; + touchDelegateBounds.right += isRtl ? mTouchDelegateStartOffset : mTouchDelegateEndOffset; + + // If our rect and rtl-ness hasn't changed, there's no need to recreate the TouchDelegate. + if (mTouchDelegate != null && touchDelegateBounds.equals(mLastTouchDelegateRect) + && mLastTouchDelegateRtlness == isRtl) { + return; + } + mLastTouchDelegateRect = touchDelegateBounds; + + // Remove the existing delegate when we recreate a new one. + if (mTouchDelegate != null) { + mCompositeTouchDelegate.removeDelegateForDescendantView(mTouchDelegate); + } + + // Set the delegate on LocationBarLayout because it has available space. Setting on + // status view itself will clip the rect. + mTouchDelegate = new TouchDelegate(touchDelegateBounds, mIconView); + mCompositeTouchDelegate.addDelegateForDescendantView(mTouchDelegate); + mLastTouchDelegateRtlness = isRtl; + } + // TODO(ender): The final last purpose of this method is to allow // ToolbarButtonInProductHelpController set up help bubbles. This dependency is about to // change. Do not depend on this method when creating new code.
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/payments/JourneyLogger.java b/chrome/android/java/src/org/chromium/chrome/browser/payments/JourneyLogger.java index a4aae254..16aac3c 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/payments/JourneyLogger.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/payments/JourneyLogger.java
@@ -195,6 +195,13 @@ nativeRecordTransactionAmount(mJourneyLoggerAndroid, currency, value, completed); } + /** + * Records the time when request.show() is called. + */ + public void setTriggerTime() { + nativeSetTriggerTime(mJourneyLoggerAndroid); + } + private native long nativeInitJourneyLoggerAndroid( boolean isIncognito, WebContents webContents); private native void nativeDestroy(long nativeJourneyLoggerAndroid); @@ -220,4 +227,5 @@ private native void nativeSetNotShown(long nativeJourneyLoggerAndroid, int reason); private native void nativeRecordTransactionAmount( long nativeJourneyLoggerAndroid, String currency, String value, boolean completed); + private native void nativeSetTriggerTime(long nativeJourneyLoggerAndroid); }
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/payments/PaymentRequestImpl.java b/chrome/android/java/src/org/chromium/chrome/browser/payments/PaymentRequestImpl.java index 4986a37..0479aa5 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/payments/PaymentRequestImpl.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/payments/PaymentRequestImpl.java
@@ -763,6 +763,7 @@ } mIsCurrentPaymentRequestShowing = true; + mJourneyLogger.setTriggerTime(); if (disconnectIfNoPaymentMethodsSupported()) return; ChromeActivity chromeActivity = ChromeActivity.fromWebContents(mWebContents); @@ -1683,7 +1684,7 @@ if (mInvokedPaymentInstrument instanceof ServiceWorkerPaymentApp) { if (mPaymentHandlerHost == null) { - mPaymentHandlerHost = new PaymentHandlerHost(this /* delegate */); + mPaymentHandlerHost = new PaymentHandlerHost(mWebContents, this /* delegate */); } ((ServiceWorkerPaymentApp) mInvokedPaymentInstrument)
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/preferences/password/PasswordEntryEditor.java b/chrome/android/java/src/org/chromium/chrome/browser/preferences/password/PasswordEntryEditor.java index 74b1f38..d981e1d 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/preferences/password/PasswordEntryEditor.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/preferences/password/PasswordEntryEditor.java
@@ -9,6 +9,7 @@ import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuInflater; +import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.EditText; @@ -19,6 +20,9 @@ * Password entry editor that allows editing passwords stored in Chrome. */ public class PasswordEntryEditor extends Fragment { + // ID of this name/password or exception. + private int mID; + private EditText mSiteText; private EditText mUsernameText; private EditText mPasswordText; @@ -36,10 +40,10 @@ public void onViewCreated(View view, Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); // Editing action in PasswordEntryViewer sets extras and launches PasswordEntryEditor. + mID = getArguments().getInt(SavePasswordsPreferences.PASSWORD_LIST_ID); mSavedPasswordEntry = PasswordManagerHandlerProvider.getInstance() .getPasswordManagerHandler() - .getSavedPasswordEntry(getArguments().getInt( - SavePasswordsPreferences.PASSWORD_LIST_ID)); + .getSavedPasswordEntry(mID); mSiteText = (EditText) view.findViewById(R.id.site_edit); mUsernameText = (EditText) view.findViewById(R.id.username_edit); mPasswordText = (EditText) view.findViewById(R.id.password_edit); @@ -52,4 +56,18 @@ public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { inflater.inflate(R.menu.password_entry_editor_action_bar_menu, menu); } + + @Override + public boolean onOptionsItemSelected(MenuItem item) { + int id = item.getItemId(); + if (id == R.id.action_save_edited_password) { + PasswordManagerHandlerProvider.getInstance() + .getPasswordManagerHandler() + .changeSavedPasswordEntry(mID, mUsernameText.getText().toString(), + mPasswordText.getText().toString()); + getActivity().finish(); + return true; + } + return super.onOptionsItemSelected(item); + } } \ No newline at end of file
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/preferences/password/PasswordEntryViewer.java b/chrome/android/java/src/org/chromium/chrome/browser/preferences/password/PasswordEntryViewer.java index 9ef6c10..5199061 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/preferences/password/PasswordEntryViewer.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/preferences/password/PasswordEntryViewer.java
@@ -10,6 +10,7 @@ import android.content.Intent; import android.net.Uri; import android.os.Bundle; +import android.support.annotation.IdRes; import android.support.annotation.StringRes; import android.support.v4.app.Fragment; import android.support.v7.content.res.AppCompatResources; @@ -44,7 +45,8 @@ /** * Password entry viewer that allows to view and delete passwords stored in Chrome. */ -public class PasswordEntryViewer extends Fragment { +public class PasswordEntryViewer + extends Fragment implements PasswordManagerHandler.PasswordListObserver { // Constants used to log UMA enum histogram, must stay in sync with // PasswordManagerAndroidPasswordEntryActions. Further actions can only be appended, existing // entries must not be overwritten. @@ -123,20 +125,15 @@ getActivity().setTitle(R.string.password_entry_viewer_title); mClipboard = (ClipboardManager) getActivity().getApplicationContext().getSystemService( Context.CLIPBOARD_SERVICE); - View urlRowsView = mView.findViewById(R.id.url_row); - TextView dataView = urlRowsView.findViewById(R.id.password_entry_viewer_row_data); - dataView.setText(url); + setRowText(R.id.url_row, url); mView.getViewTreeObserver().addOnScrollChangedListener( PreferenceUtils.getShowShadowOnScrollListener( mView, inflatedView.findViewById(R.id.shadow))); - hookupCopySiteButton(urlRowsView); + hookupCopySiteButton(mView.findViewById(R.id.url_row)); if (!mException) { - View usernameView = mView.findViewById(R.id.username_row); - TextView usernameDataView = - usernameView.findViewById(R.id.password_entry_viewer_row_data); - usernameDataView.setText(name); - hookupCopyUsernameButton(usernameView); + setRowText(R.id.username_row, name); + hookupCopyUsernameButton(mView.findViewById(R.id.username_row)); if (ReauthenticationManager.isReauthenticationApiAvailable()) { hidePassword(); hookupPasswordButtons(); @@ -186,6 +183,7 @@ "PasswordManager.Android.PasswordExceptionEntry", PASSWORD_ENTRY_ACTION_VIEWED, PASSWORD_ENTRY_ACTION_BOUNDARY); } + PasswordManagerHandlerProvider.getInstance().addObserver(this); return inflatedView; } @@ -200,6 +198,12 @@ } } + @Override + public void onDestroy() { + super.onDestroy(); + PasswordManagerHandlerProvider.getInstance().removeObserver(this); + } + private boolean isPasswordSyncingUser() { ProfileSyncService syncService = ProfileSyncService.get(); return (AndroidSyncSettings.get().isSyncEnabled() && syncService.isEngineInitialized() @@ -416,4 +420,24 @@ } }); } + + private void setRowText(@IdRes int rowId, String text) { + View rowView = mView.findViewById(rowId); + TextView dataView = rowView.findViewById(R.id.password_entry_viewer_row_data); + dataView.setText(text); + } + + @Override + public void passwordListAvailable(int count) { + TextView passwordsLinkTextView = mView.findViewById(R.id.passwords_link); + SavedPasswordEntry SavedPasswordEntry = PasswordManagerHandlerProvider.getInstance() + .getPasswordManagerHandler() + .getSavedPasswordEntry(mID); + setRowText(R.id.url_row, SavedPasswordEntry.getUrl()); + setRowText(R.id.username_row, SavedPasswordEntry.getUserName()); + passwordsLinkTextView.setText(SavedPasswordEntry.getPassword()); + } + + @Override + public void passwordExceptionListAvailable(int count) {} }
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/signin/IdentityServicesProvider.java b/chrome/android/java/src/org/chromium/chrome/browser/signin/IdentityServicesProvider.java index 0e0bd46..428669cd 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/signin/IdentityServicesProvider.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/signin/IdentityServicesProvider.java
@@ -5,38 +5,56 @@ package org.chromium.chrome.browser.signin; import org.chromium.base.ThreadUtils; +import org.chromium.base.annotations.NativeMethods; import org.chromium.chrome.browser.profiles.Profile; import org.chromium.components.signin.AccountTrackerService; import org.chromium.components.signin.OAuth2TokenService; +import org.chromium.components.signin.identitymanager.IdentityManager; /** * Provides access to sign-in related services that are profile-keyed on the native side. Java * equivalent of AccountTrackerServiceFactory and similar classes. */ public final class IdentityServicesProvider { + /** Getter for {@link IdentityManager} instance. */ + public static IdentityManager getIdentityManager() { + ThreadUtils.assertOnUiThread(); + IdentityManager result = + IdentityServicesProviderJni.get().getIdentityManager(Profile.getLastUsedProfile()); + assert result != null; + return result; + } + /** Getter for {@link AccountTrackerService} instance. */ public static AccountTrackerService getAccountTrackerService() { ThreadUtils.assertOnUiThread(); - AccountTrackerService result = nativeGetAccountTrackerService(Profile.getLastUsedProfile()); + AccountTrackerService result = IdentityServicesProviderJni.get().getAccountTrackerService( + Profile.getLastUsedProfile()); assert result != null; return result; } public static OAuth2TokenService getOAuth2TokenService() { ThreadUtils.assertOnUiThread(); - OAuth2TokenService result = nativeGetOAuth2TokenService(Profile.getLastUsedProfile()); + OAuth2TokenService result = IdentityServicesProviderJni.get().getOAuth2TokenService( + Profile.getLastUsedProfile()); assert result != null; return result; } public static SigninManager getSigninManager() { ThreadUtils.assertOnUiThread(); - SigninManager result = nativeGetSigninManager(Profile.getLastUsedProfile()); + SigninManager result = + IdentityServicesProviderJni.get().getSigninManager(Profile.getLastUsedProfile()); assert result != null; return result; } - private static native AccountTrackerService nativeGetAccountTrackerService(Profile profile); - private static native OAuth2TokenService nativeGetOAuth2TokenService(Profile profile); - private static native SigninManager nativeGetSigninManager(Profile profile); + @NativeMethods + interface Natives { + public IdentityManager getIdentityManager(Profile profile); + public AccountTrackerService getAccountTrackerService(Profile profile); + public OAuth2TokenService getOAuth2TokenService(Profile profile); + public SigninManager getSigninManager(Profile profile); + } }
diff --git a/chrome/android/javatests/src/org/chromium/chrome/browser/payments/PaymentRequestJourneyLoggerTest.java b/chrome/android/javatests/src/org/chromium/chrome/browser/payments/PaymentRequestJourneyLoggerTest.java index 64172def..11a8c07 100644 --- a/chrome/android/javatests/src/org/chromium/chrome/browser/payments/PaymentRequestJourneyLoggerTest.java +++ b/chrome/android/javatests/src/org/chromium/chrome/browser/payments/PaymentRequestJourneyLoggerTest.java
@@ -91,6 +91,15 @@ R.id.card_unmask_input, "123", mPaymentRequestTestRule.getReadyToUnmask()); mPaymentRequestTestRule.clickCardUnmaskButtonAndWait( ModalDialogProperties.ButtonType.POSITIVE, mPaymentRequestTestRule.getDismissed()); + Assert.assertEquals(1, + RecordHistogram.getHistogramTotalCountForTesting( + "PaymentRequest.TimeToCheckout.Completed")); + Assert.assertEquals(1, + RecordHistogram.getHistogramTotalCountForTesting( + "PaymentRequest.TimeToCheckout.Completed.Shown")); + Assert.assertEquals(1, + RecordHistogram.getHistogramTotalCountForTesting( + "PaymentRequest.TimeToCheckout.Completed.Shown.BasicCard")); // Make sure the right number of suggestions were logged. Assert.assertEquals(1, @@ -127,6 +136,13 @@ // Wait for the histograms to be logged. Thread.sleep(200); + Assert.assertEquals(1, + RecordHistogram.getHistogramTotalCountForTesting( + "PaymentRequest.TimeToCheckout.UserAborted")); + Assert.assertEquals(1, + RecordHistogram.getHistogramTotalCountForTesting( + "PaymentRequest.TimeToCheckout.UserAborted.Shown")); + // Make sure the right number of suggestions were logged. Assert.assertEquals(1, RecordHistogram.getHistogramValueCountForTesting(
diff --git a/chrome/android/javatests/src/org/chromium/chrome/browser/payments/PaymentRequestMetricsTest.java b/chrome/android/javatests/src/org/chromium/chrome/browser/payments/PaymentRequestMetricsTest.java index fe78069..2a7a171 100644 --- a/chrome/android/javatests/src/org/chromium/chrome/browser/payments/PaymentRequestMetricsTest.java +++ b/chrome/android/javatests/src/org/chromium/chrome/browser/payments/PaymentRequestMetricsTest.java
@@ -485,6 +485,15 @@ Assert.assertEquals(1, RecordHistogram.getHistogramValueCountForTesting( "PaymentRequest.Events", expectedSample)); + Assert.assertEquals(1, + RecordHistogram.getHistogramTotalCountForTesting( + "PaymentRequest.TimeToCheckout.Completed")); + Assert.assertEquals(1, + RecordHistogram.getHistogramTotalCountForTesting( + "PaymentRequest.TimeToCheckout.Completed.SkippedShow")); + Assert.assertEquals(1, + RecordHistogram.getHistogramTotalCountForTesting( + "PaymentRequest.TimeToCheckout.Completed.SkippedShow.Google")); } /**
diff --git a/chrome/android/javatests/src/org/chromium/chrome/browser/preferences/password/SavePasswordsPreferencesTest.java b/chrome/android/javatests/src/org/chromium/chrome/browser/preferences/password/SavePasswordsPreferencesTest.java index e4adde6b..0da0f517 100644 --- a/chrome/android/javatests/src/org/chromium/chrome/browser/preferences/password/SavePasswordsPreferencesTest.java +++ b/chrome/android/javatests/src/org/chromium/chrome/browser/preferences/password/SavePasswordsPreferencesTest.java
@@ -48,8 +48,10 @@ import android.content.IntentFilter; import android.graphics.ColorFilter; import android.graphics.drawable.Drawable; +import android.support.annotation.IdRes; import android.support.annotation.IntDef; import android.support.annotation.Nullable; +import android.support.annotation.StringRes; import android.support.test.InstrumentationRegistry; import android.support.test.espresso.Espresso; import android.support.test.espresso.intent.Intents; @@ -187,7 +189,10 @@ @Override public void changeSavedPasswordEntry(int index, String newUsername, String newPassword) { - assert false : "Define this method before starting to use it in tests."; + mSavedPasswords.set(index, + new SavedPasswordEntry( + mSavedPasswords.get(index).getUrl(), newUsername, newPassword)); + updatePasswordLists(); } @Override @@ -301,38 +306,45 @@ } /** - * Looks for the search icon by id. If it cannot be found, it's probably hidden in the overflow + * Looks for the icon by id. If it cannot be found, it's probably hidden in the overflow * menu. In that case, open the menu and search for its title. - * @return Returns either the search icon button or the search menu option. + * @return Returns either the icon button or the menu option. */ - public static Matcher<View> withSearchMenuIdOrText() { - Matcher<View> matcher = withId(R.id.menu_id_search); + public static Matcher<View> withMenuIdOrText(@IdRes int actionId, @StringRes int actionLabel) { + Matcher<View> matcher = withId(actionId); try { Espresso.onView(matcher).check(matches(isDisplayed())); return matcher; } catch (Exception NoMatchingViewException) { openActionBarOverflowOrOptionsMenu( InstrumentationRegistry.getInstrumentation().getTargetContext()); - return withText(R.string.search); + return withText(actionLabel); } } /** - * Looks for the edit saved password icon by id. If it cannot be found, it's probably hidden in - * the overflow menu. In that case, open the menu and search for its title. - * @return Returns either the edit saved password icon button or the edit saved password menu - * option. + * Looks for the search icon by id or by its title. + * @return Returns either the icon button or the menu option. + */ + public static Matcher<View> withSearchMenuIdOrText() { + return withMenuIdOrText(R.id.menu_id_search, R.string.search); + } + + /** + * Looks for the edit saved password icon by id or by its title. + * @return Returns either the icon button or the menu option. */ public static Matcher<View> withEditMenuIdOrText() { - Matcher<View> matcher = withId(R.id.action_edit_saved_password); - try { - Espresso.onView(matcher).check(matches(isDisplayed())); - return matcher; - } catch (Exception NoMatchingViewException) { - openActionBarOverflowOrOptionsMenu( - InstrumentationRegistry.getInstrumentation().getTargetContext()); - return withText(R.string.password_entry_viewer_edit_stored_password_action_title); - } + return withMenuIdOrText(R.id.action_edit_saved_password, + R.string.password_entry_viewer_edit_stored_password_action_title); + } + + /** + * Looks for the save edited password icon by id or by its title. + * @return Returns either the icon button or the menu option. + */ + public static Matcher<View> withSaveMenuIdOrText() { + return withMenuIdOrText(R.id.action_save_edited_password, R.string.save); } /** @@ -683,6 +695,37 @@ } /** + * Check that the changes of password data in the password editing activity are preserved and + * shown in the password viewing activity and in the list of passwords after the save button + * was clicked. + */ + @Test + @SmallTest + @Feature({"Preferences"}) + @Features.EnableFeatures(ChromeFeatureList.PASSWORD_EDITING_ANDROID) + public void testChangeOfStoredPasswordDataIsPreserved() throws Exception { + setPasswordSource(new SavedPasswordEntry("https://example.com", "test user", "password")); + + PreferencesTest.startPreferences(InstrumentationRegistry.getInstrumentation(), + SavePasswordsPreferences.class.getName()); + + Espresso.onView(withText(containsString("test user"))).perform(click()); + + Espresso.onView(withEditMenuIdOrText()).perform(click()); + + Espresso.onView(withId(R.id.username_edit)).perform(typeText(" new")); + + Espresso.onView(withSaveMenuIdOrText()).perform(click()); + + // Check if the password viewing activity has the updated data. + Espresso.onView(withText("test user new")).check(matches(isDisplayed())); + + Espresso.pressBack(); + // Check if the password preferences activity has the updated data in the list of passwords. + Espresso.onView(withText("test user new")).check(matches(isDisplayed())); + } + + /** * Check that if there are no saved passwords, the export menu item is disabled. */ @Test
diff --git a/chrome/android/profiles/newest.txt b/chrome/android/profiles/newest.txt index 384e76e1..e18a782 100644 --- a/chrome/android/profiles/newest.txt +++ b/chrome/android/profiles/newest.txt
@@ -1 +1 @@ -chromeos-chrome-amd64-78.0.3877.0_rc-r1-merged.afdo.bz2 \ No newline at end of file +chromeos-chrome-amd64-77.0.3864.0_rc-r1-merged.afdo.bz2 \ No newline at end of file
diff --git a/chrome/browser/about_flags.cc b/chrome/browser/about_flags.cc index faa3a23..4c173e4f 100644 --- a/chrome/browser/about_flags.cc +++ b/chrome/browser/about_flags.cc
@@ -1512,7 +1512,7 @@ FEATURE_VALUE_TYPE( chromeos::features::kBluetoothAggressiveAppearanceFilter)}, {"cryptauth-v2-enrollment", flag_descriptions::kCryptAuthV2EnrollmentName, - flag_descriptions::kCryptAuthV2EnrollmentDescription, kOsCrOS | kExpireM77, + flag_descriptions::kCryptAuthV2EnrollmentDescription, kOsCrOS, FEATURE_VALUE_TYPE(chromeos::features::kCryptAuthV2Enrollment)}, {"updated_cellular_activation_ui", flag_descriptions::kUpdatedCellularActivationUiName,
diff --git a/chrome/browser/android/chrome_feature_list.cc b/chrome/browser/android/chrome_feature_list.cc index df494f9a..872eacb64 100644 --- a/chrome/browser/android/chrome_feature_list.cc +++ b/chrome/browser/android/chrome_feature_list.cc
@@ -33,7 +33,6 @@ #include "components/signin/public/base/account_consistency_method.h" #include "components/subresource_filter/core/browser/subresource_filter_features.h" #include "components/sync/driver/sync_driver_switches.h" -#include "components/translate/core/browser/translate_prefs.h" #include "components/unified_consent/feature.h" #include "content/public/common/content_features.h" #include "media/base/media_switches.h" @@ -215,7 +214,6 @@ &signin::kMiceFeature, &switches::kSyncManualStartAndroid, &switches::kSyncSendTabToSelf, - &translate::kTranslateMobileManualTrigger, &unified_consent::kUnifiedConsent, &subresource_filter::kSafeBrowsingSubresourceFilter, };
diff --git a/chrome/browser/android/password_ui_view_android.cc b/chrome/browser/android/password_ui_view_android.cc index 9e9c23f..496c657 100644 --- a/chrome/browser/android/password_ui_view_android.cc +++ b/chrome/browser/android/password_ui_view_android.cc
@@ -40,7 +40,9 @@ using base::android::ScopedJavaLocalRef; PasswordUIViewAndroid::PasswordUIViewAndroid(JNIEnv* env, jobject obj) - : password_manager_presenter_(this), weak_java_ui_controller_(env, obj) {} + : password_manager_presenter_(this), weak_java_ui_controller_(env, obj) { + password_manager_presenter_.Initialize(); +} PasswordUIViewAndroid::~PasswordUIViewAndroid() {}
diff --git a/chrome/browser/android/payments/service_worker_payment_app_bridge.cc b/chrome/browser/android/payments/service_worker_payment_app_bridge.cc index 656b87f..88ae4d6 100644 --- a/chrome/browser/android/payments/service_worker_payment_app_bridge.cc +++ b/chrome/browser/android/payments/service_worker_payment_app_bridge.cc
@@ -12,6 +12,7 @@ #include "base/android/scoped_java_ref.h" #include "base/bind.h" #include "base/macros.h" +#include "base/numerics/safe_conversions.h" #include "chrome/android/chrome_jni_headers/ServiceWorkerPaymentAppBridge_jni.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/profiles/profile_manager.h" @@ -159,8 +160,7 @@ env, jcallback, jappsInfo); } -void OnCanMakePayment(const JavaRef<jobject>& jweb_contents, - const JavaRef<jobject>& jcallback, +void OnCanMakePayment(const JavaRef<jobject>& jcallback, bool can_make_payment) { JNIEnv* env = AttachCurrentThread(); Java_ServiceWorkerPaymentAppBridge_onCanMakePayment(env, jcallback, @@ -168,7 +168,6 @@ } void OnPaymentAppInvoked( - const JavaRef<jobject>& jweb_contents, const JavaRef<jobject>& jcallback, payments::mojom::PaymentHandlerResponsePtr handler_response) { JNIEnv* env = AttachCurrentThread(); @@ -182,9 +181,7 @@ handler_response->response_type))); } -void OnPaymentAppAborted(const JavaRef<jobject>& jweb_contents, - const JavaRef<jobject>& jcallback, - bool result) { +void OnPaymentAppAborted(const JavaRef<jobject>& jcallback, bool result) { JNIEnv* env = AttachCurrentThread(); Java_ServiceWorkerPaymentAppBridge_onPaymentAppAborted(env, jcallback, @@ -415,7 +412,6 @@ GURL(ConvertJavaStringToUTF8(env, jservice_worker_scope))), ConvertJavaStringToUTF8(env, jpayment_request_id), std::move(event_data), base::BindOnce(&OnCanMakePayment, - ScopedJavaGlobalRef<jobject>(env, jweb_contents), ScopedJavaGlobalRef<jobject>(env, jcallback))); } @@ -435,15 +431,24 @@ content::WebContents* web_contents = content::WebContents::FromJavaWebContents(jweb_contents); + auto event_data = ConvertPaymentRequestEventDataFromJavaToNative( + env, jtop_origin, jpayment_request_origin, jpayment_request_id, + jmethod_data, jtotal, jmodifiers, payment_handler_host); + + url::Origin sw_scope_origin = url::Origin::Create( + GURL(ConvertJavaStringToUTF8(env, jservice_worker_scope))); + int64_t reg_id = base::checked_cast<int64_t>(registration_id); + + auto* host = + reinterpret_cast<payments::PaymentHandlerHost*>(payment_handler_host); + host->set_sw_origin_for_logs(sw_scope_origin); + host->set_payment_request_id_for_logs(event_data->payment_request_id); + host->set_registration_id_for_logs(reg_id); + content::PaymentAppProvider::GetInstance()->InvokePaymentApp( - web_contents->GetBrowserContext(), registration_id, - url::Origin::Create( - GURL(ConvertJavaStringToUTF8(env, jservice_worker_scope))), - ConvertPaymentRequestEventDataFromJavaToNative( - env, jtop_origin, jpayment_request_origin, jpayment_request_id, - jmethod_data, jtotal, jmodifiers, payment_handler_host), + web_contents->GetBrowserContext(), reg_id, sw_scope_origin, + std::move(event_data), base::BindOnce(&OnPaymentAppInvoked, - ScopedJavaGlobalRef<jobject>(env, jweb_contents), ScopedJavaGlobalRef<jobject>(env, jcallback))); } @@ -472,17 +477,26 @@ icon_bitmap = gfx::CreateSkBitmapFromJavaBitmap(gfx::JavaBitmap(jicon)); } + auto event_data = ConvertPaymentRequestEventDataFromJavaToNative( + env, jtop_origin, jpayment_request_origin, jpayment_request_id, + jmethod_data, jtotal, jmodifiers, payment_handler_host); + + std::string sw_scope = ConvertJavaStringToUTF8(env, jsw_scope); + + auto* host = + reinterpret_cast<payments::PaymentHandlerHost*>(payment_handler_host); + host->set_sw_origin_for_logs(url::Origin::Create(GURL(sw_scope))); + host->set_payment_request_id_for_logs(event_data->payment_request_id); + content::PaymentAppProvider::GetInstance()->InstallAndInvokePaymentApp( - web_contents, - ConvertPaymentRequestEventDataFromJavaToNative( - env, jtop_origin, jpayment_request_origin, jpayment_request_id, - jmethod_data, jtotal, jmodifiers, payment_handler_host), + web_contents, std::move(event_data), ConvertJavaStringToUTF8(env, japp_name), icon_bitmap, - ConvertJavaStringToUTF8(env, jsw_js_url), - ConvertJavaStringToUTF8(env, jsw_scope), juse_cache, + ConvertJavaStringToUTF8(env, jsw_js_url), sw_scope, juse_cache, ConvertJavaStringToUTF8(env, jmethod), + base::BindOnce( + &payments::PaymentHandlerHost::set_registration_id_for_logs, + base::Unretained(host)), base::BindOnce(&OnPaymentAppInvoked, - ScopedJavaGlobalRef<jobject>(env, jweb_contents), ScopedJavaGlobalRef<jobject>(env, jcallback))); } @@ -502,7 +516,6 @@ GURL(ConvertJavaStringToUTF8(env, jservice_worker_scope))), ConvertJavaStringToUTF8(env, jpayment_request_id), base::BindOnce(&OnPaymentAppAborted, - ScopedJavaGlobalRef<jobject>(env, jweb_contents), ScopedJavaGlobalRef<jobject>(env, jcallback))); }
diff --git a/chrome/browser/apps/app_service/app_icon_factory.cc b/chrome/browser/apps/app_service/app_icon_factory.cc index f0c8a4cd..24dda84 100644 --- a/chrome/browser/apps/app_service/app_icon_factory.cc +++ b/chrome/browser/apps/app_service/app_icon_factory.cc
@@ -323,8 +323,10 @@ case apps::mojom::IconCompression::kUncompressed: case apps::mojom::IconCompression::kCompressed: { - base::PostTaskWithTraitsAndReplyWithResult( - FROM_HERE, {base::MayBlock(), base::TaskPriority::USER_VISIBLE}, + base::PostTaskAndReplyWithResult( + FROM_HERE, + {base::ThreadPool(), base::MayBlock(), + base::TaskPriority::USER_VISIBLE}, base::BindOnce(&ReadFileAsCompressedData, path), base::BindOnce(&RunCallbackWithFallback, size_hint_in_dip, is_placeholder_icon, icon_effects, icon_compression,
diff --git a/chrome/browser/apps/app_shim/app_shim_host_manager_mac.mm b/chrome/browser/apps/app_shim/app_shim_host_manager_mac.mm index d58610da..d974e85 100644 --- a/chrome/browser/apps/app_shim/app_shim_host_manager_mac.mm +++ b/chrome/browser/apps/app_shim/app_shim_host_manager_mac.mm
@@ -34,13 +34,14 @@ // If running the shim triggers Chrome startup, the user must wait for the // socket to be set up before the shim will be usable. This also requires // IO, so use MayBlock() with USER_VISIBLE. - base::PostTaskWithTraits( - FROM_HERE, {base::MayBlock(), base::TaskPriority::USER_VISIBLE}, + base::PostTask( + FROM_HERE, + {base::ThreadPool(), base::MayBlock(), base::TaskPriority::USER_VISIBLE}, base::BindOnce(&AppShimHostManager::InitOnBackgroundThread, this)); } AppShimHostManager::~AppShimHostManager() { - base::CreateSingleThreadTaskRunnerWithTraits({content::BrowserThread::IO}) + base::CreateSingleThreadTaskRunner({content::BrowserThread::IO}) ->DeleteSoon(FROM_HERE, std::move(mach_acceptor_)); // The AppShimHostManager is only initialized if the Chrome process @@ -56,9 +57,9 @@ base::FilePath version_path = user_data_dir.Append(app_mode::kRunningChromeVersionSymlinkName); - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, - {base::MayBlock(), base::TaskPriority::BEST_EFFORT, + {base::ThreadPool(), base::MayBlock(), base::TaskPriority::BEST_EFFORT, base::TaskShutdownBehavior::BLOCK_SHUTDOWN}, base::BindOnce(base::IgnoreResult(&base::DeleteFile), version_path, false)); @@ -92,7 +93,7 @@ void AppShimHostManager::OnClientConnected( mojo::PlatformChannelEndpoint endpoint, base::ProcessId peer_pid) { - base::CreateSingleThreadTaskRunnerWithTraits({content::BrowserThread::UI}) + base::CreateSingleThreadTaskRunner({content::BrowserThread::UI}) ->PostTask( FROM_HERE, base::BindOnce(&AppShimHostBootstrap::CreateForChannelAndPeerID,
diff --git a/chrome/browser/apps/app_shim/app_shim_interactive_uitest_mac.mm b/chrome/browser/apps/app_shim/app_shim_interactive_uitest_mac.mm index 8bb8c31..572a3a94 100644 --- a/chrome/browser/apps/app_shim/app_shim_interactive_uitest_mac.mm +++ b/chrome/browser/apps/app_shim/app_shim_interactive_uitest_mac.mm
@@ -447,8 +447,8 @@ // final request to close the window is posted to this thread's queue. GetFirstAppWindow()->GetBaseWindow()->Close(); base::RunLoop run_loop; - base::PostTaskWithTraitsAndReply( - FROM_HERE, {base::MayBlock()}, + base::PostTaskAndReply( + FROM_HERE, {base::ThreadPool(), base::MayBlock()}, base::BindOnce( [](base::Process* shim_process) { base::ScopedAllowBaseSyncPrimitivesForTesting
diff --git a/chrome/browser/apps/platform_apps/api/sync_file_system/sync_file_system_api.cc b/chrome/browser/apps/platform_apps/api/sync_file_system/sync_file_system_api.cc index cfb3203..897bb333 100644 --- a/chrome/browser/apps/platform_apps/api/sync_file_system/sync_file_system_api.cc +++ b/chrome/browser/apps/platform_apps/api/sync_file_system/sync_file_system_api.cc
@@ -102,7 +102,7 @@ storage::FileSystemURL file_system_url( file_system_context->CrackURL(GURL(url))); - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {BrowserThread::IO}, BindOnce( &storage::FileSystemContext::DeleteFileSystem, file_system_context, @@ -117,7 +117,7 @@ // Repost to switch from IO thread to UI thread for SendResponse(). if (!BrowserThread::CurrentlyOn(BrowserThread::UI)) { DCHECK_CURRENTLY_ON(BrowserThread::IO); - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {BrowserThread::UI}, BindOnce(&SyncFileSystemDeleteFileSystemFunction::DidDeleteFileSystem, this, error)); @@ -146,13 +146,12 @@ // Initializes sync context for this extension and continue to open // a new file system. - base::PostTaskWithTraits( - FROM_HERE, {BrowserThread::IO}, - BindOnce(&storage::FileSystemContext::OpenFileSystem, - GetFileSystemContext(), source_url().GetOrigin(), - storage::kFileSystemTypeSyncable, - storage::OPEN_FILE_SYSTEM_CREATE_IF_NONEXISTENT, - base::Bind(&self::DidOpenFileSystem, this))); + base::PostTask(FROM_HERE, {BrowserThread::IO}, + BindOnce(&storage::FileSystemContext::OpenFileSystem, + GetFileSystemContext(), source_url().GetOrigin(), + storage::kFileSystemTypeSyncable, + storage::OPEN_FILE_SYSTEM_CREATE_IF_NONEXISTENT, + base::Bind(&self::DidOpenFileSystem, this))); return true; } @@ -171,7 +170,7 @@ // Repost to switch from IO thread to UI thread for SendResponse(). if (!BrowserThread::CurrentlyOn(BrowserThread::UI)) { DCHECK_CURRENTLY_ON(BrowserThread::IO); - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {BrowserThread::UI}, BindOnce(&SyncFileSystemRequestFileSystemFunction::DidOpenFileSystem, this, root_url, file_system_name, error)); @@ -334,7 +333,7 @@ GetProfile(), render_frame_host()->GetSiteInstance()) ->GetQuotaManager(); - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {BrowserThread::IO}, BindOnce( &storage::QuotaManager::GetUsageAndQuotaForWebApps, quota_manager, @@ -353,7 +352,7 @@ // Repost to switch from IO thread to UI thread for SendResponse(). if (!BrowserThread::CurrentlyOn(BrowserThread::UI)) { DCHECK_CURRENTLY_ON(BrowserThread::IO); - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {BrowserThread::UI}, BindOnce(&SyncFileSystemGetUsageAndQuotaFunction::DidGetUsageAndQuota, this, status, usage, quota));
diff --git a/chrome/browser/apps/platform_apps/api/sync_file_system/sync_file_system_browsertest.cc b/chrome/browser/apps/platform_apps/api/sync_file_system/sync_file_system_browsertest.cc index 2f7279d..032be15 100644 --- a/chrome/browser/apps/platform_apps/api/sync_file_system/sync_file_system_browsertest.cc +++ b/chrome/browser/apps/platform_apps/api/sync_file_system/sync_file_system_browsertest.cc
@@ -63,8 +63,9 @@ SyncFileSystemTest() : remote_service_(nullptr) {} scoped_refptr<base::SequencedTaskRunner> MakeSequencedTaskRunner() { - return base::CreateSequencedTaskRunnerWithTraits( - {base::MayBlock(), base::TaskShutdownBehavior::SKIP_ON_SHUTDOWN}); + return base::CreateSequencedTaskRunner( + {base::ThreadPool(), base::MayBlock(), + base::TaskShutdownBehavior::SKIP_ON_SHUTDOWN}); } void SetUpOnMainThread() override {
diff --git a/chrome/browser/autofill/credit_card_accessory_controller_impl.cc b/chrome/browser/autofill/credit_card_accessory_controller_impl.cc index 012d337..831f5e9d 100644 --- a/chrome/browser/autofill/credit_card_accessory_controller_impl.cc +++ b/chrome/browser/autofill/credit_card_accessory_controller_impl.cc
@@ -17,6 +17,7 @@ #include "chrome/browser/profiles/profile.h" #include "chrome/browser/vr/vr_tab_helper.h" #include "components/autofill/content/browser/content_autofill_driver.h" +#include "components/autofill/core/browser/autofill_browser_util.h" #include "components/autofill/core/browser/data_model/credit_card.h" #include "components/autofill/core/common/autofill_features.h" #include "components/strings/grit/components_strings.h" @@ -32,13 +33,14 @@ : IDS_MANUAL_FILLING_CREDIT_CARD_SHEET_EMPTY_MESSAGE); } -void AddSimpleField(const base::string16& data, UserInfo* user_info) { +void AddSimpleField(const base::string16& data, + UserInfo* user_info, + bool enabled) { user_info->add_field(UserInfo::Field(data, data, - /*is_password=*/false, - /*selectable=*/true)); + /*is_password=*/false, enabled)); } -UserInfo TranslateCard(const CreditCard* data) { +UserInfo TranslateCard(const CreditCard* data, bool enabled) { DCHECK(data); UserInfo user_info(data->network()); @@ -46,21 +48,21 @@ base::string16 obfuscated_number = data->ObfuscatedLastFourDigits(); user_info.add_field(UserInfo::Field(obfuscated_number, obfuscated_number, data->guid(), /*is_password=*/false, - /*selectable=*/true)); + enabled)); if (data->HasValidExpirationDate()) { - AddSimpleField(data->ExpirationMonthAsString(), &user_info); - AddSimpleField(data->Expiration4DigitYearAsString(), &user_info); + AddSimpleField(data->ExpirationMonthAsString(), &user_info, enabled); + AddSimpleField(data->Expiration4DigitYearAsString(), &user_info, enabled); } else { - AddSimpleField(base::string16(), &user_info); - AddSimpleField(base::string16(), &user_info); + AddSimpleField(base::string16(), &user_info, enabled); + AddSimpleField(base::string16(), &user_info, enabled); } if (data->HasNameOnCard()) { AddSimpleField(data->GetRawInfo(autofill::CREDIT_CARD_NAME_FULL), - &user_info); + &user_info, enabled); } else { - AddSimpleField(base::string16(), &user_info); + AddSimpleField(base::string16(), &user_info, enabled); } return user_info; @@ -147,8 +149,13 @@ void CreditCardAccessoryControllerImpl::RefreshSuggestions() { FetchSuggestionsFromPersonalDataManager(); std::vector<UserInfo> info_to_add; + bool allow_filling = ShouldAllowCreditCardFallbacks( + GetManager()->client(), GetManager()->last_query_form()); std::transform(cards_cache_.begin(), cards_cache_.end(), - std::back_inserter(info_to_add), &TranslateCard); + std::back_inserter(info_to_add), + [allow_filling](const CreditCard* data) { + return TranslateCard(data, allow_filling); + }); const std::vector<FooterCommand> footer_commands = {FooterCommand( l10n_util::GetStringUTF16( @@ -157,10 +164,14 @@ bool has_suggestions = !info_to_add.empty(); - GetManualFillingController()->RefreshSuggestions( - autofill::CreateAccessorySheetData( - AccessoryTabType::CREDIT_CARDS, GetTitle(has_suggestions), - std::move(info_to_add), std::move(footer_commands))); + AccessorySheetData data = autofill::CreateAccessorySheetData( + AccessoryTabType::CREDIT_CARDS, GetTitle(has_suggestions), + std::move(info_to_add), std::move(footer_commands)); + if (has_suggestions && !allow_filling) { + data.set_warning( + l10n_util::GetStringUTF16(IDS_AUTOFILL_WARNING_INSECURE_CONNECTION)); + } + GetManualFillingController()->RefreshSuggestions(data); } void CreditCardAccessoryControllerImpl::OnPersonalDataChanged() {
diff --git a/chrome/browser/autofill/credit_card_accessory_controller_impl.h b/chrome/browser/autofill/credit_card_accessory_controller_impl.h index be7674d..f226b2c 100644 --- a/chrome/browser/autofill/credit_card_accessory_controller_impl.h +++ b/chrome/browser/autofill/credit_card_accessory_controller_impl.h
@@ -70,8 +70,8 @@ content::WebContents* web_contents_; base::WeakPtr<ManualFillingController> mf_controller_; PersonalDataManager* const personal_data_manager_; - autofill::AutofillManager* af_manager_for_testing_; - autofill::AutofillDriver* af_driver_for_testing_; + autofill::AutofillManager* af_manager_for_testing_ = nullptr; + autofill::AutofillDriver* af_driver_for_testing_ = nullptr; WEB_CONTENTS_USER_DATA_KEY_DECL(); };
diff --git a/chrome/browser/autofill/credit_card_accessory_controller_impl_unittest.cc b/chrome/browser/autofill/credit_card_accessory_controller_impl_unittest.cc index 29795a3..6acaf12 100644 --- a/chrome/browser/autofill/credit_card_accessory_controller_impl_unittest.cc +++ b/chrome/browser/autofill/credit_card_accessory_controller_impl_unittest.cc
@@ -15,6 +15,7 @@ #include "components/autofill/core/browser/test_autofill_client.h" #include "components/autofill/core/browser/test_autofill_driver.h" #include "components/autofill/core/browser/test_personal_data_manager.h" +#include "components/autofill/core/common/form_data.h" #include "components/strings/grit/components_strings.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" @@ -30,6 +31,35 @@ namespace autofill { namespace { +class TestAutofillManager : public AutofillManager { + public: + TestAutofillManager( + AutofillDriver* driver, + AutofillClient* client, + PersonalDataManager* personal_data, + AutocompleteHistoryManager* autocomplete_history_manager, + std::unique_ptr<CreditCardAccessManager> cc_access_manager = nullptr) + // Force to use the constructor designated for unit test. + : AutofillManager(driver, + client, + personal_data, + autocomplete_history_manager, + "en-US", + AutofillHandler::DISABLE_AUTOFILL_DOWNLOAD_MANAGER, + std::move(cc_access_manager)) {} + + ~TestAutofillManager() override = default; + + const FormData& last_query_form() const override { return last_form_; } + + void SetLastForm(FormData form) { last_form_ = std::move(form); } + + private: + FormData last_form_; + + DISALLOW_COPY_AND_ASSIGN(TestAutofillManager); +}; + AccessorySheetData::Builder CreditCardAccessorySheetDataBuilder() { return AccessorySheetData::Builder( AccessoryTabType::CREDIT_CARDS, @@ -77,8 +107,6 @@ &client_, &data_manager_, &history_, - "en-US", - AutofillHandler::DISABLE_AUTOFILL_DOWNLOAD_MANAGER, std::make_unique<TestAccessManager>(&mock_af_driver_, &client_, &data_manager_)) {} @@ -86,6 +114,7 @@ void SetUp() override { ChromeRenderViewHostTestHarness::SetUp(); NavigateAndCommit(GURL(kExampleSite)); + SetFormOrigin(GURL(kExampleSite)); FocusWebContentsOnMainFrame(); CreditCardAccessoryControllerImpl::CreateForWebContentsForTesting( @@ -103,13 +132,22 @@ return CreditCardAccessoryControllerImpl::FromWebContents(web_contents()); } + void SetFormOrigin(GURL origin) { + FormData form; + form.unique_renderer_id = 1; + form.action = origin; + form.main_frame_origin = url::Origin::Create(origin); + client_.set_form_origin(origin); + af_manager_.SetLastForm(std::move(form)); + } + protected: TestAutofillClient client_; testing::NiceMock<MockAutofillDriver> mock_af_driver_; autofill::TestPersonalDataManager data_manager_; MockAutocompleteHistoryManager history_; testing::NiceMock<MockManualFillingController> mock_mf_controller_; - AutofillManager af_manager_; + TestAutofillManager af_manager_; TestingProfile profile_; }; @@ -140,6 +178,41 @@ .Build()); } +TEST_F(CreditCardAccessoryControllerTest, PreventsFillingInsecureContexts) { + autofill::CreditCard card = test::GetCreditCard(); + data_manager_.AddCreditCard(card); + autofill::AccessorySheetData result(autofill::AccessoryTabType::CREDIT_CARDS, + base::string16()); + SetFormOrigin(GURL("http://insecure.http-site.com")); + + EXPECT_CALL(mock_mf_controller_, RefreshSuggestions(_)) + .WillOnce(SaveArg<0>(&result)); + controller()->RefreshSuggestions(); + + EXPECT_EQ(result, + CreditCardAccessorySheetDataBuilder() + .SetWarning(l10n_util::GetStringUTF16( + IDS_AUTOFILL_WARNING_INSECURE_CONNECTION)) + .AddUserInfo(kVisaCard) + .AppendField(card.ObfuscatedLastFourDigits(), + card.ObfuscatedLastFourDigits(), card.guid(), + /*is_obfuscated=*/false, + /*selectable=*/false) + .AppendField(card.ExpirationMonthAsString(), + card.ExpirationMonthAsString(), + /*is_obfuscated=*/false, + /*selectable=*/false) + .AppendField(card.Expiration4DigitYearAsString(), + card.Expiration4DigitYearAsString(), + /*is_obfuscated=*/false, + /*selectable=*/false) + .AppendField(card.GetRawInfo(autofill::CREDIT_CARD_NAME_FULL), + card.GetRawInfo(autofill::CREDIT_CARD_NAME_FULL), + /*is_obfuscated=*/false, + /*selectable=*/false) + .Build()); +} + TEST_F(CreditCardAccessoryControllerTest, ServerCardUnmask) { autofill::CreditCard card = test::GetMaskedServerCard(); data_manager_.AddCreditCard(card);
diff --git a/chrome/browser/autofill/manual_filling_controller_impl.cc b/chrome/browser/autofill/manual_filling_controller_impl.cc index 890458a..67f1414 100644 --- a/chrome/browser/autofill/manual_filling_controller_impl.cc +++ b/chrome/browser/autofill/manual_filling_controller_impl.cc
@@ -45,8 +45,7 @@ case AccessoryTabType::COUNT: break; // Intentional failure. } - NOTREACHED() << "Cannot determine filling source for " - << accessory_sheet.get_sheet_type(); + NOTREACHED() << "Cannot determine filling source"; return FillingSource::PASSWORD_FALLBACKS; } @@ -107,6 +106,11 @@ void ManualFillingControllerImpl::NotifyFocusedInputChanged( autofill::mojom::FocusedFieldType focused_field_type) { focused_field_type_ = focused_field_type; + + // Ensure warnings and filling state is updated according to focused field. + if (cc_controller_) + cc_controller_->RefreshSuggestions(); + // Whenever the focus changes, reset the accessory. if (ShouldShowAccessory()) view_->SwapSheetWithKeyboard();
diff --git a/chrome/browser/autofill/manual_filling_controller_impl_unittest.cc b/chrome/browser/autofill/manual_filling_controller_impl_unittest.cc index 543b8ce..03ec7121 100644 --- a/chrome/browser/autofill/manual_filling_controller_impl_unittest.cc +++ b/chrome/browser/autofill/manual_filling_controller_impl_unittest.cc
@@ -220,6 +220,11 @@ /*has_suggestions=*/false); } +TEST_F(ManualFillingControllerTest, UpdatesCreditCardControllerOnFocusChange) { + EXPECT_CALL(mock_cc_controller_, RefreshSuggestions); + FocusFieldAndClearExpectations(FocusedFieldType::kFillableUsernameField); +} + TEST_F(ManualFillingControllerTest, HidesAccessoryWithoutAvailableSources) { base::test::ScopedFeatureList scoped_feature_list; scoped_feature_list.InitAndEnableFeature(
diff --git a/chrome/browser/background/background_mode_manager_mac.mm b/chrome/browser/background/background_mode_manager_mac.mm index aaa164fc0..d5e6d89e 100644 --- a/chrome/browser/background/background_mode_manager_mac.mm +++ b/chrome/browser/background/background_mode_manager_mac.mm
@@ -46,9 +46,8 @@ base::BlockingType::MAY_BLOCK); if (!base::mac::CheckLoginItemStatus(NULL)) { // There's no LoginItem, so set the kUserRemovedLoginItem pref. - base::PostTaskWithTraits( - FROM_HERE, {BrowserThread::UI}, - base::BindOnce(SetUserRemovedLoginItemPrefOnUIThread)); + base::PostTask(FROM_HERE, {BrowserThread::UI}, + base::BindOnce(SetUserRemovedLoginItemPrefOnUIThread)); } } @@ -64,9 +63,8 @@ if (is_hidden) { // We already have a hidden login item, so set the kChromeCreatedLoginItem // flag. - base::PostTaskWithTraits( - FROM_HERE, {BrowserThread::UI}, - base::BindOnce(SetCreatedLoginItemPrefOnUIThread)); + base::PostTask(FROM_HERE, {BrowserThread::UI}, + base::BindOnce(SetCreatedLoginItemPrefOnUIThread)); } // LoginItem already exists - just exit. return; @@ -81,8 +79,8 @@ // before our callback is run, but the user can manually disable // "Open At Login" via the dock if this happens. base::mac::AddToLoginItems(true); // Hide on startup. - base::PostTaskWithTraits(FROM_HERE, {BrowserThread::UI}, - base::BindOnce(SetCreatedLoginItemPrefOnUIThread)); + base::PostTask(FROM_HERE, {BrowserThread::UI}, + base::BindOnce(SetCreatedLoginItemPrefOnUIThread)); } } @@ -163,7 +161,7 @@ scoped_refptr<base::SequencedTaskRunner> BackgroundModeManager::CreateTaskRunner() { - return base::CreateSequencedTaskRunnerWithTraits( - {base::MayBlock(), base::TaskPriority::BEST_EFFORT, + return base::CreateSequencedTaskRunner( + {base::ThreadPool(), base::MayBlock(), base::TaskPriority::BEST_EFFORT, base::TaskShutdownBehavior::BLOCK_SHUTDOWN}); }
diff --git a/chrome/browser/chromeos/BUILD.gn b/chrome/browser/chromeos/BUILD.gn index d08222d..b3b33a3 100644 --- a/chrome/browser/chromeos/BUILD.gn +++ b/chrome/browser/chromeos/BUILD.gn
@@ -1356,6 +1356,8 @@ "login/screens/welcome_screen.h", "login/screens/wrong_hwid_screen.cc", "login/screens/wrong_hwid_screen.h", + "login/security_token_pin_dialog_host_ash_impl.cc", + "login/security_token_pin_dialog_host_ash_impl.h", "login/session/chrome_session_manager.cc", "login/session/chrome_session_manager.h", "login/session/user_session_manager.cc",
diff --git a/chrome/browser/chromeos/accessibility/accessibility_manager.cc b/chrome/browser/chromeos/accessibility/accessibility_manager.cc index 8054b60..7cbb91f 100644 --- a/chrome/browser/chromeos/accessibility/accessibility_manager.cc +++ b/chrome/browser/chromeos/accessibility/accessibility_manager.cc
@@ -986,7 +986,7 @@ BrailleController* braille_controller = GetBrailleController(); if (!scoped_braille_observer_.IsObserving(braille_controller)) scoped_braille_observer_.Add(braille_controller); - base::PostTaskWithTraitsAndReplyWithResult( + base::PostTaskAndReplyWithResult( FROM_HERE, {BrowserThread::IO}, base::Bind(&BrailleController::GetDisplayState, base::Unretained(braille_controller)),
diff --git a/chrome/browser/chromeos/accessibility/spoken_feedback_browsertest.cc b/chrome/browser/chromeos/accessibility/spoken_feedback_browsertest.cc index 5e11b56..35d3ce0 100644 --- a/chrome/browser/chromeos/accessibility/spoken_feedback_browsertest.cc +++ b/chrome/browser/chromeos/accessibility/spoken_feedback_browsertest.cc
@@ -651,7 +651,7 @@ // Sticky key has a minimum 100 ms check to prevent key repeat from toggling // it. - base::PostDelayedTaskWithTraits( + base::PostDelayedTask( FROM_HERE, {content::BrowserThread::UI}, base::BindOnce(&LoggedInSpokenFeedbackTest::SendKeyPress, base::Unretained(this), ui::VKEY_LWIN), @@ -667,7 +667,7 @@ // Sticky key has a minimum 100 ms check to prevent key repeat from toggling // it. - base::PostDelayedTaskWithTraits( + base::PostDelayedTask( FROM_HERE, {content::BrowserThread::UI}, base::BindOnce(&LoggedInSpokenFeedbackTest::SendKeyPress, base::Unretained(this), ui::VKEY_LWIN),
diff --git a/chrome/browser/chromeos/android_sms/fcm_connection_establisher.cc b/chrome/browser/chromeos/android_sms/fcm_connection_establisher.cc index 7a9cb7d..0a9b3078 100644 --- a/chrome/browser/chromeos/android_sms/fcm_connection_establisher.cc +++ b/chrome/browser/chromeos/android_sms/fcm_connection_establisher.cc
@@ -62,7 +62,7 @@ const GURL& url, ConnectionMode connection_mode, content::ServiceWorkerContext* service_worker_context) { - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {content::BrowserThread::IO}, base::BindOnce( &FcmConnectionEstablisher::SendMessageToServiceWorkerWithRetries, @@ -74,7 +74,7 @@ void FcmConnectionEstablisher::TearDownConnection( const GURL& url, content::ServiceWorkerContext* service_worker_context) { - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {content::BrowserThread::IO}, base::BindOnce( &FcmConnectionEstablisher::SendMessageToServiceWorkerWithRetries,
diff --git a/chrome/browser/chromeos/android_sms/streaming_connection_establisher.cc b/chrome/browser/chromeos/android_sms/streaming_connection_establisher.cc index 2bffdfe..12108ecb 100644 --- a/chrome/browser/chromeos/android_sms/streaming_connection_establisher.cc +++ b/chrome/browser/chromeos/android_sms/streaming_connection_establisher.cc
@@ -34,12 +34,11 @@ const GURL& url, ConnectionMode connection_mode, content::ServiceWorkerContext* service_worker_context) { - base::PostTaskWithTraits( - FROM_HERE, {content::BrowserThread::IO}, - base::BindOnce(&StreamingConnectionEstablisher:: - SendStartStreamingMessageIfNotConnected, - weak_ptr_factory_.GetWeakPtr(), url, connection_mode, - service_worker_context)); + base::PostTask(FROM_HERE, {content::BrowserThread::IO}, + base::BindOnce(&StreamingConnectionEstablisher:: + SendStartStreamingMessageIfNotConnected, + weak_ptr_factory_.GetWeakPtr(), url, + connection_mode, service_worker_context)); } void StreamingConnectionEstablisher::TearDownConnection(
diff --git a/chrome/browser/chromeos/app_mode/app_session.cc b/chrome/browser/chromeos/app_mode/app_session.cc index 535b67ae..60684db 100644 --- a/chrome/browser/chromeos/app_mode/app_session.cc +++ b/chrome/browser/chromeos/app_mode/app_session.cc
@@ -92,7 +92,7 @@ // Wait a bit to let dump finish (if requested) before rebooting the device. const int kDumpWaitSeconds = 10; - base::PostDelayedTaskWithTraits( + base::PostDelayedTask( FROM_HERE, {content::BrowserThread::UI}, base::BindOnce(&RebootDevice), base::TimeDelta::FromSeconds(dump_requested ? kDumpWaitSeconds : 0)); } @@ -269,9 +269,8 @@ is_shutting_down_ = true; LOG(ERROR) << "Plugin hung detected. Dump and reboot."; - base::PostTaskWithTraits( - FROM_HERE, {content::BrowserThread::IO}, - base::BindOnce(&DumpPluginProcessOnIOThread, hung_plugins)); + base::PostTask(FROM_HERE, {content::BrowserThread::IO}, + base::BindOnce(&DumpPluginProcessOnIOThread, hung_plugins)); } } // namespace chromeos
diff --git a/chrome/browser/chromeos/app_mode/kiosk_app_data.cc b/chrome/browser/chromeos/app_mode/kiosk_app_data.cc index d851043..9af14253f 100644 --- a/chrome/browser/chromeos/app_mode/kiosk_app_data.cc +++ b/chrome/browser/chromeos/app_mode/kiosk_app_data.cc
@@ -86,8 +86,9 @@ : client_(client), crx_file_(crx_file), success_(false), - task_runner_(base::CreateSequencedTaskRunnerWithTraits( - {base::MayBlock(), base::TaskPriority::BEST_EFFORT, + task_runner_(base::CreateSequencedTaskRunner( + {base::ThreadPool(), base::MayBlock(), + base::TaskPriority::BEST_EFFORT, base::TaskShutdownBehavior::SKIP_ON_SHUTDOWN})) {} void Start() { @@ -169,9 +170,8 @@ << temp_dir_.GetPath().value(); } - base::PostTaskWithTraits( - FROM_HERE, {BrowserThread::UI}, - base::BindOnce(&CrxLoader::NotifyFinishedOnUIThread, this)); + base::PostTask(FROM_HERE, {BrowserThread::UI}, + base::BindOnce(&CrxLoader::NotifyFinishedOnUIThread, this)); } void NotifyFinishedOnUIThread() {
diff --git a/chrome/browser/chromeos/app_mode/kiosk_app_data_base.cc b/chrome/browser/chromeos/app_mode/kiosk_app_data_base.cc index 8daf593b..11e0f33 100644 --- a/chrome/browser/chromeos/app_mode/kiosk_app_data_base.cc +++ b/chrome/browser/chromeos/app_mode/kiosk_app_data_base.cc
@@ -102,9 +102,9 @@ const base::FilePath icon_path = cache_dir.AppendASCII(app_id_).AddExtension(kIconFileExtension); - base::PostTaskWithTraits(FROM_HERE, {base::MayBlock()}, - base::BindOnce(&SaveIconToLocalOnBlockingPool, - icon_path, std::move(image_data))); + base::PostTask(FROM_HERE, {base::ThreadPool(), base::MayBlock()}, + base::BindOnce(&SaveIconToLocalOnBlockingPool, icon_path, + std::move(image_data))); icon_path_ = icon_path; } @@ -120,8 +120,9 @@ dict_update->Remove(app_key, nullptr); if (!icon_path_.empty()) { - base::PostTaskWithTraits( - FROM_HERE, {base::MayBlock(), base::TaskPriority::BEST_EFFORT}, + base::PostTask( + FROM_HERE, + {base::ThreadPool(), base::MayBlock(), base::TaskPriority::BEST_EFFORT}, base::BindOnce(base::IgnoreResult(&base::DeleteFile), icon_path_, false)); }
diff --git a/chrome/browser/chromeos/app_mode/kiosk_app_icon_loader.cc b/chrome/browser/chromeos/app_mode/kiosk_app_icon_loader.cc index d5dd161..4b764931 100644 --- a/chrome/browser/chromeos/app_mode/kiosk_app_icon_loader.cc +++ b/chrome/browser/chromeos/app_mode/kiosk_app_icon_loader.cc
@@ -29,14 +29,14 @@ void OnImageDecoded(const SkBitmap& decoded_image) override { gfx::ImageSkia image = gfx::ImageSkia::CreateFrom1xBitmap(decoded_image); image.MakeThreadSafe(); - base::PostTaskWithTraits(FROM_HERE, {BrowserThread::UI}, - base::BindOnce(result_callback_, image)); + base::PostTask(FROM_HERE, {BrowserThread::UI}, + base::BindOnce(result_callback_, image)); delete this; } void OnDecodeImageFailed() override { LOG(ERROR) << "Failed to decode icon image."; - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {BrowserThread::UI}, base::BindOnce(result_callback_, base::Optional<gfx::ImageSkia>())); delete this; @@ -56,7 +56,7 @@ std::string data; if (!base::ReadFileToString(base::FilePath(icon_path), &data)) { LOG(ERROR) << "Failed to read icon file."; - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {BrowserThread::UI}, base::BindOnce(result_callback, base::Optional<gfx::ImageSkia>())); return; @@ -76,8 +76,9 @@ void KioskAppIconLoader::Start(const base::FilePath& icon_path) { scoped_refptr<base::SequencedTaskRunner> task_runner = - base::CreateSequencedTaskRunnerWithTraits( - {base::MayBlock(), base::TaskShutdownBehavior::SKIP_ON_SHUTDOWN}); + base::CreateSequencedTaskRunner( + {base::ThreadPool(), base::MayBlock(), + base::TaskShutdownBehavior::SKIP_ON_SHUTDOWN}); task_runner->PostTask( FROM_HERE, base::BindOnce(&LoadOnBlockingPool, icon_path, task_runner,
diff --git a/chrome/browser/chromeos/app_mode/kiosk_app_manager.cc b/chrome/browser/chromeos/app_mode/kiosk_app_manager.cc index d5eb43b..16ec49c 100644 --- a/chrome/browser/chromeos/app_mode/kiosk_app_manager.cc +++ b/chrome/browser/chromeos/app_mode/kiosk_app_manager.cc
@@ -168,8 +168,8 @@ // TODO(eseckler): The ExternalCacheImpl that uses this TaskRunner seems to be // important during startup, which is why we cannot currently use the // BEST_EFFORT TaskPriority here. - return base::CreateSequencedTaskRunnerWithTraits( - {base::MayBlock(), base::TaskPriority::USER_VISIBLE, + return base::CreateSequencedTaskRunner( + {base::ThreadPool(), base::MayBlock(), base::TaskPriority::USER_VISIBLE, base::TaskShutdownBehavior::SKIP_ON_SHUTDOWN}); } @@ -475,8 +475,10 @@ status = CONSUMER_KIOSK_AUTO_LAUNCH_CONFIGURABLE; } else if (!ownership_established_) { bool* owner_present = new bool(false); - base::PostTaskWithTraitsAndReply( - FROM_HERE, {base::MayBlock(), base::TaskPriority::BEST_EFFORT}, + base::PostTaskAndReply( + FROM_HERE, + {base::ThreadPool(), base::MayBlock(), + base::TaskPriority::BEST_EFFORT}, base::BindOnce(&CheckOwnerFilePresence, owner_present), base::BindOnce(&KioskAppManager::OnOwnerFileChecked, base::Unretained(this), callback,
diff --git a/chrome/browser/chromeos/app_mode/kiosk_diagnosis_runner.cc b/chrome/browser/chromeos/app_mode/kiosk_diagnosis_runner.cc index 2afee80..229377d3 100644 --- a/chrome/browser/chromeos/app_mode/kiosk_diagnosis_runner.cc +++ b/chrome/browser/chromeos/app_mode/kiosk_diagnosis_runner.cc
@@ -75,7 +75,7 @@ app_id_ = app_id; // Schedules system logs to be collected after 1 minute. - base::PostDelayedTaskWithTraits( + base::PostDelayedTask( FROM_HERE, {content::BrowserThread::UI}, base::BindOnce(&KioskDiagnosisRunner::StartSystemLogCollection, weak_factory_.GetWeakPtr()),
diff --git a/chrome/browser/chromeos/app_mode/kiosk_external_update_validator.cc b/chrome/browser/chromeos/app_mode/kiosk_external_update_validator.cc index 973473c..dcd89d9 100644 --- a/chrome/browser/chromeos/app_mode/kiosk_external_update_validator.cc +++ b/chrome/browser/chromeos/app_mode/kiosk_external_update_validator.cc
@@ -47,7 +47,7 @@ const extensions::CrxInstallError& error) { LOG(ERROR) << "Failed to unpack external kiosk crx file: " << crx_file_.extension_id << " " << error.message(); - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {content::BrowserThread::UI}, base::BindOnce( &KioskExternalUpdateValidatorDelegate::OnExternalUpdateUnpackFailure, @@ -72,7 +72,7 @@ minimum_browser_version.clear(); } - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {content::BrowserThread::UI}, base::BindOnce( &KioskExternalUpdateValidatorDelegate::OnExternalUpdateUnpackSuccess,
diff --git a/chrome/browser/chromeos/apps/intent_helper/chromeos_apps_navigation_throttle.cc b/chrome/browser/chromeos/apps/intent_helper/chromeos_apps_navigation_throttle.cc index 6c0c37e..86189e9 100644 --- a/chrome/browser/chromeos/apps/intent_helper/chromeos_apps_navigation_throttle.cc +++ b/chrome/browser/chromeos/apps/intent_helper/chromeos_apps_navigation_throttle.cc
@@ -202,10 +202,9 @@ content::WebContents* web_contents = navigation_handle()->GetWebContents(); if (web_contents && web_contents->GetController().IsInitialNavigation()) { // Workaround for b/79167225, closing |web_contents| here may be dangerous. - base::PostTaskWithTraits( - FROM_HERE, {content::BrowserThread::UI}, - base::BindOnce(&ChromeOsAppsNavigationThrottle::CloseTab, - weak_factory_.GetWeakPtr())); + base::PostTask(FROM_HERE, {content::BrowserThread::UI}, + base::BindOnce(&ChromeOsAppsNavigationThrottle::CloseTab, + weak_factory_.GetWeakPtr())); } else { CancelDeferredNavigation(content::NavigationThrottle::CANCEL_AND_IGNORE); }
diff --git a/chrome/browser/chromeos/arc/arc_service_launcher.cc b/chrome/browser/chromeos/arc/arc_service_launcher.cc index 7e95bde..b07a0e80 100644 --- a/chrome/browser/chromeos/arc/arc_service_launcher.cc +++ b/chrome/browser/chromeos/arc/arc_service_launcher.cc
@@ -107,8 +107,8 @@ g_arc_service_launcher = this; // Write kIsArcVm file to be 1 or 0. - base::PostTaskWithTraits( - FROM_HERE, {base::MayBlock()}, + base::PostTask( + FROM_HERE, {base::ThreadPool(), base::MayBlock()}, base::BindOnce([](const base::FilePath& filename, const char* data, int size) { base::WriteFile(filename, data, size); }, base::FilePath(kIsArcVm),
diff --git a/chrome/browser/chromeos/arc/arc_util.cc b/chrome/browser/chromeos/arc/arc_util.cc index 006b669..e56ed58 100644 --- a/chrome/browser/chromeos/arc/arc_util.cc +++ b/chrome/browser/chromeos/arc/arc_util.cc
@@ -555,9 +555,9 @@ } // Otherwise, check the underlying filesystem. - base::PostTaskWithTraitsAndReplyWithResult( + base::PostTaskAndReplyWithResult( FROM_HERE, - {base::MayBlock(), base::TaskPriority::USER_BLOCKING, + {base::ThreadPool(), base::MayBlock(), base::TaskPriority::USER_BLOCKING, base::TaskShutdownBehavior::CONTINUE_ON_SHUTDOWN}, base::BindOnce(&IsArcCompatibleFilesystem, profile_path), base::BindOnce(&StoreCompatibilityCheckResult, account_id,
diff --git a/chrome/browser/chromeos/arc/file_system_watcher/arc_file_system_watcher_service.cc b/chrome/browser/chromeos/arc/file_system_watcher/arc_file_system_watcher_service.cc index bdacb367..2a4199b7 100644 --- a/chrome/browser/chromeos/arc/file_system_watcher/arc_file_system_watcher_service.cc +++ b/chrome/browser/chromeos/arc/file_system_watcher/arc_file_system_watcher_service.cc
@@ -356,10 +356,9 @@ void ArcFileSystemWatcherService::FileSystemWatcher::DelayBuildTimestampMap() { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); DCHECK(outstanding_task_); - base::PostTaskWithTraitsAndReplyWithResult( - FROM_HERE, {base::MayBlock()}, - base::Bind(&BuildTimestampMapCallback, cros_dir_, - android_dir_), + base::PostTaskAndReplyWithResult( + FROM_HERE, {base::ThreadPool(), base::MayBlock()}, + base::Bind(&BuildTimestampMapCallback, cros_dir_, android_dir_), base::Bind(&FileSystemWatcher::OnBuildTimestampMap, weak_ptr_factory_.GetWeakPtr())); } @@ -379,8 +378,8 @@ for (size_t i = 0; i < changed_paths.size(); ++i) { string_paths[i] = changed_paths[i].value(); } - base::PostTaskWithTraits(FROM_HERE, {BrowserThread::UI}, - base::BindOnce(callback_, std::move(string_paths))); + base::PostTask(FROM_HERE, {BrowserThread::UI}, + base::BindOnce(callback_, std::move(string_paths))); if (last_notify_time_ > snapshot_time) DelayBuildTimestampMap(); else @@ -398,8 +397,8 @@ ArcBridgeService* bridge_service) : context_(context), arc_bridge_service_(bridge_service), - file_task_runner_( - base::CreateSequencedTaskRunnerWithTraits({base::MayBlock()})), + file_task_runner_(base::CreateSequencedTaskRunner( + {base::ThreadPool(), base::MayBlock()})), weak_ptr_factory_(this) { DCHECK_CURRENTLY_ON(BrowserThread::UI); arc_bridge_service_->file_system()->AddObserver(this);
diff --git a/chrome/browser/chromeos/arc/fileapi/arc_content_file_system_file_stream_reader.cc b/chrome/browser/chromeos/arc/fileapi/arc_content_file_system_file_stream_reader.cc index c1f58b1c..e0f0daac6 100644 --- a/chrome/browser/chromeos/arc/fileapi/arc_content_file_system_file_stream_reader.cc +++ b/chrome/browser/chromeos/arc/fileapi/arc_content_file_system_file_stream_reader.cc
@@ -46,8 +46,9 @@ const GURL& arc_url, int64_t offset) : arc_url_(arc_url), offset_(offset), weak_ptr_factory_(this) { - task_runner_ = base::CreateSequencedTaskRunnerWithTraits( - {base::MayBlock(), base::TaskShutdownBehavior::SKIP_ON_SHUTDOWN}); + task_runner_ = base::CreateSequencedTaskRunner( + {base::ThreadPool(), base::MayBlock(), + base::TaskShutdownBehavior::SKIP_ON_SHUTDOWN}); } ArcContentFileSystemFileStreamReader::~ArcContentFileSystemFileStreamReader() {
diff --git a/chrome/browser/chromeos/arc/fileapi/arc_content_file_system_file_stream_writer.cc b/chrome/browser/chromeos/arc/fileapi/arc_content_file_system_file_stream_writer.cc index 7e7d6bf..b9bb8da4 100644 --- a/chrome/browser/chromeos/arc/fileapi/arc_content_file_system_file_stream_writer.cc +++ b/chrome/browser/chromeos/arc/fileapi/arc_content_file_system_file_stream_writer.cc
@@ -54,8 +54,9 @@ int64_t offset) : arc_url_(arc_url), offset_(offset), - task_runner_(base::CreateSequencedTaskRunnerWithTraits( - {base::MayBlock(), base::TaskShutdownBehavior::SKIP_ON_SHUTDOWN})), + task_runner_(base::CreateSequencedTaskRunner( + {base::ThreadPool(), base::MayBlock(), + base::TaskShutdownBehavior::SKIP_ON_SHUTDOWN})), has_pending_operation_(false), weak_ptr_factory_(this) {}
diff --git a/chrome/browser/chromeos/arc/fileapi/arc_documents_provider_async_file_util.cc b/chrome/browser/chromeos/arc/fileapi/arc_documents_provider_async_file_util.cc index e3ede2b..2ca856f 100644 --- a/chrome/browser/chromeos/arc/fileapi/arc_documents_provider_async_file_util.cc +++ b/chrome/browser/chromeos/arc/fileapi/arc_documents_provider_async_file_util.cc
@@ -34,8 +34,8 @@ base::File::Error result, const base::File::Info& info) { DCHECK_CURRENTLY_ON(BrowserThread::UI); - base::PostTaskWithTraits(FROM_HERE, {BrowserThread::IO}, - base::BindOnce(std::move(callback), result, info)); + base::PostTask(FROM_HERE, {BrowserThread::IO}, + base::BindOnce(std::move(callback), result, info)); } void OnReadDirectoryOnUIThread( @@ -53,9 +53,9 @@ : filesystem::mojom::FsFileType::REGULAR_FILE); } - base::PostTaskWithTraits(FROM_HERE, {BrowserThread::IO}, - base::BindOnce(std::move(callback), result, entries, - false /* has_more */)); + base::PostTask(FROM_HERE, {BrowserThread::IO}, + base::BindOnce(std::move(callback), result, entries, + false /* has_more */)); } void OnCreateFileOnUIThread( @@ -69,7 +69,7 @@ } else if (result == base::File::FILE_ERROR_EXISTS) { result_to_report = base::File::FILE_OK; } - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {BrowserThread::IO}, base::BindOnce(std::move(callback), result_to_report, created)); } @@ -77,8 +77,8 @@ void OnStatusCallbackOnUIThread(storage::AsyncFileUtil::StatusCallback callback, base::File::Error result) { DCHECK_CURRENTLY_ON(BrowserThread::UI); - base::PostTaskWithTraits(FROM_HERE, {BrowserThread::IO}, - base::BindOnce(std::move(callback), result)); + base::PostTask(FROM_HERE, {BrowserThread::IO}, + base::BindOnce(std::move(callback), result)); } void GetFileInfoOnUIThread( @@ -307,7 +307,7 @@ DCHECK_CURRENTLY_ON(BrowserThread::IO); DCHECK_EQ(storage::kFileSystemTypeArcDocumentsProvider, url.type()); - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {BrowserThread::UI}, base::BindOnce(&CreateFileOnUIThread, url, std::move(callback))); } @@ -326,7 +326,7 @@ // directory already exists at |url| for simpler ArcDocumentsProviderRoot // implementation. Chances of this case are small, since Files app // de-duplicate the new directory name to avoid conflicting with existing one. - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {BrowserThread::UI}, base::BindOnce(&CreateDirectoryOnUIThread, url, std::move(callback))); } @@ -339,7 +339,7 @@ DCHECK_CURRENTLY_ON(BrowserThread::IO); DCHECK_EQ(storage::kFileSystemTypeArcDocumentsProvider, url.type()); - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {BrowserThread::UI}, base::BindOnce(&GetFileInfoOnUIThread, url, fields, std::move(callback))); } @@ -351,7 +351,7 @@ DCHECK_CURRENTLY_ON(BrowserThread::IO); DCHECK_EQ(storage::kFileSystemTypeArcDocumentsProvider, url.type()); - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {BrowserThread::UI}, base::BindOnce(&ReadDirectoryOnUIThread, url, std::move(callback))); } @@ -392,9 +392,9 @@ DCHECK_EQ(storage::kFileSystemTypeArcDocumentsProvider, src_url.type()); DCHECK_EQ(storage::kFileSystemTypeArcDocumentsProvider, dest_url.type()); - base::PostTaskWithTraits(FROM_HERE, {BrowserThread::UI}, - base::BindOnce(&CopyFileLocalOnUIThread, src_url, - dest_url, std::move(callback))); + base::PostTask(FROM_HERE, {BrowserThread::UI}, + base::BindOnce(&CopyFileLocalOnUIThread, src_url, dest_url, + std::move(callback))); } void ArcDocumentsProviderAsyncFileUtil::MoveFileLocal( @@ -407,9 +407,9 @@ DCHECK_EQ(storage::kFileSystemTypeArcDocumentsProvider, src_url.type()); DCHECK_EQ(storage::kFileSystemTypeArcDocumentsProvider, dest_url.type()); - base::PostTaskWithTraits(FROM_HERE, {BrowserThread::UI}, - base::BindOnce(&MoveFileLocalOnUIThread, src_url, - dest_url, std::move(callback))); + base::PostTask(FROM_HERE, {BrowserThread::UI}, + base::BindOnce(&MoveFileLocalOnUIThread, src_url, dest_url, + std::move(callback))); } void ArcDocumentsProviderAsyncFileUtil::CopyInForeignFile( @@ -430,7 +430,7 @@ DCHECK_EQ(storage::kFileSystemTypeArcDocumentsProvider, url.type()); // TODO(fukino): Report an error if the document at |url| is not a file. - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {BrowserThread::UI}, base::BindOnce(&DeleteFileOnUIThread, url, std::move(callback))); } @@ -445,7 +445,7 @@ // TODO(fukino): Report an error if the document at |url| is not a directory. // TODO(fukino): Report an error if the document at |url| is a directory which // is not empty. - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {BrowserThread::UI}, base::BindOnce(&DeleteFileOnUIThread, url, std::move(callback))); } @@ -457,7 +457,7 @@ DCHECK_CURRENTLY_ON(BrowserThread::IO); DCHECK_EQ(storage::kFileSystemTypeArcDocumentsProvider, url.type()); - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {BrowserThread::UI}, base::BindOnce(&DeleteFileOnUIThread, url, std::move(callback))); }
diff --git a/chrome/browser/chromeos/arc/fileapi/arc_documents_provider_file_stream_reader.cc b/chrome/browser/chromeos/arc/fileapi/arc_documents_provider_file_stream_reader.cc index 6bf0591..5b0625a 100644 --- a/chrome/browser/chromeos/arc/fileapi/arc_documents_provider_file_stream_reader.cc +++ b/chrome/browser/chromeos/arc/fileapi/arc_documents_provider_file_stream_reader.cc
@@ -29,8 +29,8 @@ ArcDocumentsProviderRoot::ResolveToContentUrlCallback callback, const GURL& url) { DCHECK_CURRENTLY_ON(BrowserThread::UI); - base::PostTaskWithTraits(FROM_HERE, {BrowserThread::IO}, - base::BindOnce(std::move(callback), url)); + base::PostTask(FROM_HERE, {BrowserThread::IO}, + base::BindOnce(std::move(callback), url)); } void ResolveToContentUrlOnUIThread( @@ -65,7 +65,7 @@ : offset_(offset), content_url_resolved_(false), weak_ptr_factory_(this) { DCHECK_CURRENTLY_ON(BrowserThread::IO); - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {BrowserThread::UI}, base::BindOnce( &ResolveToContentUrlOnUIThread, url,
diff --git a/chrome/browser/chromeos/arc/fileapi/arc_documents_provider_file_stream_writer.cc b/chrome/browser/chromeos/arc/fileapi/arc_documents_provider_file_stream_writer.cc index 102d8ee0..60c43e1f 100644 --- a/chrome/browser/chromeos/arc/fileapi/arc_documents_provider_file_stream_writer.cc +++ b/chrome/browser/chromeos/arc/fileapi/arc_documents_provider_file_stream_writer.cc
@@ -28,8 +28,8 @@ ArcDocumentsProviderRoot::ResolveToContentUrlCallback callback, const GURL& url) { DCHECK_CURRENTLY_ON(BrowserThread::UI); - base::PostTaskWithTraits(FROM_HERE, {BrowserThread::IO}, - base::BindOnce(std::move(callback), url)); + base::PostTask(FROM_HERE, {BrowserThread::IO}, + base::BindOnce(std::move(callback), url)); } void ResolveToContentUrlOnUIThread( @@ -86,7 +86,7 @@ // Resolve the |arc_url_| to a Content URL to instantiate the underlying // writer. - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {BrowserThread::UI}, base::BindOnce( &ResolveToContentUrlOnUIThread, arc_url_,
diff --git a/chrome/browser/chromeos/arc/fileapi/arc_documents_provider_watcher_manager.cc b/chrome/browser/chromeos/arc/fileapi/arc_documents_provider_watcher_manager.cc index e6b0b3f..711e457 100644 --- a/chrome/browser/chromeos/arc/fileapi/arc_documents_provider_watcher_manager.cc +++ b/chrome/browser/chromeos/arc/fileapi/arc_documents_provider_watcher_manager.cc
@@ -25,24 +25,24 @@ const storage::WatcherManager::StatusCallback& callback, base::File::Error result) { DCHECK_CURRENTLY_ON(BrowserThread::UI); - base::PostTaskWithTraits(FROM_HERE, {BrowserThread::IO}, - base::BindOnce(callback, result)); + base::PostTask(FROM_HERE, {BrowserThread::IO}, + base::BindOnce(callback, result)); } void OnRemoveWatcherOnUIThread( const storage::WatcherManager::StatusCallback& callback, base::File::Error result) { DCHECK_CURRENTLY_ON(BrowserThread::UI); - base::PostTaskWithTraits(FROM_HERE, {BrowserThread::IO}, - base::BindOnce(callback, result)); + base::PostTask(FROM_HERE, {BrowserThread::IO}, + base::BindOnce(callback, result)); } void OnNotificationOnUIThread( const storage::WatcherManager::NotificationCallback& notification_callback, ArcDocumentsProviderRoot::ChangeType change_type) { DCHECK_CURRENTLY_ON(BrowserThread::UI); - base::PostTaskWithTraits(FROM_HERE, {BrowserThread::IO}, - base::BindOnce(notification_callback, change_type)); + base::PostTask(FROM_HERE, {BrowserThread::IO}, + base::BindOnce(notification_callback, change_type)); } void AddWatcherOnUIThread( @@ -115,7 +115,7 @@ return; } - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {BrowserThread::UI}, base::BindOnce( &AddWatcherOnUIThread, url, @@ -137,7 +137,7 @@ return; } - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {BrowserThread::UI}, base::BindOnce( &RemoveWatcherOnUIThread, url,
diff --git a/chrome/browser/chromeos/arc/fileapi/arc_file_system_bridge.cc b/chrome/browser/chromeos/arc/fileapi/arc_file_system_bridge.cc index 685ba4d2..c7d2b50 100644 --- a/chrome/browser/chromeos/arc/fileapi/arc_file_system_bridge.cc +++ b/chrome/browser/chromeos/arc/fileapi/arc_file_system_bridge.cc
@@ -101,8 +101,8 @@ file_info.size >= 0) { size = file_info.size; } - base::PostTaskWithTraits(FROM_HERE, {content::BrowserThread::UI}, - base::BindOnce(std::move(callback), size)); + base::PostTask(FROM_HERE, {content::BrowserThread::UI}, + base::BindOnce(std::move(callback), size)); }, base::Passed(&callback))); } @@ -249,7 +249,7 @@ GetFileSystemContext(profile_, url_decoded); file_manager::util::FileSystemURLAndHandle file_system_url_and_handle = GetFileSystemURL(*context, url_decoded); - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {content::BrowserThread::IO}, base::BindOnce(&GetFileSizeOnIOThread, std::move(context), file_system_url_and_handle.url, std::move(callback))); @@ -321,8 +321,8 @@ return; } - base::PostTaskWithTraitsAndReplyWithResult( - FROM_HERE, {base::MayBlock()}, + base::PostTaskAndReplyWithResult( + FROM_HERE, {base::ThreadPool(), base::MayBlock()}, base::BindOnce(&OpenDriveFSFileToRead, fs_path), std::move(callback)); }
diff --git a/chrome/browser/chromeos/arc/fileapi/arc_file_system_operation_runner_util.cc b/chrome/browser/chromeos/arc/fileapi/arc_file_system_operation_runner_util.cc index b707b6da..157dcd54 100644 --- a/chrome/browser/chromeos/arc/fileapi/arc_file_system_operation_runner_util.cc +++ b/chrome/browser/chromeos/arc/fileapi/arc_file_system_operation_runner_util.cc
@@ -32,9 +32,8 @@ template <typename T> void PostToIOThread(base::OnceCallback<void(T)> callback, T result) { DCHECK_CURRENTLY_ON(BrowserThread::UI); - base::PostTaskWithTraits( - FROM_HERE, {BrowserThread::IO}, - base::BindOnce(std::move(callback), std::move(result))); + base::PostTask(FROM_HERE, {BrowserThread::IO}, + base::BindOnce(std::move(callback), std::move(result))); } void GetFileSizeOnUIThread(const GURL& url, GetFileSizeCallback callback) { @@ -79,17 +78,16 @@ void GetFileSizeOnIOThread(const GURL& url, GetFileSizeCallback callback) { DCHECK_CURRENTLY_ON(BrowserThread::IO); - base::PostTaskWithTraits( - FROM_HERE, {BrowserThread::UI}, - base::BindOnce( - &GetFileSizeOnUIThread, url, - base::BindOnce(&PostToIOThread<int64_t>, std::move(callback)))); + base::PostTask(FROM_HERE, {BrowserThread::UI}, + base::BindOnce(&GetFileSizeOnUIThread, url, + base::BindOnce(&PostToIOThread<int64_t>, + std::move(callback)))); } void OpenFileToReadOnIOThread(const GURL& url, OpenFileToReadCallback callback) { DCHECK_CURRENTLY_ON(BrowserThread::IO); - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {BrowserThread::UI}, base::BindOnce(&OpenFileToReadOnUIThread, url, base::BindOnce(&PostToIOThread<mojo::ScopedHandle>, @@ -99,7 +97,7 @@ void OpenFileToWriteOnIOThread(const GURL& url, OpenFileToReadCallback callback) { DCHECK_CURRENTLY_ON(BrowserThread::IO); - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {BrowserThread::UI}, base::BindOnce(&OpenFileToWriteOnUIThread, url, base::BindOnce(&PostToIOThread<mojo::ScopedHandle>,
diff --git a/chrome/browser/chromeos/arc/fileapi/file_stream_forwarder.cc b/chrome/browser/chromeos/arc/fileapi/file_stream_forwarder.cc index 61a6503..2201a49 100644 --- a/chrome/browser/chromeos/arc/fileapi/file_stream_forwarder.cc +++ b/chrome/browser/chromeos/arc/fileapi/file_stream_forwarder.cc
@@ -38,26 +38,24 @@ remaining_size_(size), fd_dest_(std::move(fd_dest)), callback_(std::move(callback)), - task_runner_( - base::CreateSequencedTaskRunnerWithTraits( - // It's safe to shutdown without waiting for the - // completion of tasks running with this task runner. - {base::TaskShutdownBehavior::CONTINUE_ON_SHUTDOWN, - base::MayBlock()})), + task_runner_(base::CreateSequencedTaskRunner( + // It's safe to shutdown without waiting for the + // completion of tasks running with this task runner. + {base::ThreadPool(), base::TaskShutdownBehavior::CONTINUE_ON_SHUTDOWN, + base::MayBlock()})), buf_(base::MakeRefCounted<net::IOBufferWithSize>(kBufSize)), weak_ptr_factory_(this) { DCHECK_CURRENTLY_ON(BrowserThread::UI); - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {BrowserThread::IO}, base::BindOnce(&FileStreamForwarder::Start, base::Unretained(this))); } void FileStreamForwarder::Destroy() { DCHECK_CURRENTLY_ON(BrowserThread::UI); - base::PostTaskWithTraits( - FROM_HERE, {BrowserThread::IO}, - base::BindOnce(&FileStreamForwarder::DestroyOnIOThread, - base::Unretained(this))); + base::PostTask(FROM_HERE, {BrowserThread::IO}, + base::BindOnce(&FileStreamForwarder::DestroyOnIOThread, + base::Unretained(this))); } FileStreamForwarder::~FileStreamForwarder() { @@ -143,8 +141,8 @@ void FileStreamForwarder::NotifyCompleted(bool result) { DCHECK_CURRENTLY_ON(BrowserThread::IO); DCHECK(!callback_.is_null()); - base::PostTaskWithTraits(FROM_HERE, {BrowserThread::UI}, - base::BindOnce(std::move(callback_), result)); + base::PostTask(FROM_HERE, {BrowserThread::UI}, + base::BindOnce(std::move(callback_), result)); } } // namespace arc
diff --git a/chrome/browser/chromeos/arc/oemcrypto/arc_oemcrypto_bridge.cc b/chrome/browser/chromeos/arc/oemcrypto/arc_oemcrypto_bridge.cc index 89a150e..0bf292c 100644 --- a/chrome/browser/chromeos/arc/oemcrypto/arc_oemcrypto_bridge.cc +++ b/chrome/browser/chromeos/arc/oemcrypto/arc_oemcrypto_bridge.cc
@@ -148,8 +148,7 @@ // We need to get the GPU interface on the IO thread, then after that is // done it will run the Mojo call on our thread. base::PostTaskAndReplyWithResult( - base::CreateSingleThreadTaskRunnerWithTraits({content::BrowserThread::IO}) - .get(), + base::CreateSingleThreadTaskRunner({content::BrowserThread::IO}).get(), FROM_HERE, base::BindOnce(&GetGpuBufferManagerOnIOThread), base::BindOnce(&ArcOemCryptoBridge::FinishConnectingToDaemon, weak_factory_.GetWeakPtr(), std::move(request)));
diff --git a/chrome/browser/chromeos/arc/print/arc_print_service.cc b/chrome/browser/chromeos/arc/print/arc_print_service.cc index 94f44ca..413d961ba 100644 --- a/chrome/browser/chromeos/arc/print/arc_print_service.cc +++ b/chrome/browser/chromeos/arc/print/arc_print_service.cc
@@ -172,9 +172,8 @@ // Send initialized PrinterQuery to UI thread. void OnSetSettingsDoneOnIOThread(std::unique_ptr<printing::PrinterQuery> query, PrinterQueryCallback callback) { - base::PostTaskWithTraits( - FROM_HERE, {content::BrowserThread::UI}, - base::BindOnce(std::move(callback), std::move(query))); + base::PostTask(FROM_HERE, {content::BrowserThread::UI}, + base::BindOnce(std::move(callback), std::move(query))); } std::unique_ptr<printing::PrinterSemanticCapsAndDefaults> @@ -306,8 +305,8 @@ } void FetchCapabilities(const chromeos::Printer& printer) { - base::PostTaskWithTraitsAndReplyWithResult( - FROM_HERE, {base::MayBlock()}, + base::PostTaskAndReplyWithResult( + FROM_HERE, {base::ThreadPool(), base::MayBlock()}, base::BindOnce(&FetchCapabilitiesOnBlockingTaskRunner, printer.id()), base::BindOnce(&PrinterDiscoverySessionHostImpl::CapabilitiesReceived, weak_ptr_factory_.GetWeakPtr(), printer)); @@ -389,13 +388,13 @@ // We read printing data from pipe on working thread in parallel with // initializing PrinterQuery on IO thread. When both tasks are complete we // start printing. - base::PostTaskWithTraitsAndReplyWithResult( - FROM_HERE, {base::MayBlock()}, + base::PostTaskAndReplyWithResult( + FROM_HERE, {base::ThreadPool(), base::MayBlock()}, base::BindOnce(&ReadFileOnBlockingTaskRunner, std::move(file), data_size), base::BindOnce(&PrintJobHostImpl::OnFileRead, weak_ptr_factory_.GetWeakPtr())); - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {content::BrowserThread::IO}, base::BindOnce(&CreateQueryOnIOThread, std::move(settings), base::BindOnce(&PrintJobHostImpl::OnSetSettingsDone,
diff --git a/chrome/browser/chromeos/arc/process/arc_process_service.cc b/chrome/browser/chromeos/arc/process/arc_process_service.cc index 54c96bd..7fec4c6b 100644 --- a/chrome/browser/chromeos/arc/process/arc_process_service.cc +++ b/chrome/browser/chromeos/arc/process/arc_process_service.cc
@@ -299,8 +299,9 @@ nspid_to_pid_(new NSPidToPidMap()), weak_ptr_factory_(this) { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); - task_runner_ = base::CreateSequencedTaskRunnerWithTraits( - {base::MayBlock(), base::TaskShutdownBehavior::SKIP_ON_SHUTDOWN, + task_runner_ = base::CreateSequencedTaskRunner( + {base::ThreadPool(), base::MayBlock(), + base::TaskShutdownBehavior::SKIP_ON_SHUTDOWN, base::TaskPriority::USER_VISIBLE}); arc_bridge_service_->process()->AddObserver(this); }
diff --git a/chrome/browser/chromeos/arc/tracing/arc_system_stat_collector.cc b/chrome/browser/chromeos/arc/tracing/arc_system_stat_collector.cc index 67a46f96..04faa8b9 100644 --- a/chrome/browser/chromeos/arc/tracing/arc_system_stat_collector.cc +++ b/chrome/browser/chromeos/arc/tracing/arc_system_stat_collector.cc
@@ -129,8 +129,8 @@ // Maximum 10 warning per session. missed_update_warning_left_ = 10; - background_task_runner_ = base::CreateSequencedTaskRunnerWithTraits( - {base::MayBlock(), base::TaskPriority::USER_VISIBLE}); + background_task_runner_ = base::CreateSequencedTaskRunner( + {base::ThreadPool(), base::MayBlock(), base::TaskPriority::USER_VISIBLE}); timer_.Start( FROM_HERE, kSystemStatUpdateInterval, base::BindRepeating(&ArcSystemStatCollector::ScheduleSystemStatUpdate,
diff --git a/chrome/browser/chromeos/arc/tracing/arc_tracing_bridge.cc b/chrome/browser/chromeos/arc/tracing/arc_tracing_bridge.cc index ea20bda..bfe3f45 100644 --- a/chrome/browser/chromeos/arc/tracing/arc_tracing_bridge.cc +++ b/chrome/browser/chromeos/arc/tracing/arc_tracing_bridge.cc
@@ -128,7 +128,7 @@ const perfetto::DataSourceConfig& data_source_config) override { // |this| never gets destructed, so it's OK to bind an unretained pointer. // |producer| is a singleton that is never destroyed. - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {content::BrowserThread::UI}, base::BindOnce(&ArcTracingDataSource::StartTracingOnUI, base::Unretained(this), producer, data_source_config)); @@ -136,11 +136,10 @@ void StopTracing(base::OnceClosure stop_complete_callback) override { // |this| never gets destructed, so it's OK to bind an unretained pointer. - base::PostTaskWithTraits( - FROM_HERE, {content::BrowserThread::UI}, - base::BindOnce(&ArcTracingDataSource::StopTracingOnUI, - base::Unretained(this), - std::move(stop_complete_callback))); + base::PostTask(FROM_HERE, {content::BrowserThread::UI}, + base::BindOnce(&ArcTracingDataSource::StopTracingOnUI, + base::Unretained(this), + std::move(stop_complete_callback))); } void Flush(base::RepeatingClosure flush_complete_callback) override { @@ -304,7 +303,7 @@ arc_bridge_service_->tracing()->RemoveObserver(this); // Delete the reader on the IO thread. - base::CreateSingleThreadTaskRunnerWithTraits({content::BrowserThread::IO}) + base::CreateSingleThreadTaskRunner({content::BrowserThread::IO}) ->DeleteSoon(FROM_HERE, reader_.release()); } @@ -380,7 +379,7 @@ // |reader_| will be destroyed after us on the IO thread, so it's OK to use an // unretained pointer. - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {content::BrowserThread::IO}, base::BindOnce(&ArcTracingReader::StartTracing, base::Unretained(reader_.get()), std::move(read_fd))); @@ -425,7 +424,7 @@ } // |reader_| will be destroyed after us on the IO thread, so it's OK to use an // unretained pointer. - base::PostTaskWithTraitsAndReplyWithResult( + base::PostTaskAndReplyWithResult( FROM_HERE, {content::BrowserThread::IO}, base::BindOnce(&ArcTracingReader::StopTracing, base::Unretained(reader_.get())),
diff --git a/chrome/browser/chromeos/arc/video/gpu_arc_video_service_host.cc b/chrome/browser/chromeos/arc/video/gpu_arc_video_service_host.cc index 9027a9f0..62a1d0e 100644 --- a/chrome/browser/chromeos/arc/video/gpu_arc_video_service_host.cc +++ b/chrome/browser/chromeos/arc/video/gpu_arc_video_service_host.cc
@@ -61,7 +61,7 @@ void CreateDecodeAccelerator( mojom::VideoDecodeAcceleratorRequest request) override { - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {content::BrowserThread::IO}, base::BindOnce( &content::BindInterfaceInGpuProcess<mojom::VideoDecodeAccelerator>, @@ -70,7 +70,7 @@ void CreateEncodeAccelerator( mojom::VideoEncodeAcceleratorRequest request) override { - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {content::BrowserThread::IO}, base::BindOnce( &content::BindInterfaceInGpuProcess<mojom::VideoEncodeAccelerator>, @@ -79,11 +79,10 @@ void CreateProtectedBufferAllocator( mojom::VideoProtectedBufferAllocatorRequest request) override { - base::PostTaskWithTraits( - FROM_HERE, {content::BrowserThread::IO}, - base::BindOnce(&content::BindInterfaceInGpuProcess< - mojom::VideoProtectedBufferAllocator>, - std::move(request))); + base::PostTask(FROM_HERE, {content::BrowserThread::IO}, + base::BindOnce(&content::BindInterfaceInGpuProcess< + mojom::VideoProtectedBufferAllocator>, + std::move(request))); } private:
diff --git a/chrome/browser/chromeos/arc/wallpaper/arc_wallpaper_service.cc b/chrome/browser/chromeos/arc/wallpaper/arc_wallpaper_service.cc index c360b65..5ab6d632 100644 --- a/chrome/browser/chromeos/arc/wallpaper/arc_wallpaper_service.cc +++ b/chrome/browser/chromeos/arc/wallpaper/arc_wallpaper_service.cc
@@ -157,8 +157,9 @@ void ArcWallpaperService::GetWallpaper(GetWallpaperCallback callback) { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); gfx::ImageSkia image = WallpaperControllerClient::Get()->GetWallpaperImage(); - base::PostTaskWithTraitsAndReplyWithResult( - FROM_HERE, {base::MayBlock(), base::TaskPriority::BEST_EFFORT}, + base::PostTaskAndReplyWithResult( + FROM_HERE, + {base::ThreadPool(), base::MayBlock(), base::TaskPriority::BEST_EFFORT}, base::BindOnce(&EncodeImagePng, image), std::move(callback)); }
diff --git a/chrome/browser/chromeos/attestation/enrollment_certificate_uploader_impl.cc b/chrome/browser/chromeos/attestation/enrollment_certificate_uploader_impl.cc index 3d422acc..25b2396 100644 --- a/chrome/browser/chromeos/attestation/enrollment_certificate_uploader_impl.cc +++ b/chrome/browser/chromeos/attestation/enrollment_certificate_uploader_impl.cc
@@ -165,7 +165,7 @@ void EnrollmentCertificateUploaderImpl::Reschedule() { if (++num_retries_ < retry_limit_) { - base::PostDelayedTaskWithTraits( + base::PostDelayedTask( FROM_HERE, {content::BrowserThread::UI}, base::BindOnce(&EnrollmentCertificateUploaderImpl::GetCertificate, weak_factory_.GetWeakPtr()),
diff --git a/chrome/browser/chromeos/attestation/enrollment_policy_observer.cc b/chrome/browser/chromeos/attestation/enrollment_policy_observer.cc index 882ce7b5..7f3d3d89 100644 --- a/chrome/browser/chromeos/attestation/enrollment_policy_observer.cc +++ b/chrome/browser/chromeos/attestation/enrollment_policy_observer.cc
@@ -161,7 +161,7 @@ void EnrollmentPolicyObserver::RescheduleGetEnrollmentId() { if (++num_retries_ < retry_limit_) { - base::PostDelayedTaskWithTraits( + base::PostDelayedTask( FROM_HERE, {content::BrowserThread::UI}, base::BindOnce(&EnrollmentPolicyObserver::GetEnrollmentId, weak_factory_.GetWeakPtr()),
diff --git a/chrome/browser/chromeos/attestation/machine_certificate_uploader_impl.cc b/chrome/browser/chromeos/attestation/machine_certificate_uploader_impl.cc index 0006634..44fe172 100644 --- a/chrome/browser/chromeos/attestation/machine_certificate_uploader_impl.cc +++ b/chrome/browser/chromeos/attestation/machine_certificate_uploader_impl.cc
@@ -346,7 +346,7 @@ void MachineCertificateUploaderImpl::Reschedule() { if (++num_retries_ < retry_limit_) { - base::PostDelayedTaskWithTraits( + base::PostDelayedTask( FROM_HERE, {content::BrowserThread::UI}, base::BindRepeating(&MachineCertificateUploaderImpl::Start, weak_factory_.GetWeakPtr()),
diff --git a/chrome/browser/chromeos/authpolicy/authpolicy_helper.cc b/chrome/browser/chromeos/authpolicy/authpolicy_helper.cc index 89e3e67..68500dd 100644 --- a/chrome/browser/chromeos/authpolicy/authpolicy_helper.cc +++ b/chrome/browser/chromeos/authpolicy/authpolicy_helper.cc
@@ -147,8 +147,9 @@ void AuthPolicyHelper::DecryptConfiguration(const std::string& blob, const std::string& password, OnDecryptedCallback callback) { - base::PostTaskWithTraitsAndReplyWithResult( - FROM_HERE, {base::TaskShutdownBehavior::SKIP_ON_SHUTDOWN}, + base::PostTaskAndReplyWithResult( + FROM_HERE, + {base::ThreadPool(), base::TaskShutdownBehavior::SKIP_ON_SHUTDOWN}, base::BindOnce(&DoDecrypt, blob, password), std::move(callback)); }
diff --git a/chrome/browser/chromeos/authpolicy/kerberos_files_handler.cc b/chrome/browser/chromeos/authpolicy/kerberos_files_handler.cc index cdeb0a44..de5075c9 100644 --- a/chrome/browser/chromeos/authpolicy/kerberos_files_handler.cc +++ b/chrome/browser/chromeos/authpolicy/kerberos_files_handler.cc
@@ -137,9 +137,9 @@ base::Optional<std::string> krb5conf) { krb5conf = MaybeAdjustConfig(krb5conf, !negotiate_disable_cname_lookup_.GetValue()); - base::PostTaskWithTraitsAndReply( + base::PostTaskAndReply( FROM_HERE, - {base::MayBlock(), base::TaskPriority::BEST_EFFORT, + {base::ThreadPool(), base::MayBlock(), base::TaskPriority::BEST_EFFORT, base::TaskShutdownBehavior::SKIP_ON_SHUTDOWN}, base::BindOnce(&WriteFiles, std::move(krb5cc), std::move(krb5conf)), base::BindOnce(&KerberosFilesHandler::OnFilesChanged, @@ -149,9 +149,9 @@ void KerberosFilesHandler::DeleteFiles() { // These files contain user credentials, so use BLOCK_SHUTDOWN here to make // sure they do get deleted. - base::PostTaskWithTraitsAndReply( + base::PostTaskAndReply( FROM_HERE, - {base::MayBlock(), base::TaskPriority::BEST_EFFORT, + {base::ThreadPool(), base::MayBlock(), base::TaskPriority::BEST_EFFORT, base::TaskShutdownBehavior::BLOCK_SHUTDOWN}, base::BindOnce(&RemoveFiles), base::BindOnce(&KerberosFilesHandler::OnFilesChanged,
diff --git a/chrome/browser/chromeos/base/file_flusher.cc b/chrome/browser/chromeos/base/file_flusher.cc index 258ba39..df7cc0a 100644 --- a/chrome/browser/chromeos/base/file_flusher.cc +++ b/chrome/browser/chromeos/base/file_flusher.cc
@@ -98,8 +98,9 @@ return; } - base::PostTaskWithTraitsAndReply( - FROM_HERE, {base::MayBlock(), base::TaskPriority::BEST_EFFORT}, + base::PostTaskAndReply( + FROM_HERE, + {base::ThreadPool(), base::MayBlock(), base::TaskPriority::BEST_EFFORT}, base::Bind(&FileFlusher::Job::FlushAsync, base::Unretained(this)), base::Bind(&FileFlusher::Job::FinishOnUIThread, base::Unretained(this))); } @@ -149,7 +150,7 @@ return; finish_scheduled_ = true; - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {content::BrowserThread::UI}, base::BindOnce(&Job::FinishOnUIThread, base::Unretained(this))); }
diff --git a/chrome/browser/chromeos/base/locale_util.cc b/chrome/browser/chromeos/base/locale_util.cc index 39570d34..43fe8f66 100644 --- a/chrome/browser/chromeos/base/locale_util.cc +++ b/chrome/browser/chromeos/base/locale_util.cc
@@ -148,8 +148,9 @@ locale, enable_locale_keyboard_layouts, login_layouts_only, callback, profile); // USER_BLOCKING because it blocks startup on ChromeOS. crbug.com/968554 - base::PostTaskWithTraitsAndReplyWithResult( - FROM_HERE, {base::MayBlock(), base::TaskPriority::USER_BLOCKING}, + base::PostTaskAndReplyWithResult( + FROM_HERE, + {base::ThreadPool(), base::MayBlock(), base::TaskPriority::USER_BLOCKING}, base::BindOnce(&SwitchLanguageDoReloadLocale, std::move(data)), base::BindOnce(&FinishSwitchLanguage)); }
diff --git a/chrome/browser/chromeos/boot_times_recorder.cc b/chrome/browser/chromeos/boot_times_recorder.cc index 57df35e..79b2ac7 100644 --- a/chrome/browser/chromeos/boot_times_recorder.cc +++ b/chrome/browser/chromeos/boot_times_recorder.cc
@@ -218,8 +218,9 @@ } void BootTimesRecorder::Stats::RecordStats(const std::string& name) const { - base::PostTaskWithTraits( - FROM_HERE, {base::MayBlock(), base::TaskPriority::BEST_EFFORT}, + base::PostTask( + FROM_HERE, + {base::ThreadPool(), base::MayBlock(), base::TaskPriority::BEST_EFFORT}, base::BindOnce(&BootTimesRecorder::Stats::RecordStatsAsync, base::Owned(new Stats(*this)), name)); } @@ -227,8 +228,9 @@ void BootTimesRecorder::Stats::RecordStatsWithCallback( const std::string& name, const base::Closure& callback) const { - base::PostTaskWithTraitsAndReply( - FROM_HERE, {base::MayBlock(), base::TaskPriority::BEST_EFFORT}, + base::PostTaskAndReply( + FROM_HERE, + {base::ThreadPool(), base::MayBlock(), base::TaskPriority::BEST_EFFORT}, base::Bind(&BootTimesRecorder::Stats::RecordStatsAsync, base::Owned(new Stats(*this)), name), callback); @@ -346,8 +348,9 @@ content::NotificationService::AllSources()); } // Don't swamp the background thread right away. - base::PostDelayedTaskWithTraits( - FROM_HERE, {base::MayBlock(), base::TaskPriority::BEST_EFFORT}, + base::PostDelayedTask( + FROM_HERE, + {base::ThreadPool(), base::MayBlock(), base::TaskPriority::BEST_EFFORT}, base::BindOnce(&WriteTimes, kLoginTimes, (is_user_new ? kUmaLoginNewUser : kUmaLogin), kUmaLoginPrefix, login_time_markers_), @@ -471,9 +474,9 @@ // Add the marker on the UI thread. // Note that it's safe to use an unretained pointer to the vector because // BootTimesRecorder's lifetime exceeds that of the UI thread message loop. - base::PostTaskWithTraits(FROM_HERE, {BrowserThread::UI}, - base::BindOnce(&BootTimesRecorder::AddMarker, - base::Unretained(vector), marker)); + base::PostTask(FROM_HERE, {BrowserThread::UI}, + base::BindOnce(&BootTimesRecorder::AddMarker, + base::Unretained(vector), marker)); } }
diff --git a/chrome/browser/chromeos/camera_detector.cc b/chrome/browser/chromeos/camera_detector.cc index be39a67..6d1043e 100644 --- a/chrome/browser/chromeos/camera_detector.cc +++ b/chrome/browser/chromeos/camera_detector.cc
@@ -47,9 +47,9 @@ DVLOG(1) << "Starting camera presence check"; presence_check_in_progress_ = true; base::PostTaskAndReplyWithResult( - base::CreateTaskRunnerWithTraits( - {base::MayBlock(), base::TaskPriority::BEST_EFFORT, - base::TaskShutdownBehavior::SKIP_ON_SHUTDOWN}) + base::CreateTaskRunner({base::ThreadPool(), base::MayBlock(), + base::TaskPriority::BEST_EFFORT, + base::TaskShutdownBehavior::SKIP_ON_SHUTDOWN}) .get(), FROM_HERE, base::Bind(&CameraDetector::CheckPresence), base::Bind(&CameraDetector::OnPresenceCheckDone, callback));
diff --git a/chrome/browser/chromeos/certificate_provider/certificate_provider_service.cc b/chrome/browser/chromeos/certificate_provider/certificate_provider_service.cc index f88def0..afc0145d 100644 --- a/chrome/browser/chromeos/certificate_provider/certificate_provider_service.cc +++ b/chrome/browser/chromeos/certificate_provider/certificate_provider_service.cc
@@ -258,8 +258,9 @@ std::move(callback).Run(net::ERR_FAILED, no_signature); return; } - service->RequestSignatureFromExtension(extension_id, certificate, algorithm, - input, std::move(callback)); + service->RequestSignatureFromExtension( + extension_id, certificate, algorithm, input, + /*authenticating_user_account_id=*/{}, std::move(callback)); } void CertificateProviderService::SSLPrivateKey::Sign( @@ -428,6 +429,7 @@ const std::string& subject_public_key_info, uint16_t algorithm, base::span<const uint8_t> digest, + const base::Optional<AccountId>& authenticating_user_account_id, net::SSLPrivateKey::SignCallback callback) { DCHECK(thread_checker_.CalledOnValidThread()); bool is_currently_provided = false; @@ -442,7 +444,8 @@ } RequestSignatureFromExtension(extension_id, info.certificate, algorithm, - digest, std::move(callback)); + digest, authenticating_user_account_id, + std::move(callback)); } bool CertificateProviderService::GetSupportedAlgorithmsBySpki( @@ -526,11 +529,14 @@ const scoped_refptr<net::X509Certificate>& certificate, uint16_t algorithm, base::span<const uint8_t> digest, + const base::Optional<AccountId>& authenticating_user_account_id, net::SSLPrivateKey::SignCallback callback) { DCHECK(thread_checker_.CalledOnValidThread()); const int sign_request_id = sign_requests_.AddRequest(extension_id, certificate, std::move(callback)); + pin_dialog_manager_.AddSignRequestId(extension_id, sign_request_id, + authenticating_user_account_id); if (!delegate_->DispatchSignRequestToExtension( extension_id, sign_request_id, algorithm, certificate, digest)) { scoped_refptr<net::X509Certificate> local_certificate;
diff --git a/chrome/browser/chromeos/certificate_provider/certificate_provider_service.h b/chrome/browser/chromeos/certificate_provider/certificate_provider_service.h index 4d310ffd..af1e523 100644 --- a/chrome/browser/chromeos/certificate_provider/certificate_provider_service.h +++ b/chrome/browser/chromeos/certificate_provider/certificate_provider_service.h
@@ -18,12 +18,14 @@ #include "base/memory/ref_counted.h" #include "base/memory/weak_ptr.h" #include "base/observer_list.h" +#include "base/optional.h" #include "base/threading/thread_checker.h" #include "chrome/browser/chromeos/certificate_provider/certificate_info.h" #include "chrome/browser/chromeos/certificate_provider/certificate_requests.h" #include "chrome/browser/chromeos/certificate_provider/pin_dialog_manager.h" #include "chrome/browser/chromeos/certificate_provider/sign_requests.h" #include "chrome/browser/chromeos/certificate_provider/thread_safe_certificate_map.h" +#include "components/account_id/account_id.h" #include "components/keyed_service/core/keyed_service.h" #include "net/cert/x509_certificate.h" #include "net/ssl/client_cert_identity.h" @@ -170,10 +172,12 @@ // key. |algorithm| is a TLS 1.3 SignatureScheme value. See net::SSLPrivateKey // for details. |callback| will be run with the reply of the extension or an // error. - void RequestSignatureBySpki(const std::string& subject_public_key_info, - uint16_t algorithm, - base::span<const uint8_t> digest, - net::SSLPrivateKey::SignCallback callback); + void RequestSignatureBySpki( + const std::string& subject_public_key_info, + uint16_t algorithm, + base::span<const uint8_t> digest, + const base::Optional<AccountId>& authenticating_user_account_id, + net::SSLPrivateKey::SignCallback callback); // Looks up the certificate identified by |subject_public_key_info|. If any // extension is currently providing such a certificate, fills @@ -222,6 +226,7 @@ const scoped_refptr<net::X509Certificate>& certificate, uint16_t algorithm, base::span<const uint8_t> digest, + const base::Optional<AccountId>& authenticating_user_account_id, net::SSLPrivateKey::SignCallback callback); std::unique_ptr<Delegate> delegate_;
diff --git a/chrome/browser/chromeos/certificate_provider/certificate_provider_service_factory.cc b/chrome/browser/chromeos/certificate_provider/certificate_provider_service_factory.cc index f37608cf..0598a424 100644 --- a/chrome/browser/chromeos/certificate_provider/certificate_provider_service_factory.cc +++ b/chrome/browser/chromeos/certificate_provider/certificate_provider_service_factory.cc
@@ -40,6 +40,7 @@ class DefaultDelegate : public CertificateProviderService::Delegate, public extensions::ExtensionRegistryObserver { public: + // |event_router| may be null in tests. DefaultDelegate(CertificateProviderService* service, extensions::ExtensionRegistry* registry, extensions::EventRouter* event_router); @@ -73,7 +74,6 @@ extensions::EventRouter* event_router) : service_(service), registry_(registry), event_router_(event_router) { DCHECK(service_); - DCHECK(event_router_); registry_->AddObserver(this); } @@ -112,7 +112,6 @@ return false; api_cp::SignRequest request; - service_->pin_dialog_manager()->AddSignRequestId(extension_id, request_id); request.sign_request_id = request_id; switch (algorithm) { case SSL_SIGN_RSA_PKCS1_MD5_SHA1:
diff --git a/chrome/browser/chromeos/certificate_provider/certificate_provider_service_unittest.cc b/chrome/browser/chromeos/certificate_provider/certificate_provider_service_unittest.cc index f75471c..ae87372 100644 --- a/chrome/browser/chromeos/certificate_provider/certificate_provider_service_unittest.cc +++ b/chrome/browser/chromeos/certificate_provider/certificate_provider_service_unittest.cc
@@ -572,6 +572,7 @@ std::vector<uint8_t> received_signature; service_->RequestSignatureBySpki( client1_spki, SSL_SIGN_RSA_PKCS1_SHA256, input, + /*authenticating_user_account_id=*/{}, base::BindOnce(&ExpectOKAndStoreSignature, &received_signature)); task_runner_->RunUntilIdle();
diff --git a/chrome/browser/chromeos/certificate_provider/pin_dialog_manager.cc b/chrome/browser/chromeos/certificate_provider/pin_dialog_manager.cc index de251fa..429b56a 100644 --- a/chrome/browser/chromeos/certificate_provider/pin_dialog_manager.cc +++ b/chrome/browser/chromeos/certificate_provider/pin_dialog_manager.cc
@@ -18,11 +18,14 @@ PinDialogManager::~PinDialogManager() = default; -void PinDialogManager::AddSignRequestId(const std::string& extension_id, - int sign_request_id) { +void PinDialogManager::AddSignRequestId( + const std::string& extension_id, + int sign_request_id, + const base::Optional<AccountId>& authenticating_user_account_id) { ExtensionNameRequestIdPair key(extension_id, sign_request_id); - // Cache the ID with current timestamp. - sign_request_times_[key] = base::Time::Now(); + sign_requests_.insert( + std::make_pair(key, SignRequestState(/*begin_time=*/base::Time::Now(), + authenticating_user_account_id))); } PinDialogManager::RequestPinResult PinDialogManager::RequestPin( @@ -36,6 +39,12 @@ DCHECK_GE(attempts_left, -1); const bool accept_input = (attempts_left != 0); + // Check the validity of sign_request_id. + const SignRequestState* const sign_request_state = + FindSignRequestState(extension_id, sign_request_id); + if (!sign_request_state) + return RequestPinResult::kInvalidId; + // Start from sanity checks, as the extension might have issued this call // incorrectly. if (active_dialog_state_) { @@ -50,22 +59,20 @@ return RequestPinResult::kDialogDisplayedAlready; } } else { - // Check the validity of sign_request_id - const ExtensionNameRequestIdPair key(extension_id, sign_request_id); - if (sign_request_times_.find(key) == sign_request_times_.end()) - return RequestPinResult::kInvalidId; + // Check that the sign request hasn't timed out yet. const base::Time current_time = base::Time::Now(); - if (current_time - sign_request_times_[key] > kSignRequestIdTimeout) + if (current_time - sign_request_state->begin_time > kSignRequestIdTimeout) return RequestPinResult::kInvalidId; // A new dialog will be opened, so initialize the related internal state. active_dialog_state_.emplace(GetHostForNewDialog(), extension_id, - extension_name, code_type); + extension_name, sign_request_id, code_type); } active_dialog_state_->request_pin_callback = std::move(callback); active_dialog_state_->host->ShowSecurityTokenPinDialog( extension_name, code_type, accept_input, error_label, attempts_left, + sign_request_state->authenticating_user_account_id, base::BindOnce(&PinDialogManager::OnPinEntered, weak_factory_.GetWeakPtr()), base::BindOnce(&PinDialogManager::OnPinDialogClosed, @@ -92,11 +99,16 @@ return StopPinRequestResult::kNoUserInput; } + const SignRequestState* const sign_request_state = + FindSignRequestState(extension_id, active_dialog_state_->sign_request_id); + if (!sign_request_state) + return StopPinRequestResult::kNoActiveDialog; + active_dialog_state_->stop_pin_request_callback = std::move(callback); active_dialog_state_->host->ShowSecurityTokenPinDialog( active_dialog_state_->extension_name, active_dialog_state_->code_type, /*enable_user_input=*/false, error_label, - /*attempts_left=*/-1, + /*attempts_left=*/-1, sign_request_state->authenticating_user_account_id, base::BindOnce(&PinDialogManager::OnPinEntered, weak_factory_.GetWeakPtr()), base::BindOnce(&PinDialogManager::OnPinDialogClosed, @@ -133,10 +145,9 @@ last_response_closed_[extension_id] = false; - for (auto it = sign_request_times_.cbegin(); - it != sign_request_times_.cend();) { + for (auto it = sign_requests_.cbegin(); it != sign_requests_.cend();) { if (it->first.first == extension_id) - sign_request_times_.erase(it++); + sign_requests_.erase(it++); else ++it; } @@ -156,18 +167,43 @@ base::Erase(added_dialog_hosts_, pin_dialog_host); } +PinDialogManager::SignRequestState::SignRequestState( + base::Time begin_time, + const base::Optional<AccountId>& authenticating_user_account_id) + : begin_time(begin_time), + authenticating_user_account_id(authenticating_user_account_id) {} + +PinDialogManager::SignRequestState::SignRequestState(const SignRequestState&) = + default; +PinDialogManager::SignRequestState& PinDialogManager::SignRequestState:: +operator=(const SignRequestState&) = default; + +PinDialogManager::SignRequestState::~SignRequestState() = default; + PinDialogManager::ActiveDialogState::ActiveDialogState( SecurityTokenPinDialogHost* host, const std::string& extension_id, const std::string& extension_name, + int sign_request_id, SecurityTokenPinCodeType code_type) : host(host), extension_id(extension_id), extension_name(extension_name), + sign_request_id(sign_request_id), code_type(code_type) {} PinDialogManager::ActiveDialogState::~ActiveDialogState() = default; +PinDialogManager::SignRequestState* PinDialogManager::FindSignRequestState( + const std::string& extension_id, + int sign_request_id) { + const ExtensionNameRequestIdPair key(extension_id, sign_request_id); + const auto sign_request_iter = sign_requests_.find(key); + if (sign_request_iter == sign_requests_.end()) + return nullptr; + return &sign_request_iter->second; +} + void PinDialogManager::OnPinEntered(const std::string& user_input) { DCHECK(!active_dialog_state_->stop_pin_request_callback); last_response_closed_[active_dialog_state_->extension_id] = false;
diff --git a/chrome/browser/chromeos/certificate_provider/pin_dialog_manager.h b/chrome/browser/chromeos/certificate_provider/pin_dialog_manager.h index 7884a41d..9b99f8ad 100644 --- a/chrome/browser/chromeos/certificate_provider/pin_dialog_manager.h +++ b/chrome/browser/chromeos/certificate_provider/pin_dialog_manager.h
@@ -18,6 +18,7 @@ #include "chrome/browser/chromeos/certificate_provider/security_token_pin_dialog_host.h" #include "chrome/browser/chromeos/certificate_provider/security_token_pin_dialog_host_popup_impl.h" #include "chromeos/constants/security_token_pin_types.h" +#include "components/account_id/account_id.h" namespace chromeos { @@ -49,7 +50,10 @@ ~PinDialogManager(); // Stores internally the |signRequestId| along with current timestamp. - void AddSignRequestId(const std::string& extension_id, int sign_request_id); + void AddSignRequestId( + const std::string& extension_id, + int sign_request_id, + const base::Optional<AccountId>& authenticating_user_account_id); // Creates and displays a new PIN dialog, or reuses the old dialog with just // updating the parameters if active one exists. @@ -113,11 +117,24 @@ } private: + struct SignRequestState { + SignRequestState( + base::Time begin_time, + const base::Optional<AccountId>& authenticating_user_account_id); + SignRequestState(const SignRequestState&); + SignRequestState& operator=(const SignRequestState&); + ~SignRequestState(); + + base::Time begin_time; + base::Optional<AccountId> authenticating_user_account_id; + }; + // Holds information related to the currently opened PIN dialog. struct ActiveDialogState { ActiveDialogState(SecurityTokenPinDialogHost* host, const std::string& extension_id, const std::string& extension_name, + int sign_request_id, SecurityTokenPinCodeType code_type); ~ActiveDialogState(); @@ -128,6 +145,7 @@ const std::string extension_id; const std::string extension_name; + const int sign_request_id; const SecurityTokenPinCodeType code_type; RequestPinCallback request_pin_callback; StopPinRequestCallback stop_pin_request_callback; @@ -135,6 +153,10 @@ using ExtensionNameRequestIdPair = std::pair<std::string, int>; + // Returns the sign request state for the given key, or null if not found. + SignRequestState* FindSignRequestState(const std::string& extension_id, + int sign_request_id); + // The callback that gets invoked once the user sends some input into the PIN // dialog. void OnPinEntered(const std::string& user_input); @@ -155,9 +177,9 @@ // been exceeded. std::unordered_map<std::string, bool> last_response_closed_; - // The map with extension_id and sign request id issued by Chrome as key while - // the time when the id was generated is the value. - std::map<ExtensionNameRequestIdPair, base::Time> sign_request_times_; + // The map from extension_id and an active sign request id to the state of the + // request. + std::map<ExtensionNameRequestIdPair, SignRequestState> sign_requests_; SecurityTokenPinDialogHostPopupImpl default_dialog_host_; // The list of dynamically added dialog hosts, in the same order as they were
diff --git a/chrome/browser/chromeos/certificate_provider/security_token_pin_dialog_host.h b/chrome/browser/chromeos/certificate_provider/security_token_pin_dialog_host.h index 89f96358..8963c936 100644 --- a/chrome/browser/chromeos/certificate_provider/security_token_pin_dialog_host.h +++ b/chrome/browser/chromeos/certificate_provider/security_token_pin_dialog_host.h
@@ -8,7 +8,9 @@ #include <string> #include "base/callback_forward.h" +#include "base/optional.h" #include "chromeos/constants/security_token_pin_types.h" +#include "components/account_id/account_id.h" namespace chromeos { @@ -43,6 +45,8 @@ // (note that a non-empty error does NOT disable the user input per se). // |attempts_left| - when non-negative, the UI should indicate this number to // the user; otherwise must be equal to -1. + // |authenticating_user_account_id| - when set, is the ID of the user whose + // authentication triggered this PIN request. // |pin_entered_callback| - called when the user submits the input. // |pin_dialog_closed_callback| - called when the dialog is closed (either by // the user or programmatically; it's optional whether to call it after @@ -53,6 +57,7 @@ bool enable_user_input, SecurityTokenPinErrorLabel error_label, int attempts_left, + const base::Optional<AccountId>& authenticating_user_account_id, SecurityTokenPinEnteredCallback pin_entered_callback, SecurityTokenPinDialogClosedCallback pin_dialog_closed_callback) = 0;
diff --git a/chrome/browser/chromeos/certificate_provider/security_token_pin_dialog_host_popup_impl.cc b/chrome/browser/chromeos/certificate_provider/security_token_pin_dialog_host_popup_impl.cc index fb7a168..4d2b41d 100644 --- a/chrome/browser/chromeos/certificate_provider/security_token_pin_dialog_host_popup_impl.cc +++ b/chrome/browser/chromeos/certificate_provider/security_token_pin_dialog_host_popup_impl.cc
@@ -50,6 +50,7 @@ bool enable_user_input, SecurityTokenPinErrorLabel error_label, int attempts_left, + const base::Optional<AccountId>& /*authenticating_user_account_id*/, SecurityTokenPinEnteredCallback pin_entered_callback, SecurityTokenPinDialogClosedCallback pin_dialog_closed_callback) { DCHECK(!caller_extension_name.empty());
diff --git a/chrome/browser/chromeos/certificate_provider/security_token_pin_dialog_host_popup_impl.h b/chrome/browser/chromeos/certificate_provider/security_token_pin_dialog_host_popup_impl.h index 2178217a..a2abe74f 100644 --- a/chrome/browser/chromeos/certificate_provider/security_token_pin_dialog_host_popup_impl.h +++ b/chrome/browser/chromeos/certificate_provider/security_token_pin_dialog_host_popup_impl.h
@@ -38,6 +38,7 @@ bool enable_user_input, SecurityTokenPinErrorLabel error_label, int attempts_left, + const base::Optional<AccountId>& authenticating_user_account_id, SecurityTokenPinEnteredCallback pin_entered_callback, SecurityTokenPinDialogClosedCallback pin_dialog_closed_callback) override; void CloseSecurityTokenPinDialog() override;
diff --git a/chrome/browser/chromeos/chrome_browser_main_chromeos.cc b/chrome/browser/chromeos/chrome_browser_main_chromeos.cc index aad1c0e2..d40af48 100644 --- a/chrome/browser/chromeos/chrome_browser_main_chromeos.cc +++ b/chrome/browser/chromeos/chrome_browser_main_chromeos.cc
@@ -249,10 +249,9 @@ void GotSystemSlotOnIOThread( base::Callback<void(crypto::ScopedPK11Slot)> callback_ui_thread, crypto::ScopedPK11Slot system_slot) { - base::PostTaskWithTraits( - FROM_HERE, {content::BrowserThread::UI}, - base::BindOnce(&GotSystemSlotOnUIThread, callback_ui_thread, - std::move(system_slot))); + base::PostTask(FROM_HERE, {content::BrowserThread::UI}, + base::BindOnce(&GotSystemSlotOnUIThread, callback_ui_thread, + std::move(system_slot))); } // Called on IO Thread, initiates retrieval of system slot. |callback_ui_thread| @@ -516,9 +515,8 @@ base::Callback<void(crypto::ScopedPK11Slot)> callback = base::BindRepeating(&SystemTokenCertDBInitializer::InitializeDatabase, weak_ptr_factory_.GetWeakPtr()); - base::PostTaskWithTraits( - FROM_HERE, {content::BrowserThread::IO}, - base::BindOnce(&GetSystemSlotOnIOThread, callback)); + base::PostTask(FROM_HERE, {content::BrowserThread::IO}, + base::BindOnce(&GetSystemSlotOnIOThread, callback)); } // Initializes the global system token NSSCertDatabase with |system_slot|. @@ -649,8 +647,7 @@ // Set the crypto thread after the IO thread has been created/started. TPMTokenLoader::Get()->SetCryptoTaskRunner( - base::CreateSingleThreadTaskRunnerWithTraits( - {content::BrowserThread::IO})); + base::CreateSingleThreadTaskRunner({content::BrowserThread::IO})); // Initialize NSS database for system token. system_token_certdb_initializer_ = @@ -783,8 +780,9 @@ // must be placed after UserManager::SessionStarted(); MagnificationManager::Initialize(); - base::PostTaskWithTraitsAndReplyWithResult( - FROM_HERE, {base::MayBlock(), base::TaskPriority::BEST_EFFORT}, + base::PostTaskAndReplyWithResult( + FROM_HERE, + {base::ThreadPool(), base::MayBlock(), base::TaskPriority::BEST_EFFORT}, base::Bind(&version_loader::GetVersion, version_loader::VERSION_FULL), base::Bind(&ChromeOSVersionCallback));
diff --git a/chrome/browser/chromeos/crostini/crostini_export_import.cc b/chrome/browser/chromeos/crostini/crostini_export_import.cc index 5fb6ebc..4f87d72 100644 --- a/chrome/browser/chromeos/crostini/crostini_export_import.cc +++ b/chrome/browser/chromeos/crostini/crostini_export_import.cc
@@ -182,8 +182,8 @@ switch (type) { case ExportImportType::EXPORT: - base::PostTaskWithTraitsAndReply( - FROM_HERE, {base::MayBlock()}, + base::PostTaskAndReply( + FROM_HERE, {base::ThreadPool(), base::MayBlock()}, // Ensure file exists so that it can be shared. base::BindOnce( [](const base::FilePath& path) { @@ -251,10 +251,11 @@ // If a user requests to cancel, but the export completes before the // cancel can happen (|result| == SUCCESS), then removing the exported // file is functionally the same as a successful cancel. - base::PostTaskWithTraits( - FROM_HERE, {base::MayBlock(), base::TaskPriority::BEST_EFFORT}, - base::BindOnce(base::IgnoreResult(&base::DeleteFile), - it->second->path(), false)); + base::PostTask(FROM_HERE, + {base::ThreadPool(), base::MayBlock(), + base::TaskPriority::BEST_EFFORT}, + base::BindOnce(base::IgnoreResult(&base::DeleteFile), + it->second->path(), false)); RemoveNotification(it).SetStatusCancelled(); break; } @@ -272,10 +273,11 @@ // If a user requests to cancel, and the export is cancelled (|result| // == CONTAINER_EXPORT_IMPORT_CANCELLED), then the partially exported // file needs to be cleaned up. - base::PostTaskWithTraits( - FROM_HERE, {base::MayBlock(), base::TaskPriority::BEST_EFFORT}, - base::BindOnce(base::IgnoreResult(&base::DeleteFile), - it->second->path(), false)); + base::PostTask(FROM_HERE, + {base::ThreadPool(), base::MayBlock(), + base::TaskPriority::BEST_EFFORT}, + base::BindOnce(base::IgnoreResult(&base::DeleteFile), + it->second->path(), false)); RemoveNotification(it).SetStatusCancelled(); break; } @@ -284,8 +286,9 @@ } } else { LOG(ERROR) << "Error exporting " << int(result); - base::PostTaskWithTraits( - FROM_HERE, {base::MayBlock(), base::TaskPriority::BEST_EFFORT}, + base::PostTask( + FROM_HERE, + {base::ThreadPool(), base::MayBlock(), base::TaskPriority::BEST_EFFORT}, base::BindOnce(base::IgnoreResult(&base::DeleteFile), it->second->path(), false)); switch (result) {
diff --git a/chrome/browser/chromeos/crostini/crostini_manager.cc b/chrome/browser/chromeos/crostini/crostini_manager.cc index 16296df..1c002f9 100644 --- a/chrome/browser/chromeos/crostini/crostini_manager.cc +++ b/chrome/browser/chromeos/crostini/crostini_manager.cc
@@ -132,7 +132,7 @@ is_running_ = true; // Skip to the end immediately if testing. if (crostini_manager_->skip_restart_for_testing()) { - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {content::BrowserThread::UI}, base::BindOnce(&CrostiniRestarter::StartLxdContainerFinished, base::WrapRefCounted(this), CrostiniResult::SUCCESS)); @@ -603,8 +603,8 @@ // |component_manager| may be nullptr in unit tests. return; } - base::PostTaskWithTraitsAndReply( - FROM_HERE, {base::MayBlock()}, + base::PostTaskAndReply( + FROM_HERE, {base::ThreadPool(), base::MayBlock()}, base::BindOnce(CrostiniManager::CheckPathsAndComponents), base::BindOnce(&CrostiniManager::MaybeUpgradeCrostiniAfterChecks, weak_ptr_factory_.GetWeakPtr())); @@ -646,7 +646,7 @@ g_browser_process->platform_part()->cros_component_manager(); if (!cros_component_manager) { // Running in a unit test. We still PostTask to prevent races. - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {content::BrowserThread::UI}, base::BindOnce(&CrostiniManager::OnInstallTerminaComponent, weak_ptr_factory_.GetWeakPtr(), std::move(callback),
diff --git a/chrome/browser/chromeos/crostini/crostini_registry_service.cc b/chrome/browser/chromeos/crostini/crostini_registry_service.cc index 3e389a7..da774962 100644 --- a/chrome/browser/chromeos/crostini/crostini_registry_service.cc +++ b/chrome/browser/chromeos/crostini/crostini_registry_service.cc
@@ -847,8 +847,9 @@ retry_icon_requests_.erase(app_id); // Remove local data on filesystem for the icons. - base::PostTaskWithTraits( - FROM_HERE, {base::MayBlock(), base::TaskPriority::BEST_EFFORT}, + base::PostTask( + FROM_HERE, + {base::ThreadPool(), base::MayBlock(), base::TaskPriority::BEST_EFFORT}, base::BindOnce(&DeleteIconFolderFromFileThread, GetAppPath(app_id))); } @@ -957,8 +958,9 @@ return; // Now install the icon that we received. const base::FilePath icon_path = GetIconPath(app_id, scale_factor); - base::PostTaskWithTraitsAndReplyWithResult( - FROM_HERE, {base::MayBlock(), base::TaskPriority::BEST_EFFORT}, + base::PostTaskAndReplyWithResult( + FROM_HERE, + {base::ThreadPool(), base::MayBlock(), base::TaskPriority::BEST_EFFORT}, base::BindOnce(&InstallIconFromFileThread, icon_path, icons[0].content), base::BindOnce(&CrostiniRegistryService::OnIconInstalled, weak_ptr_factory_.GetWeakPtr(), app_id, scale_factor));
diff --git a/chrome/browser/chromeos/crostini/crosvm_metrics.cc b/chrome/browser/chromeos/crostini/crosvm_metrics.cc index fdadf45..d68bc4af 100644 --- a/chrome/browser/chromeos/crostini/crosvm_metrics.cc +++ b/chrome/browser/chromeos/crostini/crosvm_metrics.cc
@@ -33,12 +33,12 @@ } // namespace CrosvmMetrics::CrosvmMetrics() - : task_runner_(base::CreateSequencedTaskRunnerWithTraits( - {base::MayBlock(), base::TaskPriority::BEST_EFFORT, + : task_runner_(base::CreateSequencedTaskRunner( + {base::ThreadPool(), base::MayBlock(), + base::TaskPriority::BEST_EFFORT, base::TaskShutdownBehavior::SKIP_ON_SHUTDOWN})), page_size_(sysconf(_SC_PAGESIZE)), - weak_ptr_factory_(this) { -} + weak_ptr_factory_(this) {} CrosvmMetrics::~CrosvmMetrics() = default;
diff --git a/chrome/browser/chromeos/customization/customization_document.cc b/chrome/browser/chromeos/customization/customization_document.cc index 884e6588..dfd7d755 100644 --- a/chrome/browser/chromeos/customization/customization_document.cc +++ b/chrome/browser/chromeos/customization/customization_document.cc
@@ -552,8 +552,10 @@ if (url_.is_valid()) { load_started_ = true; if (url_.SchemeIsFile()) { - base::PostTaskWithTraitsAndReplyWithResult( - FROM_HERE, {base::TaskPriority::BEST_EFFORT, base::MayBlock()}, + base::PostTaskAndReplyWithResult( + FROM_HERE, + {base::ThreadPool(), base::TaskPriority::BEST_EFFORT, + base::MayBlock()}, base::BindOnce(&ReadFileInBackground, base::FilePath(url_.path())), base::BindOnce(&ServicesCustomizationDocument::OnManifestRead, weak_ptr_factory_.GetWeakPtr())); @@ -641,7 +643,7 @@ } else { if (num_retries_ < kMaxFetchRetries) { num_retries_++; - base::PostDelayedTaskWithTraits( + base::PostDelayedTask( FROM_HERE, {content::BrowserThread::UI}, base::BindOnce(&ServicesCustomizationDocument::StartFileFetch, weak_ptr_factory_.GetWeakPtr()), @@ -876,8 +878,9 @@ &ServicesCustomizationDocument::OnCheckedWallpaperCacheExists, weak_ptr_factory_.GetWeakPtr(), base::Passed(std::move(exists)), std::move(applying)); - base::PostTaskWithTraitsAndReply( - FROM_HERE, {base::MayBlock(), base::TaskPriority::BEST_EFFORT}, + base::PostTaskAndReply( + FROM_HERE, + {base::ThreadPool(), base::MayBlock(), base::TaskPriority::BEST_EFFORT}, std::move(check_file_exists), std::move(on_checked_closure)); }
diff --git a/chrome/browser/chromeos/customization/customization_wallpaper_downloader.cc b/chrome/browser/chromeos/customization/customization_wallpaper_downloader.cc index a8697a33..5c63526 100644 --- a/chrome/browser/chromeos/customization/customization_wallpaper_downloader.cc +++ b/chrome/browser/chromeos/customization/customization_wallpaper_downloader.cc
@@ -136,8 +136,9 @@ base::OnceClosure on_created_closure = base::BindOnce( &CustomizationWallpaperDownloader::OnWallpaperDirectoryCreated, weak_factory_.GetWeakPtr(), std::move(success)); - base::PostTaskWithTraitsAndReply( - FROM_HERE, {base::MayBlock(), base::TaskPriority::BEST_EFFORT}, + base::PostTaskAndReply( + FROM_HERE, + {base::ThreadPool(), base::MayBlock(), base::TaskPriority::BEST_EFFORT}, std::move(mkdir_closure), std::move(on_created_closure)); } @@ -172,8 +173,9 @@ base::OnceClosure on_rename_closure = base::BindOnce(&CustomizationWallpaperDownloader::OnTemporaryFileRenamed, weak_factory_.GetWeakPtr(), std::move(success)); - base::PostTaskWithTraitsAndReply( - FROM_HERE, {base::MayBlock(), base::TaskPriority::BEST_EFFORT}, + base::PostTaskAndReply( + FROM_HERE, + {base::ThreadPool(), base::MayBlock(), base::TaskPriority::BEST_EFFORT}, std::move(rename_closure), std::move(on_rename_closure)); }
diff --git a/chrome/browser/chromeos/customization/customization_wallpaper_util.cc b/chrome/browser/chromeos/customization/customization_wallpaper_util.cc index bbab4fefb..d17840e9 100644 --- a/chrome/browser/chromeos/customization/customization_wallpaper_util.cc +++ b/chrome/browser/chromeos/customization/customization_wallpaper_util.cc
@@ -102,8 +102,9 @@ wallpaper->image().EnsureRepsForSupportedScales(); scoped_refptr<base::SequencedTaskRunner> task_runner = - base::CreateSequencedTaskRunnerWithTraits( - {base::MayBlock(), base::TaskPriority::USER_BLOCKING, + base::CreateSequencedTaskRunner( + {base::ThreadPool(), base::MayBlock(), + base::TaskPriority::USER_BLOCKING, base::TaskShutdownBehavior::CONTINUE_ON_SHUTDOWN}); base::PostTaskAndReplyWithResult( task_runner.get(), FROM_HERE, @@ -131,8 +132,9 @@ // Either resized images do not exist or cached version is incorrect. // Need to start decoding again. scoped_refptr<base::SequencedTaskRunner> task_runner = - base::CreateSequencedTaskRunnerWithTraits( - {base::MayBlock(), base::TaskPriority::USER_BLOCKING, + base::CreateSequencedTaskRunner( + {base::ThreadPool(), base::MayBlock(), + base::TaskPriority::USER_BLOCKING, base::TaskShutdownBehavior::CONTINUE_ON_SHUTDOWN}); user_image_loader::StartWithFilePath( task_runner, file_path, ImageDecoder::ROBUST_JPEG_CODEC, @@ -167,8 +169,9 @@ } scoped_refptr<base::SequencedTaskRunner> task_runner = - base::CreateSequencedTaskRunnerWithTraits( - {base::MayBlock(), base::TaskPriority::USER_BLOCKING, + base::CreateSequencedTaskRunner( + {base::ThreadPool(), base::MayBlock(), + base::TaskPriority::USER_BLOCKING, base::TaskShutdownBehavior::CONTINUE_ON_SHUTDOWN}); base::PostTaskAndReplyWithResult( task_runner.get(), FROM_HERE,
diff --git a/chrome/browser/chromeos/dbus/component_updater_service_provider.cc b/chrome/browser/chromeos/dbus/component_updater_service_provider.cc index a72cd38d..e15a210 100644 --- a/chrome/browser/chromeos/dbus/component_updater_service_provider.cc +++ b/chrome/browser/chromeos/dbus/component_updater_service_provider.cc
@@ -83,7 +83,7 @@ void ComponentUpdaterServiceProvider::EmitInstalledSignal( const std::string& component) { - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {content::BrowserThread::UI}, base::BindOnce( &ComponentUpdaterServiceProvider::EmitInstalledSignalInternal,
diff --git a/chrome/browser/chromeos/dbus/cryptohome_key_delegate_service_provider.cc b/chrome/browser/chromeos/dbus/cryptohome_key_delegate_service_provider.cc index 21437613..e3d4ee3 100644 --- a/chrome/browser/chromeos/dbus/cryptohome_key_delegate_service_provider.cc +++ b/chrome/browser/chromeos/dbus/cryptohome_key_delegate_service_provider.cc
@@ -16,8 +16,10 @@ #include "chrome/browser/chromeos/certificate_provider/certificate_provider_service_factory.h" #include "chrome/browser/chromeos/profiles/profile_helper.h" #include "chrome/browser/profiles/profile.h" +#include "chromeos/cryptohome/cryptohome_parameters.h" #include "chromeos/dbus/cryptohome/key.pb.h" #include "chromeos/dbus/cryptohome/rpc.pb.h" +#include "components/account_id/account_id.h" #include "dbus/message.h" #include "net/base/net_errors.h" #include "third_party/boringssl/src/include/openssl/digest.h" @@ -104,6 +106,7 @@ void HandleSignatureKeyChallenge( dbus::MethodCall* method_call, const cryptohome::SignatureKeyChallengeRequestData& challenge_request_data, + const AccountId& account_id, dbus::ExportedObject::ResponseSender response_sender) { if (challenge_request_data.data_to_sign().empty()) { response_sender.Run(dbus::ErrorResponse::FromMethodCall( @@ -168,6 +171,7 @@ certificate_provider_service->RequestSignatureBySpki( challenge_request_data.public_key_spki_der(), ssl_algorithm, digest, + account_id, base::BindOnce(&CompleteSignatureKeyChallenge, base::Unretained(method_call), response_sender)); } @@ -207,7 +211,14 @@ "Unable to parse AccountIdentifier from request")); return; } - // For now |account_identifier| is not used. + const AccountId account_id = + cryptohome::GetAccountIdFromAccountIdentifier(account_identifier); + if (!account_id.is_valid() || + account_id.GetAccountType() == AccountType::UNKNOWN) { + response_sender.Run(dbus::ErrorResponse::FromMethodCall( + method_call, DBUS_ERROR_FAILED, "Unknown account")); + return; + } cryptohome::KeyChallengeRequest request; if (!reader.PopArrayOfBytesAsProto(&request)) { @@ -232,7 +243,7 @@ return; } HandleSignatureKeyChallenge(method_call, request.signature_request_data(), - response_sender); + account_id, response_sender); return; }
diff --git a/chrome/browser/chromeos/dbus/cryptohome_key_delegate_service_provider_browsertest.cc b/chrome/browser/chromeos/dbus/cryptohome_key_delegate_service_provider_browsertest.cc index f8d4d32c..9a7e2d9 100644 --- a/chrome/browser/chromeos/dbus/cryptohome_key_delegate_service_provider_browsertest.cc +++ b/chrome/browser/chromeos/dbus/cryptohome_key_delegate_service_provider_browsertest.cc
@@ -26,6 +26,7 @@ #include "chromeos/dbus/cryptohome/rpc.pb.h" #include "chromeos/dbus/services/service_provider_test_helper.h" #include "components/account_id/account_id.h" +#include "components/user_manager/user_names.h" #include "components/version_info/channel.h" #include "content/public/browser/browser_context.h" #include "dbus/message.h" @@ -183,7 +184,8 @@ cryptohome::ChallengeSignatureAlgorithm signature_algorithm, std::vector<uint8_t>* signature) { const cryptohome::AccountIdentifier account_identifier = - cryptohome::CreateAccountIdentifierFromAccountId(EmptyAccountId()); + cryptohome::CreateAccountIdentifierFromAccountId( + user_manager::StubAccountId()); cryptohome::KeyChallengeRequest request; request.set_challenge_type( cryptohome::KeyChallengeRequest::CHALLENGE_TYPE_SIGNATURE);
diff --git a/chrome/browser/chromeos/drive/download_handler.cc b/chrome/browser/chromeos/drive/download_handler.cc index 51c26ba..1428f67 100644 --- a/chrome/browser/chromeos/drive/download_handler.cc +++ b/chrome/browser/chromeos/drive/download_handler.cc
@@ -315,7 +315,7 @@ // Remove any persisted Drive DownloadItem. crbug.com/171384 if (IsPersistedDriveDownload(drive_tmp_download_path_, download)) { // Remove download later, since doing it here results in a crash. - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {BrowserThread::UI}, base::BindOnce(&DownloadHandler::RemoveDownload, weak_ptr_factory_.GetWeakPtr(), @@ -375,8 +375,8 @@ FileError error) { DVLOG(1) << "OnCreateDirectory " << FileErrorToString(error); if (error == FILE_ERROR_OK) { - base::PostTaskWithTraitsAndReplyWithResult( - FROM_HERE, {base::MayBlock()}, + base::PostTaskAndReplyWithResult( + FROM_HERE, {base::ThreadPool(), base::MayBlock()}, base::Bind(&GetDriveTempDownloadPath, drive_tmp_download_path_), callback); } else {
diff --git a/chrome/browser/chromeos/drive/drive_file_stream_reader.cc b/chrome/browser/chromeos/drive/drive_file_stream_reader.cc index 7d710d8..f2eb84e 100644 --- a/chrome/browser/chromeos/drive/drive_file_stream_reader.cc +++ b/chrome/browser/chromeos/drive/drive_file_stream_reader.cc
@@ -319,7 +319,7 @@ const base::Callback<void(const base::Closure&)>& reply_callback) { DCHECK_CURRENTLY_ON(BrowserThread::IO); - base::PostTaskWithTraitsAndReplyWithResult( + base::PostTaskAndReplyWithResult( FROM_HERE, {BrowserThread::UI}, base::Bind(&GetFileContentOnUIThread, file_system_getter, drive_file_path, base::Passed(google_apis::CreateRelayCallback(
diff --git a/chrome/browser/chromeos/drive/drive_integration_service.cc b/chrome/browser/chromeos/drive/drive_integration_service.cc index 372a6a3..903e2bc 100644 --- a/chrome/browser/chromeos/drive/drive_integration_service.cc +++ b/chrome/browser/chromeos/drive/drive_integration_service.cc
@@ -665,8 +665,8 @@ DCHECK(profile && !profile->IsOffTheRecord()); logger_ = std::make_unique<EventLogger>(); - blocking_task_runner_ = base::CreateSequencedTaskRunnerWithTraits( - {base::MayBlock(), base::TaskPriority::USER_BLOCKING, + blocking_task_runner_ = base::CreateSequencedTaskRunner( + {base::ThreadPool(), base::MayBlock(), base::TaskPriority::USER_BLOCKING, base::WithBaseSyncPrimitives()}); if (preference_watcher_)
diff --git a/chrome/browser/chromeos/drive/file_system_util.cc b/chrome/browser/chromeos/drive/file_system_util.cc index ebf830d..63755d2a0 100644 --- a/chrome/browser/chromeos/drive/file_system_util.cc +++ b/chrome/browser/chromeos/drive/file_system_util.cc
@@ -182,8 +182,10 @@ FileSystemInterface* file_system = GetFileSystemByProfile(profile); if (!file_system || !IsUnderDriveMountPoint(path)) { - base::PostTaskWithTraits( - FROM_HERE, {base::MayBlock(), base::TaskPriority::USER_BLOCKING}, + base::PostTask( + FROM_HERE, + {base::ThreadPool(), base::MayBlock(), + base::TaskPriority::USER_BLOCKING}, base::BindOnce(callback, FILE_ERROR_FAILED, base::FilePath())); return; }
diff --git a/chrome/browser/chromeos/drive/fileapi/async_file_util.cc b/chrome/browser/chromeos/drive/fileapi/async_file_util.cc index 7b12f07d..4e640e0 100644 --- a/chrome/browser/chromeos/drive/fileapi/async_file_util.cc +++ b/chrome/browser/chromeos/drive/fileapi/async_file_util.cc
@@ -38,7 +38,7 @@ const base::Closure& on_error_callback) { DCHECK_CURRENTLY_ON(BrowserThread::IO); - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {BrowserThread::UI}, base::BindOnce(&fileapi_internal::RunFileSystemCallback, file_system_getter, function, @@ -60,10 +60,10 @@ // It will be provided as a FileSystem::OpenFileCallback's argument later. // (crbug.com/259184). std::move(callback).Run( - std::move(file), base::Bind(&google_apis::RunTaskWithTaskRunner, - base::CreateSingleThreadTaskRunnerWithTraits( - {BrowserThread::UI}), - close_callback_on_ui_thread)); + std::move(file), + base::Bind(&google_apis::RunTaskWithTaskRunner, + base::CreateSingleThreadTaskRunner({BrowserThread::UI}), + close_callback_on_ui_thread)); } // Runs CreateOrOpenFile when the error happens. @@ -102,10 +102,11 @@ DCHECK_CURRENTLY_ON(BrowserThread::IO); scoped_refptr<storage::ShareableFileReference> file_reference = - storage::ShareableFileReference::GetOrCreate(storage::ScopedFile( - local_path, scope_out_policy, - base::CreateSequencedTaskRunnerWithTraits( - {base::MayBlock(), base::TaskPriority::USER_BLOCKING}))); + storage::ShareableFileReference::GetOrCreate( + storage::ScopedFile(local_path, scope_out_policy, + base::CreateSequencedTaskRunner( + {base::ThreadPool(), base::MayBlock(), + base::TaskPriority::USER_BLOCKING}))); std::move(callback).Run(error, file_info, local_path, std::move(file_reference)); }
diff --git a/chrome/browser/chromeos/drive/fileapi/drivefs_async_file_util.cc b/chrome/browser/chromeos/drive/fileapi/drivefs_async_file_util.cc index f10b96d..460a841 100644 --- a/chrome/browser/chromeos/drive/fileapi/drivefs_async_file_util.cc +++ b/chrome/browser/chromeos/drive/fileapi/drivefs_async_file_util.cc
@@ -218,7 +218,7 @@ CopyOrMoveOption option, CopyFileProgressCallback progress_callback, StatusCallback callback) { - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {content::BrowserThread::UI}, base::BindOnce( &CopyOperation::Start, @@ -233,13 +233,12 @@ std::unique_ptr<storage::FileSystemOperationContext> context, const storage::FileSystemURL& url, StatusCallback callback) { - base::PostTaskWithTraits( - FROM_HERE, {content::BrowserThread::UI}, - base::BindOnce(&DeleteOperation::Start, - base::Unretained(new DeleteOperation( - profile_, url.path(), std::move(callback), - base::SequencedTaskRunnerHandle::Get(), - context->task_runner())))); + base::PostTask(FROM_HERE, {content::BrowserThread::UI}, + base::BindOnce(&DeleteOperation::Start, + base::Unretained(new DeleteOperation( + profile_, url.path(), std::move(callback), + base::SequencedTaskRunnerHandle::Get(), + context->task_runner())))); } } // namespace internal
diff --git a/chrome/browser/chromeos/drive/fileapi/file_system_backend_delegate.cc b/chrome/browser/chromeos/drive/fileapi/file_system_backend_delegate.cc index 6e260f5..6ab4ea1b 100644 --- a/chrome/browser/chromeos/drive/fileapi/file_system_backend_delegate.cc +++ b/chrome/browser/chromeos/drive/fileapi/file_system_backend_delegate.cc
@@ -40,8 +40,7 @@ entry->file_specific_info().is_hosted_document()) { url = GURL(entry->alternate_url()); } - base::PostTaskWithTraits(FROM_HERE, {BrowserThread::IO}, - base::BindOnce(callback, url)); + base::PostTask(FROM_HERE, {BrowserThread::IO}, base::BindOnce(callback, url)); } // Called on the UI thread after @@ -54,14 +53,14 @@ FileSystemInterface* const file_system = fileapi_internal::GetFileSystemFromUrl(url); if (!file_system) { - base::PostTaskWithTraits(FROM_HERE, {BrowserThread::IO}, - base::BindOnce(callback, GURL())); + base::PostTask(FROM_HERE, {BrowserThread::IO}, + base::BindOnce(callback, GURL())); return; } const base::FilePath file_path = util::ExtractDrivePathFromFileSystemUrl(url); if (file_path.empty()) { - base::PostTaskWithTraits(FROM_HERE, {BrowserThread::IO}, - base::BindOnce(callback, GURL())); + base::PostTask(FROM_HERE, {BrowserThread::IO}, + base::BindOnce(callback, GURL())); return; } @@ -136,7 +135,7 @@ const storage::FileSystemURL& url, const storage::URLCallback& callback) { DCHECK_CURRENTLY_ON(BrowserThread::IO); - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {BrowserThread::UI}, base::BindOnce(&GetRedirectURLForContentsOnUIThread, url, callback)); }
diff --git a/chrome/browser/chromeos/drive/fileapi/fileapi_worker.cc b/chrome/browser/chromeos/drive/fileapi/fileapi_worker.cc index f561bb7..b1f77d7 100644 --- a/chrome/browser/chromeos/drive/fileapi/fileapi_worker.cc +++ b/chrome/browser/chromeos/drive/fileapi/fileapi_worker.cc
@@ -185,8 +185,8 @@ } // Cache file prepared for modification is available. Open it locally. - base::PostTaskWithTraitsAndReplyWithResult( - FROM_HERE, {base::MayBlock()}, + base::PostTaskAndReplyWithResult( + FROM_HERE, {base::ThreadPool(), base::MayBlock()}, base::Bind(&OpenFile, local_path, file_flags), base::Bind(&RunOpenFileCallback, callback, close_callback)); }
diff --git a/chrome/browser/chromeos/drive/fileapi/webkit_file_stream_writer_impl.cc b/chrome/browser/chromeos/drive/fileapi/webkit_file_stream_writer_impl.cc index 892e1ea..088a349 100644 --- a/chrome/browser/chromeos/drive/fileapi/webkit_file_stream_writer_impl.cc +++ b/chrome/browser/chromeos/drive/fileapi/webkit_file_stream_writer_impl.cc
@@ -30,7 +30,7 @@ const fileapi_internal::CreateWritableSnapshotFileCallback& callback) { DCHECK_CURRENTLY_ON(BrowserThread::IO); - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {BrowserThread::UI}, base::BindOnce( &fileapi_internal::RunFileSystemCallback, file_system_getter, @@ -60,8 +60,8 @@ // It is necessary to close the local file in advance. local_file_writer_.reset(); DCHECK(!close_callback_on_ui_thread_.is_null()); - base::PostTaskWithTraits(FROM_HERE, {BrowserThread::UI}, - close_callback_on_ui_thread_); + base::PostTask(FROM_HERE, {BrowserThread::UI}, + close_callback_on_ui_thread_); } } @@ -143,8 +143,8 @@ // Here the file is internally created. To revert the operation, close // the file. DCHECK(!close_callback_on_ui_thread.is_null()); - base::PostTaskWithTraits(FROM_HERE, {BrowserThread::UI}, - close_callback_on_ui_thread); + base::PostTask(FROM_HERE, {BrowserThread::UI}, + close_callback_on_ui_thread); } std::move(pending_cancel_callback_).Run(net::OK);
diff --git a/chrome/browser/chromeos/drive/write_on_cache_file.cc b/chrome/browser/chromeos/drive/write_on_cache_file.cc index 0b32ffad..843b9c5 100644 --- a/chrome/browser/chromeos/drive/write_on_cache_file.cc +++ b/chrome/browser/chromeos/drive/write_on_cache_file.cc
@@ -38,8 +38,9 @@ const base::Closure& close_callback) { DCHECK_CURRENTLY_ON(BrowserThread::UI); - base::PostTaskWithTraitsAndReply( - FROM_HERE, {base::MayBlock(), base::TaskPriority::USER_BLOCKING}, + base::PostTaskAndReply( + FROM_HERE, + {base::ThreadPool(), base::MayBlock(), base::TaskPriority::USER_BLOCKING}, base::BindOnce(file_io_task_callback, error, local_cache_path), base::BindOnce(&RunCloseCallbackAndReplyTask, close_callback, reply, error));
diff --git a/chrome/browser/chromeos/extensions/default_app_order.cc b/chrome/browser/chromeos/extensions/default_app_order.cc index d118f17a..7d51112 100644 --- a/chrome/browser/chromeos/extensions/default_app_order.cc +++ b/chrome/browser/chromeos/extensions/default_app_order.cc
@@ -150,8 +150,10 @@ loader_instance = this; if (async) { - base::PostTaskWithTraits( - FROM_HERE, {base::MayBlock(), base::TaskPriority::USER_VISIBLE}, + base::PostTask( + FROM_HERE, + {base::ThreadPool(), base::MayBlock(), + base::TaskPriority::USER_VISIBLE}, base::BindOnce(&ExternalLoader::Load, base::Unretained(this))); } else { Load();
diff --git a/chrome/browser/chromeos/extensions/external_cache_impl_unittest.cc b/chrome/browser/chromeos/extensions/external_cache_impl_unittest.cc index e88ae48..0bc700a5 100644 --- a/chrome/browser/chromeos/extensions/external_cache_impl_unittest.cc +++ b/chrome/browser/chromeos/extensions/external_cache_impl_unittest.cc
@@ -138,8 +138,8 @@ base::FilePath cache_dir(CreateCacheDir(false)); ExternalCacheImpl external_cache( cache_dir, url_loader_factory(), - base::CreateSequencedTaskRunnerWithTraits({base::MayBlock()}), this, true, - false); + base::CreateSequencedTaskRunner({base::ThreadPool(), base::MayBlock()}), + this, true, false); external_cache.use_null_connector_for_test(); std::unique_ptr<base::DictionaryValue> prefs(new base::DictionaryValue); @@ -261,8 +261,8 @@ base::FilePath cache_dir(CreateCacheDir(false)); ExternalCacheImpl external_cache( cache_dir, url_loader_factory(), - base::CreateSequencedTaskRunnerWithTraits({base::MayBlock()}), this, true, - false); + base::CreateSequencedTaskRunner({base::ThreadPool(), base::MayBlock()}), + this, true, false); external_cache.use_null_connector_for_test(); std::unique_ptr<base::DictionaryValue> prefs(new base::DictionaryValue);
diff --git a/chrome/browser/chromeos/extensions/file_manager/file_browser_handler_api_test.cc b/chrome/browser/chromeos/extensions/file_manager/file_browser_handler_api_test.cc index b3e41b3..ca4ff3d 100644 --- a/chrome/browser/chromeos/extensions/file_manager/file_browser_handler_api_test.cc +++ b/chrome/browser/chromeos/extensions/file_manager/file_browser_handler_api_test.cc
@@ -295,8 +295,9 @@ const std::string kExpectedContents = "hello from test extension."; base::RunLoop run_loop; std::string contents; - base::PostTaskWithTraitsAndReply( - FROM_HERE, {base::MayBlock(), base::TaskPriority::USER_VISIBLE}, + base::PostTaskAndReply( + FROM_HERE, + {base::ThreadPool(), base::MayBlock(), base::TaskPriority::USER_VISIBLE}, base::BindOnce(base::IgnoreResult(base::ReadFileToString), selected_path, &contents), run_loop.QuitClosure());
diff --git a/chrome/browser/chromeos/extensions/file_manager/private_api_file_system.cc b/chrome/browser/chromeos/extensions/file_manager/private_api_file_system.cc index 23330f5..9eca60f 100644 --- a/chrome/browser/chromeos/extensions/file_manager/private_api_file_system.cc +++ b/chrome/browser/chromeos/extensions/file_manager/private_api_file_system.cc
@@ -161,10 +161,9 @@ int64_t size) { DCHECK_CURRENTLY_ON(BrowserThread::IO); - base::PostTaskWithTraits( - FROM_HERE, {BrowserThread::UI}, - base::BindOnce(&NotifyCopyProgress, profile_id, *operation_id, type, - source_url, destination_url, size)); + base::PostTask(FROM_HERE, {BrowserThread::UI}, + base::BindOnce(&NotifyCopyProgress, profile_id, *operation_id, + type, source_url, destination_url, size)); } // Notifies the copy completion to extensions via event router. @@ -194,7 +193,7 @@ base::File::Error error) { DCHECK_CURRENTLY_ON(BrowserThread::IO); - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {BrowserThread::UI}, base::BindOnce(&NotifyCopyCompletion, profile_id, *operation_id, source_url, destination_url, error)); @@ -260,9 +259,8 @@ base::OnceCallback<void(std::string)> callback, std::string hash) { DCHECK_CURRENTLY_ON(BrowserThread::IO); - base::PostTaskWithTraits( - FROM_HERE, {BrowserThread::UI}, - base::BindOnce(std::move(callback), std::move(hash))); + base::PostTask(FROM_HERE, {BrowserThread::UI}, + base::BindOnce(std::move(callback), std::move(hash))); } // Calls a response callback on the UI thread. @@ -271,9 +269,8 @@ base::File::Error result, const base::File::Info& file_info) { DCHECK_CURRENTLY_ON(BrowserThread::IO); - base::PostTaskWithTraits( - FROM_HERE, {BrowserThread::UI}, - base::BindOnce(std::move(callback), result, file_info)); + base::PostTask(FROM_HERE, {BrowserThread::UI}, + base::BindOnce(std::move(callback), result, file_info)); } // Construct a case-insensitive fnmatch query from |query|. E.g. for abc123, @@ -415,16 +412,16 @@ const FileWatchFunctionBase::ResponseCallback& callback, bool success) { DCHECK_CURRENTLY_ON(BrowserThread::IO); - base::PostTaskWithTraits(FROM_HERE, {BrowserThread::UI}, - base::BindOnce(callback, success)); + base::PostTask(FROM_HERE, {BrowserThread::UI}, + base::BindOnce(callback, success)); } void PostNotificationCallbackTaskToUIThread( const storage::WatcherManager::NotificationCallback& callback, storage::WatcherManager::ChangeType type) { DCHECK_CURRENTLY_ON(BrowserThread::IO); - base::PostTaskWithTraits(FROM_HERE, {BrowserThread::UI}, - base::BindOnce(callback, type)); + base::PostTask(FROM_HERE, {BrowserThread::UI}, + base::BindOnce(callback, type)); } } // namespace @@ -467,11 +464,10 @@ file_manager::EventRouterFactory::GetForProfile( chrome_details.GetProfile()); - base::PostTaskWithTraits( - FROM_HERE, {BrowserThread::IO}, - base::BindOnce(&FileWatchFunctionBase::RunAsyncOnIOThread, this, - file_system_context, file_system_url, - event_router->GetWeakPtr())); + base::PostTask(FROM_HERE, {BrowserThread::IO}, + base::BindOnce(&FileWatchFunctionBase::RunAsyncOnIOThread, + this, file_system_context, file_system_url, + event_router->GetWeakPtr())); return RespondLater(); } @@ -485,7 +481,7 @@ file_system_context->GetWatcherManager(file_system_url.type()); if (!watcher_manager) { - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {BrowserThread::UI}, base::BindOnce( &FileWatchFunctionBase::PerformFallbackFileWatchOperationOnUIThread, @@ -611,8 +607,10 @@ } else { uint64_t* total_size = new uint64_t(0); uint64_t* remaining_size = new uint64_t(0); - base::PostTaskWithTraitsAndReply( - FROM_HERE, {base::MayBlock(), base::TaskPriority::USER_VISIBLE}, + base::PostTaskAndReply( + FROM_HERE, + {base::ThreadPool(), base::MayBlock(), + base::TaskPriority::USER_VISIBLE}, base::BindOnce(&GetSizeStatsAsync, volume->mount_path(), total_size, remaining_size), base::BindOnce(&FileManagerPrivateGetSizeStatsFunction::OnGetSizeStats, @@ -686,8 +684,9 @@ return RespondNow(OneArgument(std::make_unique<base::Value>(true))); } - base::PostTaskWithTraitsAndReplyWithResult( - FROM_HERE, {base::MayBlock(), base::TaskPriority::USER_BLOCKING}, + base::PostTaskAndReplyWithResult( + FROM_HERE, + {base::ThreadPool(), base::MayBlock(), base::TaskPriority::USER_BLOCKING}, base::BindOnce(&GetFileNameMaxLengthAsync, file_system_url.path().AsUTF8Unsafe()), base::BindOnce(&FileManagerPrivateInternalValidatePathNameLengthFunction:: @@ -820,7 +819,7 @@ } // Check how much space we need for the copy operation. - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {BrowserThread::IO}, base::BindOnce( &GetFileMetadataOnIOThread, file_system_context, source_url_, @@ -855,8 +854,8 @@ } destination_dirs.push_back(destination_url_.path().DirName()); - base::PostTaskWithTraitsAndReplyWithResult( - FROM_HERE, {base::MayBlock()}, + base::PostTaskAndReplyWithResult( + FROM_HERE, {base::ThreadPool(), base::MayBlock()}, base::BindOnce(&GetLocalDiskSpaces, std::move(destination_dirs)), base::BindOnce( &FileManagerPrivateInternalStartCopyFunction::RunAfterCheckDiskSpace, @@ -924,7 +923,7 @@ scoped_refptr<storage::FileSystemContext> file_system_context = file_manager::util::GetFileSystemContextForRenderFrameHost( chrome_details_.GetProfile(), render_frame_host()); - base::PostTaskWithTraitsAndReplyWithResult( + base::PostTaskAndReplyWithResult( FROM_HERE, {BrowserThread::IO}, base::BindOnce(&StartCopyOnIOThread, chrome_details_.GetProfile(), file_system_context, source_url_, destination_url_), @@ -953,10 +952,9 @@ chrome_details.GetProfile(), render_frame_host()); // We don't much take care about the result of cancellation. - base::PostTaskWithTraits( - FROM_HERE, {BrowserThread::IO}, - base::BindOnce(&CancelCopyOnIOThread, file_system_context, - params->copy_id)); + base::PostTask(FROM_HERE, {BrowserThread::IO}, + base::BindOnce(&CancelCopyOnIOThread, file_system_context, + params->copy_id)); return RespondNow(NoArguments()); } @@ -1068,11 +1066,10 @@ base::BindOnce( &FileManagerPrivateInternalComputeChecksumFunction::RespondWith, this)); - base::PostTaskWithTraits( - FROM_HERE, {BrowserThread::IO}, - base::BindOnce(&FileStreamMd5Digester::GetMd5Digest, - base::Unretained(digester_.get()), std::move(reader), - std::move(result_callback))); + base::PostTask(FROM_HERE, {BrowserThread::IO}, + base::BindOnce(&FileStreamMd5Digester::GetMd5Digest, + base::Unretained(digester_.get()), + std::move(reader), std::move(result_callback))); return RespondLater(); } @@ -1128,8 +1125,9 @@ // |file_system| is NULL if the backend is DriveFs. It doesn't provide // dedicated backup solution yet, so for now just walk the files and check // MD5 extended attribute. - base::PostTaskWithTraitsAndReplyWithResult( - FROM_HERE, {base::MayBlock(), base::TaskPriority::BEST_EFFORT}, + base::PostTaskAndReplyWithResult( + FROM_HERE, + {base::ThreadPool(), base::MayBlock(), base::TaskPriority::BEST_EFFORT}, base::BindOnce( &FileManagerPrivateSearchFilesByHashesFunction::SearchByAttribute, this, hashes, @@ -1223,8 +1221,9 @@ base::FilePath root = file_manager::util::GetMyFilesFolderForProfile( chrome_details_.GetProfile()); - base::PostTaskWithTraitsAndReplyWithResult( - FROM_HERE, {base::MayBlock(), base::TaskPriority::BEST_EFFORT}, + base::PostTaskAndReplyWithResult( + FROM_HERE, + {base::ThreadPool(), base::MayBlock(), base::TaskPriority::BEST_EFFORT}, base::BindOnce(&SearchByPattern, root, params->search_params.query, base::internal::checked_cast<size_t>( params->search_params.max_results)), @@ -1362,8 +1361,9 @@ Error("Failed to get a local path from the entry's url.")); } - base::PostTaskWithTraitsAndReplyWithResult( - FROM_HERE, {base::MayBlock(), base::TaskPriority::USER_VISIBLE}, + base::PostTaskAndReplyWithResult( + FROM_HERE, + {base::ThreadPool(), base::MayBlock(), base::TaskPriority::USER_VISIBLE}, base::BindOnce(&base::ComputeDirectorySize, root_path), base::BindOnce(&FileManagerPrivateInternalGetDirectorySizeFunction:: OnDirectorySizeRetrieved,
diff --git a/chrome/browser/chromeos/extensions/file_manager/private_api_mount.cc b/chrome/browser/chromeos/extensions/file_manager/private_api_mount.cc index 0e3d694..67e2ca34 100644 --- a/chrome/browser/chromeos/extensions/file_manager/private_api_mount.cc +++ b/chrome/browser/chromeos/extensions/file_manager/private_api_mount.cc
@@ -106,8 +106,10 @@ if (is_under_downloads) { // For files under downloads, change the file permission and make it // readable from avfs/fuse if needed. - base::PostTaskWithTraits( - FROM_HERE, {base::MayBlock(), base::TaskPriority::USER_BLOCKING}, + base::PostTask( + FROM_HERE, + {base::ThreadPool(), base::MayBlock(), + base::TaskPriority::USER_BLOCKING}, base::BindOnce(&EnsureReadableFilePermissionAsync, path, google_apis::CreateRelayCallback(base::BindOnce( &FileManagerPrivateAddMountFunction::
diff --git a/chrome/browser/chromeos/extensions/install_limiter.cc b/chrome/browser/chromeos/extensions/install_limiter.cc index 700c6af..b2394d6 100644 --- a/chrome/browser/chromeos/extensions/install_limiter.cc +++ b/chrome/browser/chromeos/extensions/install_limiter.cc
@@ -76,8 +76,8 @@ return; } - base::PostTaskWithTraitsAndReplyWithResult( - FROM_HERE, {base::MayBlock()}, + base::PostTaskAndReplyWithResult( + FROM_HERE, {base::ThreadPool(), base::MayBlock()}, base::BindOnce(&GetFileSize, file_info.path), base::BindOnce(&InstallLimiter::AddWithSize, AsWeakPtr(), installer, file_info));
diff --git a/chrome/browser/chromeos/extensions/quick_unlock_private/quick_unlock_private_api.cc b/chrome/browser/chromeos/extensions/quick_unlock_private/quick_unlock_private_api.cc index 63c3cd0..9df3ba8 100644 --- a/chrome/browser/chromeos/extensions/quick_unlock_private/quick_unlock_private_api.cc +++ b/chrome/browser/chromeos/extensions/quick_unlock_private/quick_unlock_private_api.cc
@@ -277,7 +277,7 @@ // is needed. AddRef(); - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {content::BrowserThread::UI}, base::BindOnce(&chromeos::ExtendedAuthenticator::AuthenticateToCheck, extended_authenticator_.get(), user_context,
diff --git a/chrome/browser/chromeos/extensions/wallpaper_private_api.cc b/chrome/browser/chromeos/extensions/wallpaper_private_api.cc index de9ee2ef..8138e97 100644 --- a/chrome/browser/chromeos/extensions/wallpaper_private_api.cc +++ b/chrome/browser/chromeos/extensions/wallpaper_private_api.cc
@@ -267,7 +267,7 @@ ExtensionFunction::ResponseAction WallpaperPrivateGetSyncSettingFunction::Run() { - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {BrowserThread::UI}, base::BindOnce( &WallpaperPrivateGetSyncSettingFunction::CheckSyncServiceStatus, @@ -311,7 +311,7 @@ // TODO(xdai): It would be cleaner to implement a SyncServiceObserver and wait // for OnStateChanged() instead of polling. retry_number_++; - base::PostDelayedTaskWithTraits( + base::PostDelayedTask( FROM_HERE, {BrowserThread::UI}, base::BindOnce( &WallpaperPrivateGetSyncSettingFunction::CheckSyncServiceStatus, @@ -565,18 +565,18 @@ std::string data; if (GetData(path, &data)) { if (data.empty()) { - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {BrowserThread::UI}, base::BindOnce(&WallpaperPrivateGetThumbnailFunction::FileNotLoaded, this)); } else { - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {BrowserThread::UI}, base::BindOnce(&WallpaperPrivateGetThumbnailFunction::FileLoaded, this, data)); } } else { - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {BrowserThread::UI}, base::BindOnce(&WallpaperPrivateGetThumbnailFunction::Failure, this, path.BaseName().value())); @@ -619,11 +619,11 @@ WallpaperFunctionBase::AssertCalledOnWallpaperSequence( WallpaperFunctionBase::GetNonBlockingTaskRunner()); if (SaveData(chrome::DIR_CHROMEOS_WALLPAPER_THUMBNAILS, file_name, data)) { - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {BrowserThread::UI}, base::BindOnce(&WallpaperPrivateSaveThumbnailFunction::Success, this)); } else { - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {BrowserThread::UI}, base::BindOnce(&WallpaperPrivateSaveThumbnailFunction::Failure, this, file_name));
diff --git a/chrome/browser/chromeos/external_metrics.cc b/chrome/browser/chromeos/external_metrics.cc index ca4d8ed..8607410 100644 --- a/chrome/browser/chromeos/external_metrics.cc +++ b/chrome/browser/chromeos/external_metrics.cc
@@ -95,7 +95,7 @@ } void ExternalMetrics::RecordAction(const std::string& action) { - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {BrowserThread::UI}, base::BindOnce(&ExternalMetrics::RecordActionUI, this, action)); } @@ -105,7 +105,7 @@ } void ExternalMetrics::RecordCrash(const std::string& crash_kind) { - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {BrowserThread::UI}, base::BindOnce(&ExternalMetrics::RecordCrashUI, this, crash_kind)); } @@ -176,8 +176,9 @@ } void ExternalMetrics::ScheduleCollector() { - base::PostDelayedTaskWithTraits( - FROM_HERE, {base::MayBlock(), base::TaskPriority::BEST_EFFORT}, + base::PostDelayedTask( + FROM_HERE, + {base::ThreadPool(), base::MayBlock(), base::TaskPriority::BEST_EFFORT}, base::BindOnce(&chromeos::ExternalMetrics::CollectEventsAndReschedule, this), collection_interval_);
diff --git a/chrome/browser/chromeos/file_manager/file_browser_handlers.cc b/chrome/browser/chromeos/file_manager/file_browser_handlers.cc index 5cab2de..9864f93f 100644 --- a/chrome/browser/chromeos/file_manager/file_browser_handlers.cc +++ b/chrome/browser/chromeos/file_manager/file_browser_handlers.cc
@@ -282,8 +282,9 @@ scoped_refptr<storage::FileSystemContext> file_system_context( util::GetFileSystemContextForExtensionId(profile_, extension_->id())); - base::PostTaskWithTraitsAndReplyWithResult( - FROM_HERE, {base::MayBlock(), base::TaskPriority::USER_BLOCKING}, + base::PostTaskAndReplyWithResult( + FROM_HERE, + {base::ThreadPool(), base::MayBlock(), base::TaskPriority::USER_BLOCKING}, base::BindOnce(&SetupFileAccessPermissions, file_system_context, extension_, file_urls), base::BindOnce(&FileBrowserHandlerExecutor::ExecuteAfterSetupFileAccess,
diff --git a/chrome/browser/chromeos/file_manager/file_manager_jstest.cc b/chrome/browser/chromeos/file_manager/file_manager_jstest.cc index 1d1351b..9869004f 100644 --- a/chrome/browser/chromeos/file_manager/file_manager_jstest.cc +++ b/chrome/browser/chromeos/file_manager/file_manager_jstest.cc
@@ -164,7 +164,7 @@ } IN_PROC_BROWSER_TEST_F(FileManagerJsTest, FilesMessage) { - RunGeneratedTest("/foreground/elements/files_message_unittest.html"); + RunTestURL("/file_manager/foreground/elements/files_message_unittest.html"); } IN_PROC_BROWSER_TEST_F(FileManagerJsTest, FilesToast) { @@ -214,3 +214,7 @@ IN_PROC_BROWSER_TEST_F(FileManagerJsTest, FileTransferController) { RunGeneratedTest("/foreground/js/file_transfer_controller_unittest.html"); } + +IN_PROC_BROWSER_TEST_F(FileManagerJsTest, FilesToolTip) { + RunTestURL("/file_manager/foreground/elements/files_tooltip_unittest.html"); +}
diff --git a/chrome/browser/chromeos/file_manager/file_manager_jstest_base.cc b/chrome/browser/chromeos/file_manager/file_manager_jstest_base.cc index aa72418..60dc51f 100644 --- a/chrome/browser/chromeos/file_manager/file_manager_jstest_base.cc +++ b/chrome/browser/chromeos/file_manager/file_manager_jstest_base.cc
@@ -151,6 +151,10 @@ RunTestImpl(embedded_test_server()->GetURL(file)); } +void FileManagerJsTestBase::RunTestURL(const std::string& file) { + RunTestImpl(GURL("chrome://file_manager_test" + file)); +} + void FileManagerJsTestBase::RunTestImpl(const GURL& url) { ui_test_utils::NavigateToURL(browser(), url); content::WebContents* const web_contents =
diff --git a/chrome/browser/chromeos/file_manager/file_manager_jstest_base.h b/chrome/browser/chromeos/file_manager/file_manager_jstest_base.h index c219642..2c4671d 100644 --- a/chrome/browser/chromeos/file_manager/file_manager_jstest_base.h +++ b/chrome/browser/chromeos/file_manager/file_manager_jstest_base.h
@@ -23,6 +23,10 @@ // |file|, relative to DIR_EXE/gen/base_path. void RunGeneratedTest(const std::string& file); + // Run the test from chrome://file_manager_test/. + // |file| is relative path to //ui/file_manager/ . + void RunTestURL(const std::string& file); + // Set up & tear down void SetUpOnMainThread() override; void TearDownOnMainThread() override; @@ -30,9 +34,9 @@ // chrome://file_manager_test. static const std::string kTestResourceURL; + private: void RunTestImpl(const GURL& url); - private: std::unique_ptr<TestChromeWebUIControllerFactory> webui_controller_factory_; base::FilePath base_path_; };
diff --git a/chrome/browser/chromeos/file_manager/file_tasks_notifier.cc b/chrome/browser/chromeos/file_manager/file_tasks_notifier.cc index 61a9d57..38019659 100644 --- a/chrome/browser/chromeos/file_manager/file_tasks_notifier.cc +++ b/chrome/browser/chromeos/file_manager/file_tasks_notifier.cc
@@ -171,8 +171,8 @@ void FileTasksNotifier::GetFileAvailability(PendingFileAvailabilityTask task) { if (task.url.type() != storage::kFileSystemTypeDriveFs) { base::FilePath path = std::move(task.url.path()); - base::PostTaskWithTraitsAndReplyWithResult( - FROM_HERE, {base::MayBlock()}, + base::PostTaskAndReplyWithResult( + FROM_HERE, {base::ThreadPool(), base::MayBlock()}, base::BindOnce(&base::PathExists, std::move(path)), base::BindOnce(&FileTasksNotifier::ForwardQueryResult, std::move(task)));
diff --git a/chrome/browser/chromeos/file_manager/file_watcher.cc b/chrome/browser/chromeos/file_manager/file_watcher.cc index 02ada646..3b2fc36e 100644 --- a/chrome/browser/chromeos/file_manager/file_watcher.cc +++ b/chrome/browser/chromeos/file_manager/file_watcher.cc
@@ -35,8 +35,9 @@ } // namespace FileWatcher::FileWatcher(const base::FilePath& virtual_path) - : sequenced_task_runner_(base::CreateSequencedTaskRunnerWithTraits( - {base::MayBlock(), base::TaskPriority::USER_VISIBLE})), + : sequenced_task_runner_( + base::CreateSequencedTaskRunner({base::ThreadPool(), base::MayBlock(), + base::TaskPriority::USER_VISIBLE})), local_file_watcher_(nullptr), virtual_path_(virtual_path), weak_ptr_factory_(this) {
diff --git a/chrome/browser/chromeos/file_manager/fileapi_util.cc b/chrome/browser/chromeos/file_manager/fileapi_util.cc index 77de2d0..2463e934 100644 --- a/chrome/browser/chromeos/file_manager/fileapi_util.cc +++ b/chrome/browser/chromeos/file_manager/fileapi_util.cc
@@ -328,7 +328,7 @@ // If the list includes at least one non-native file (wihtout a snapshot // file), move to IO thread to obtian metadata for the non-native file. if (need_fill_metadata) { - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {BrowserThread::IO}, base::BindOnce( &ConvertSelectedFileInfoListToFileChooserFileInfoListImpl:: @@ -358,7 +358,7 @@ DCHECK_CURRENTLY_ON(BrowserThread::IO); if (it == chooser_info_list_.end()) { - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {BrowserThread::UI}, base::BindOnce( &ConvertSelectedFileInfoListToFileChooserFileInfoListImpl:: @@ -391,7 +391,7 @@ DCHECK_CURRENTLY_ON(BrowserThread::IO); if (result != base::File::FILE_OK) { - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {BrowserThread::UI}, base::BindOnce( &ConvertSelectedFileInfoListToFileChooserFileInfoListImpl:: @@ -607,7 +607,7 @@ const storage::FileSystemURL internal_url = backend->CreateInternalURL(file_system_context.get(), directory_path); - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {BrowserThread::IO}, base::BindOnce(&CheckIfDirectoryExistsOnIoThread, file_system_context, internal_url, @@ -627,7 +627,7 @@ const storage::FileSystemURL internal_url = backend->CreateInternalURL(file_system_context.get(), entry_path); - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {BrowserThread::IO}, base::BindOnce(&GetMetadataForPathOnIoThread, file_system_context, internal_url, fields,
diff --git a/chrome/browser/chromeos/file_manager/filesystem_api_util.cc b/chrome/browser/chromeos/file_manager/filesystem_api_util.cc index 1dbb03f..6595447 100644 --- a/chrome/browser/chromeos/file_manager/filesystem_api_util.cc +++ b/chrome/browser/chromeos/file_manager/filesystem_api_util.cc
@@ -222,9 +222,8 @@ path)) { chromeos::file_system_provider::util::LocalPathParser parser(profile, path); if (!parser.Parse()) { - base::PostTaskWithTraits( - FROM_HERE, {content::BrowserThread::UI}, - base::BindOnce(std::move(callback), base::nullopt)); + base::PostTask(FROM_HERE, {content::BrowserThread::UI}, + base::BindOnce(std::move(callback), base::nullopt)); return; } @@ -243,9 +242,8 @@ auto* runner = arc::ArcFileSystemOperationRunner::GetForBrowserContext(profile); if (!runner) { - base::PostTaskWithTraits( - FROM_HERE, {content::BrowserThread::UI}, - base::BindOnce(std::move(callback), base::nullopt)); + base::PostTask(FROM_HERE, {content::BrowserThread::UI}, + base::BindOnce(std::move(callback), base::nullopt)); return; } runner->GetMimeType( @@ -258,8 +256,8 @@ // We don't have a way to obtain metadata other than drive and FSP. Returns an // error with empty MIME type, that leads fallback guessing mime type from // file extensions. - base::PostTaskWithTraits(FROM_HERE, {content::BrowserThread::UI}, - base::BindOnce(std::move(callback), base::nullopt)); + base::PostTask(FROM_HERE, {content::BrowserThread::UI}, + base::BindOnce(std::move(callback), base::nullopt)); } void IsNonNativeLocalPathDirectory(Profile* profile, @@ -286,8 +284,8 @@ profile, path, kFileManagerAppId, &url)) { // Posting to the current thread, so that we always call back asynchronously // independent from whether or not the operation succeeds. - base::PostTaskWithTraits(FROM_HERE, {content::BrowserThread::UI}, - base::BindOnce(std::move(callback), false)); + base::PostTask(FROM_HERE, {content::BrowserThread::UI}, + base::BindOnce(std::move(callback), false)); return; } @@ -300,7 +298,7 @@ const storage::FileSystemURL internal_url = backend->CreateInternalURL(file_system_context.get(), path); - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {content::BrowserThread::IO}, base::BindOnce(&PrepareFileOnIOThread, file_system_context, internal_url, google_apis::CreateRelayCallback(std::move(callback))));
diff --git a/chrome/browser/chromeos/file_manager/open_with_browser.cc b/chrome/browser/chromeos/file_manager/open_with_browser.cc index 0e1d3bb..70b25d9 100644 --- a/chrome/browser/chromeos/file_manager/open_with_browser.cc +++ b/chrome/browser/chromeos/file_manager/open_with_browser.cc
@@ -132,8 +132,8 @@ // Parse a local file to extract the Docs url and open this url. void OpenGDocUrlFromFile(const base::FilePath& file_path, Profile* profile) { - base::PostTaskWithTraitsAndReplyWithResult( - FROM_HERE, {base::MayBlock()}, + base::PostTaskAndReplyWithResult( + FROM_HERE, {base::ThreadPool(), base::MayBlock()}, base::BindOnce(&ReadUrlFromGDocAsync, file_path), base::BindOnce(&OpenNewTab, profile)); }
diff --git a/chrome/browser/chromeos/file_manager/snapshot_manager.cc b/chrome/browser/chromeos/file_manager/snapshot_manager.cc index 49a6628..53c8788 100644 --- a/chrome/browser/chromeos/file_manager/snapshot_manager.cc +++ b/chrome/browser/chromeos/file_manager/snapshot_manager.cc
@@ -53,8 +53,9 @@ return; } - base::PostTaskWithTraitsAndReplyWithResult( - FROM_HERE, {base::MayBlock(), base::TaskPriority::USER_BLOCKING}, + base::PostTaskAndReplyWithResult( + FROM_HERE, + {base::ThreadPool(), base::MayBlock(), base::TaskPriority::USER_BLOCKING}, base::BindOnce(&ComputeSpaceNeedToBeFreedAfterGetMetadataAsync, path, file_info.size), std::move(callback)); @@ -81,7 +82,7 @@ const storage::FileSystemURL& url, GetNecessaryFreeSpaceCallback callback) { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {content::BrowserThread::IO}, base::BindOnce(&GetMetadataOnIOThread, profile->GetPath(), context, url, google_apis::CreateRelayCallback(std::move(callback)))); @@ -222,7 +223,7 @@ DCHECK(context.get()); // Free up space if needed and start creating the snapshot. - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {content::BrowserThread::IO}, base::BindOnce(&FileRefsHolder::FreeSpaceAndCreateSnapshotFile, holder_, context, filesystem_url, needed_space,
diff --git a/chrome/browser/chromeos/file_manager/volume_manager.cc b/chrome/browser/chromeos/file_manager/volume_manager.cc index 72dd587..d8ddaeb 100644 --- a/chrome/browser/chromeos/file_manager/volume_manager.cc +++ b/chrome/browser/chromeos/file_manager/volume_manager.cc
@@ -516,9 +516,10 @@ Volume::CreateForDownloads(localVolume)); // Asyncrhonously record the disk usage for the downloads path - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, - {base::MayBlock(), base::TaskShutdownBehavior::SKIP_ON_SHUTDOWN, + {base::ThreadPool(), base::MayBlock(), + base::TaskShutdownBehavior::SKIP_ON_SHUTDOWN, base::TaskPriority::BEST_EFFORT}, base::BindOnce(&RecordDownloadsDiskUsageStats, std::move(localVolume))); @@ -1223,7 +1224,7 @@ storage::FileSystemMountOption(), path); DCHECK(result); - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {content::BrowserThread::IO}, base::BindOnce(&MTPDeviceMapService::RegisterMTPFileSystem, base::Unretained(MTPDeviceMapService::GetInstance()), @@ -1244,7 +1245,7 @@ const std::string fsid = GetMountPointNameForMediaStorage(info); storage::ExternalMountPoints::GetSystemInstance()->RevokeFileSystem(fsid); - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {content::BrowserThread::IO}, base::BindOnce(&MTPDeviceMapService::RevokeMTPFileSystem, base::Unretained(MTPDeviceMapService::GetInstance()),
diff --git a/chrome/browser/chromeos/file_system_provider/fileapi/file_stream_reader.cc b/chrome/browser/chromeos/file_system_provider/fileapi/file_stream_reader.cc index ca9e419..329072d 100644 --- a/chrome/browser/chromeos/file_system_provider/fileapi/file_stream_reader.cc +++ b/chrome/browser/chromeos/file_system_provider/fileapi/file_stream_reader.cc
@@ -50,7 +50,7 @@ util::FileSystemURLParser parser(url); if (!parser.Parse()) { - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {BrowserThread::IO}, base::BindOnce(std::move(callback), base::File::FILE_ERROR_SECURITY)); return; @@ -78,9 +78,9 @@ // If the file system got unmounted, then abort the reading operation. if (!file_system_.get()) { - base::PostTaskWithTraits(FROM_HERE, {BrowserThread::IO}, - base::BindOnce(callback, 0, false /* has_more */, - base::File::FILE_ERROR_ABORT)); + base::PostTask(FROM_HERE, {BrowserThread::IO}, + base::BindOnce(callback, 0, false /* has_more */, + base::File::FILE_ERROR_ABORT)); return; } @@ -102,7 +102,7 @@ // If the file system got unmounted, then abort the get length operation. if (!file_system_.get()) { - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {BrowserThread::IO}, base::BindOnce(std::move(callback), base::Passed(base::WrapUnique<EntryMetadata>(NULL)), @@ -152,8 +152,8 @@ if (result == base::File::FILE_OK) file_handle_ = file_handle; - base::PostTaskWithTraits(FROM_HERE, {BrowserThread::IO}, - base::BindOnce(std::move(callback), result)); + base::PostTask(FROM_HERE, {BrowserThread::IO}, + base::BindOnce(std::move(callback), result)); } // Forwards a metadata to the IO thread. @@ -164,7 +164,7 @@ DCHECK_CURRENTLY_ON(BrowserThread::UI); abort_callback_ = AbortCallback(); - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {BrowserThread::IO}, base::BindOnce(std::move(callback), base::Passed(&metadata), result)); } @@ -180,9 +180,9 @@ if (!has_more) abort_callback_ = AbortCallback(); - base::PostTaskWithTraits(FROM_HERE, {BrowserThread::IO}, - base::BindOnce(chunk_received_callback, - chunk_length, has_more, result)); + base::PostTask(FROM_HERE, {BrowserThread::IO}, + base::BindOnce(chunk_received_callback, chunk_length, + has_more, result)); } AbortCallback abort_callback_; @@ -210,7 +210,7 @@ // FileStreamReader doesn't have a Cancel() method like in FileStreamWriter. // Therefore, aborting and/or closing an opened file is done from the // destructor. - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {BrowserThread::UI}, base::BindOnce(&OperationRunner::CloseRunnerOnUIThread, runner_)); @@ -225,7 +225,7 @@ DCHECK_EQ(NOT_INITIALIZED, state_); state_ = INITIALIZING; - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {BrowserThread::UI}, base::BindOnce(&OperationRunner::OpenFileOnUIThread, runner_, url_, base::BindOnce(&FileStreamReader::OnOpenFileCompleted, @@ -252,7 +252,7 @@ DCHECK_EQ(base::File::FILE_OK, result); // Verify the last modification time. - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {BrowserThread::UI}, base::BindOnce(&OperationRunner::GetMetadataOnUIThread, runner_, base::BindOnce(&FileStreamReader::OnInitializeCompleted, @@ -385,20 +385,19 @@ DCHECK_EQ(INITIALIZED, state_); current_length_ = 0; - base::PostTaskWithTraits( - FROM_HERE, {BrowserThread::UI}, - base::BindOnce( - &OperationRunner::ReadFileOnUIThread, runner_, buffer, - current_offset_, buffer_length, - base::BindRepeating(&FileStreamReader::OnReadChunkReceived, - weak_ptr_factory_.GetWeakPtr(), callback))); + base::PostTask(FROM_HERE, {BrowserThread::UI}, + base::BindOnce(&OperationRunner::ReadFileOnUIThread, runner_, + buffer, current_offset_, buffer_length, + base::BindRepeating( + &FileStreamReader::OnReadChunkReceived, + weak_ptr_factory_.GetWeakPtr(), callback))); } void FileStreamReader::GetLengthAfterInitialized() { DCHECK_CURRENTLY_ON(BrowserThread::IO); DCHECK_EQ(INITIALIZED, state_); - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {BrowserThread::UI}, base::BindOnce( &OperationRunner::GetMetadataOnUIThread, runner_,
diff --git a/chrome/browser/chromeos/file_system_provider/fileapi/file_stream_writer.cc b/chrome/browser/chromeos/file_system_provider/fileapi/file_stream_writer.cc index 15fdfbd8..633df064 100644 --- a/chrome/browser/chromeos/file_system_provider/fileapi/file_stream_writer.cc +++ b/chrome/browser/chromeos/file_system_provider/fileapi/file_stream_writer.cc
@@ -43,7 +43,7 @@ util::FileSystemURLParser parser(url); if (!parser.Parse()) { - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {BrowserThread::IO}, base::BindOnce(std::move(callback), base::File::FILE_ERROR_SECURITY)); return; @@ -67,7 +67,7 @@ // If the file system got unmounted, then abort the writing operation. if (!file_system_.get()) { - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {BrowserThread::IO}, base::BindOnce(std::move(callback), base::File::FILE_ERROR_ABORT)); return; @@ -113,8 +113,8 @@ if (result == base::File::FILE_OK) file_handle_ = file_handle; - base::PostTaskWithTraits(FROM_HERE, {BrowserThread::IO}, - base::BindOnce(std::move(callback), result)); + base::PostTask(FROM_HERE, {BrowserThread::IO}, + base::BindOnce(std::move(callback), result)); } // Forwards a response of writing to a file to the IO thread. @@ -124,8 +124,8 @@ DCHECK_CURRENTLY_ON(BrowserThread::UI); abort_callback_ = AbortCallback(); - base::PostTaskWithTraits(FROM_HERE, {BrowserThread::IO}, - base::BindOnce(std::move(callback), result)); + base::PostTask(FROM_HERE, {BrowserThread::IO}, + base::BindOnce(std::move(callback), result)); } AbortCallback abort_callback_; @@ -147,7 +147,7 @@ FileStreamWriter::~FileStreamWriter() { // Close the runner explicitly if the file streamer is if (state_ != CANCELLING) { - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {BrowserThread::UI}, base::BindOnce(&OperationRunner::CloseRunnerOnUIThread, runner_)); } @@ -163,7 +163,7 @@ DCHECK_EQ(NOT_INITIALIZED, state_); state_ = INITIALIZING; - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {BrowserThread::UI}, base::BindOnce(&OperationRunner::OpenFileOnUIThread, runner_, url_, base::BindOnce(&FileStreamWriter::OnOpenFileCompleted, @@ -251,7 +251,7 @@ // Abort and optimistically return an OK result code, as the aborting // operation is always forced and can't be cancelled. Similarly, for closing // files. - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {BrowserThread::UI}, base::BindOnce(&OperationRunner::CloseRunnerOnUIThread, runner_)); base::ThreadTaskRunnerHandle::Get()->PostTask( @@ -317,7 +317,7 @@ state_ = EXECUTING; - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {BrowserThread::UI}, base::BindOnce(&OperationRunner::WriteFileOnUIThread, runner_, buffer, current_offset_, buffer_length,
diff --git a/chrome/browser/chromeos/file_system_provider/fileapi/provider_async_file_util.cc b/chrome/browser/chromeos/file_system_provider/fileapi/provider_async_file_util.cc index 7ae056cb..9a4b9578 100644 --- a/chrome/browser/chromeos/file_system_provider/fileapi/provider_async_file_util.cc +++ b/chrome/browser/chromeos/file_system_provider/fileapi/provider_async_file_util.cc
@@ -58,7 +58,7 @@ std::unique_ptr<EntryMetadata> metadata, base::File::Error result) { if (result != base::File::FILE_OK) { - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {BrowserThread::IO}, base::BindOnce(std::move(callback), result, base::File::Info())); return; @@ -82,7 +82,7 @@ file_info.is_symbolic_link = false; // Not supported. - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {BrowserThread::IO}, base::BindOnce(std::move(callback), base::File::FILE_OK, file_info)); } @@ -108,7 +108,7 @@ base::File::Error result, storage::AsyncFileUtil::EntryList entry_list, bool has_more) { - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {BrowserThread::IO}, base::BindOnce(callback, result, std::move(entry_list), has_more)); } @@ -141,8 +141,8 @@ ? base::File::FILE_OK : result; - base::PostTaskWithTraits(FROM_HERE, {BrowserThread::IO}, - base::BindOnce(std::move(callback), error)); + base::PostTask(FROM_HERE, {BrowserThread::IO}, + base::BindOnce(std::move(callback), error)); } // Executes DeleteEntry on the UI thread. @@ -164,8 +164,8 @@ // Routes the response of DeleteEntry back to the IO thread. void OnDeleteEntry(storage::AsyncFileUtil::StatusCallback callback, base::File::Error result) { - base::PostTaskWithTraits(FROM_HERE, {BrowserThread::IO}, - base::BindOnce(std::move(callback), result)); + base::PostTask(FROM_HERE, {BrowserThread::IO}, + base::BindOnce(std::move(callback), result)); } // Executes CreateFile on the UI thread. @@ -194,8 +194,8 @@ const base::File::Error error = result == base::File::FILE_ERROR_EXISTS ? base::File::FILE_OK : result; - base::PostTaskWithTraits(FROM_HERE, {BrowserThread::IO}, - base::BindOnce(std::move(callback), error, created)); + base::PostTask(FROM_HERE, {BrowserThread::IO}, + base::BindOnce(std::move(callback), error, created)); } // Executes CopyEntry on the UI thread. @@ -222,8 +222,8 @@ // IO thread. void OnCopyEntry(storage::AsyncFileUtil::StatusCallback callback, base::File::Error result) { - base::PostTaskWithTraits(FROM_HERE, {BrowserThread::IO}, - base::BindOnce(std::move(callback), result)); + base::PostTask(FROM_HERE, {BrowserThread::IO}, + base::BindOnce(std::move(callback), result)); } // Executes MoveEntry on the UI thread. @@ -250,8 +250,8 @@ // IO thread. void OnMoveEntry(storage::AsyncFileUtil::StatusCallback callback, base::File::Error result) { - base::PostTaskWithTraits(FROM_HERE, {BrowserThread::IO}, - base::BindOnce(std::move(callback), result)); + base::PostTask(FROM_HERE, {BrowserThread::IO}, + base::BindOnce(std::move(callback), result)); } // Executes Truncate on the UI thread. @@ -273,8 +273,8 @@ // Routes the response of Truncate back to the IO thread. void OnTruncate(storage::AsyncFileUtil::StatusCallback callback, base::File::Error result) { - base::PostTaskWithTraits(FROM_HERE, {BrowserThread::IO}, - base::BindOnce(std::move(callback), result)); + base::PostTask(FROM_HERE, {BrowserThread::IO}, + base::BindOnce(std::move(callback), result)); } } // namespace @@ -308,7 +308,7 @@ const storage::FileSystemURL& url, EnsureFileExistsCallback callback) { DCHECK_CURRENTLY_ON(BrowserThread::IO); - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {BrowserThread::UI}, base::BindOnce(&CreateFileOnUIThread, base::Passed(&context), url, base::BindOnce(&OnCreateFileForEnsureFileExists, @@ -322,7 +322,7 @@ bool recursive, StatusCallback callback) { DCHECK_CURRENTLY_ON(BrowserThread::IO); - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {BrowserThread::UI}, base::BindOnce( &CreateDirectoryOnUIThread, base::Passed(&context), url, exclusive, @@ -336,7 +336,7 @@ int fields, GetFileInfoCallback callback) { DCHECK_CURRENTLY_ON(BrowserThread::IO); - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {BrowserThread::UI}, base::BindOnce( &GetFileInfoOnUIThread, base::Passed(&context), url, fields, @@ -348,7 +348,7 @@ const storage::FileSystemURL& url, ReadDirectoryCallback callback) { DCHECK_CURRENTLY_ON(BrowserThread::IO); - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {BrowserThread::UI}, base::BindOnce(&ReadDirectoryOnUIThread, std::move(context), url, base::BindRepeating(&OnReadDirectory, callback))); @@ -370,7 +370,7 @@ int64_t length, StatusCallback callback) { DCHECK_CURRENTLY_ON(BrowserThread::IO); - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {BrowserThread::UI}, base::BindOnce(&TruncateOnUIThread, base::Passed(&context), url, length, base::BindOnce(&OnTruncate, std::move(callback)))); @@ -386,7 +386,7 @@ DCHECK_CURRENTLY_ON(BrowserThread::IO); // TODO(mtomasz): Consier adding support for options (preserving last modified // time) as well as the progress callback. - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {BrowserThread::UI}, base::BindOnce(&CopyEntryOnUIThread, base::Passed(&context), src_url, dest_url, @@ -402,7 +402,7 @@ DCHECK_CURRENTLY_ON(BrowserThread::IO); // TODO(mtomasz): Consier adding support for options (preserving last modified // time) as well as the progress callback. - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {BrowserThread::UI}, base::BindOnce(&MoveEntryOnUIThread, base::Passed(&context), src_url, dest_url, @@ -423,7 +423,7 @@ const storage::FileSystemURL& url, StatusCallback callback) { DCHECK_CURRENTLY_ON(BrowserThread::IO); - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {BrowserThread::UI}, base::BindOnce(&DeleteEntryOnUIThread, base::Passed(&context), url, false, // recursive @@ -435,7 +435,7 @@ const storage::FileSystemURL& url, StatusCallback callback) { DCHECK_CURRENTLY_ON(BrowserThread::IO); - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {BrowserThread::UI}, base::BindOnce(&DeleteEntryOnUIThread, base::Passed(&context), url, false, // recursive @@ -447,7 +447,7 @@ const storage::FileSystemURL& url, StatusCallback callback) { DCHECK_CURRENTLY_ON(BrowserThread::IO); - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {BrowserThread::UI}, base::BindOnce(&DeleteEntryOnUIThread, base::Passed(&context), url, true, // recursive
diff --git a/chrome/browser/chromeos/file_system_provider/fileapi/watcher_manager.cc b/chrome/browser/chromeos/file_system_provider/fileapi/watcher_manager.cc index b3ceef61..352732b 100644 --- a/chrome/browser/chromeos/file_system_provider/fileapi/watcher_manager.cc +++ b/chrome/browser/chromeos/file_system_provider/fileapi/watcher_manager.cc
@@ -28,15 +28,15 @@ void CallStatusCallbackOnIOThread(const StatusCallback& callback, base::File::Error error) { DCHECK_CURRENTLY_ON(BrowserThread::UI); - base::PostTaskWithTraits(FROM_HERE, {BrowserThread::IO}, - base::BindOnce(callback, error)); + base::PostTask(FROM_HERE, {BrowserThread::IO}, + base::BindOnce(callback, error)); } void CallNotificationCallbackOnIOThread(const NotificationCallback& callback, ChangeType type) { DCHECK_CURRENTLY_ON(BrowserThread::UI); - base::PostTaskWithTraits(FROM_HERE, {BrowserThread::IO}, - base::BindOnce(callback, type)); + base::PostTask(FROM_HERE, {BrowserThread::IO}, + base::BindOnce(callback, type)); } void AddWatcherOnUIThread(const storage::FileSystemURL& url, @@ -92,7 +92,7 @@ const StatusCallback& callback, const NotificationCallback& notification_callback) { DCHECK_CURRENTLY_ON(BrowserThread::IO); - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {BrowserThread::UI}, base::BindOnce(&AddWatcherOnUIThread, url, recursive, base::Bind(&CallStatusCallbackOnIOThread, callback), @@ -104,7 +104,7 @@ bool recursive, const StatusCallback& callback) { DCHECK_CURRENTLY_ON(BrowserThread::IO); - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {BrowserThread::UI}, base::BindOnce(&RemoveWatcherOnUIThread, url, recursive, base::Bind(&CallStatusCallbackOnIOThread, callback)));
diff --git a/chrome/browser/chromeos/fileapi/external_file_resolver.cc b/chrome/browser/chromeos/fileapi/external_file_resolver.cc index e7c0529c..103ff9f6 100644 --- a/chrome/browser/chromeos/fileapi/external_file_resolver.cc +++ b/chrome/browser/chromeos/fileapi/external_file_resolver.cc
@@ -46,7 +46,7 @@ : callback_(std::move(callback)) { DCHECK_CURRENTLY_ON(content::BrowserThread::IO); Lifetime lifetime(this); - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {content::BrowserThread::UI}, base::BindOnce(&URLHelper::RunOnUIThread, base::Unretained(this), std::move(lifetime), profile_id, url)); @@ -108,7 +108,7 @@ void ReplyResult(net::Error error) { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {content::BrowserThread::IO}, base::BindOnce(std::move(callback_), error, std::move(file_system_context_),
diff --git a/chrome/browser/chromeos/fileapi/external_file_url_loader_factory.cc b/chrome/browser/chromeos/fileapi/external_file_url_loader_factory.cc index 30b6967..1fcb7fd 100644 --- a/chrome/browser/chromeos/fileapi/external_file_url_loader_factory.cc +++ b/chrome/browser/chromeos/fileapi/external_file_url_loader_factory.cc
@@ -359,7 +359,7 @@ mojo::ReportBadMessage("Unauthorized externalfile request"); return; } - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {content::BrowserThread::IO}, base::BindOnce(&ExternalFileURLLoader::CreateAndStart, profile_id_, request, std::move(loader), client.PassInterface()));
diff --git a/chrome/browser/chromeos/fileapi/file_system_backend.cc b/chrome/browser/chromeos/fileapi/file_system_backend.cc index edc3bc31c..b197f17 100644 --- a/chrome/browser/chromeos/fileapi/file_system_backend.cc +++ b/chrome/browser/chromeos/fileapi/file_system_backend.cc
@@ -348,8 +348,9 @@ return storage::FileSystemOperation::Create( url, context, std::make_unique<storage::FileSystemOperationContext>( - context, base::CreateSequencedTaskRunnerWithTraits( - {base::MayBlock(), base::TaskPriority::USER_VISIBLE}) + context, base::CreateSequencedTaskRunner( + {base::ThreadPool(), base::MayBlock(), + base::TaskPriority::USER_VISIBLE}) .get())); } @@ -416,8 +417,8 @@ case storage::kFileSystemTypeDriveFs: return std::unique_ptr<storage::FileStreamReader>( storage::FileStreamReader::CreateForLocalFile( - base::CreateTaskRunnerWithTraits( - {base::MayBlock(), base::TaskPriority::USER_VISIBLE}) + base::CreateTaskRunner({base::ThreadPool(), base::MayBlock(), + base::TaskPriority::USER_VISIBLE}) .get(), url.path(), offset, expected_modification_time)); case storage::kFileSystemTypeDeviceMediaAsFileStorage: @@ -454,8 +455,8 @@ case storage::kFileSystemTypeNativeLocal: case storage::kFileSystemTypeDriveFs: return storage::FileStreamWriter::CreateForLocalFile( - base::CreateTaskRunnerWithTraits( - {base::MayBlock(), base::TaskPriority::USER_VISIBLE}) + base::CreateTaskRunner({base::ThreadPool(), base::MayBlock(), + base::TaskPriority::USER_VISIBLE}) .get(), url.path(), offset, storage::FileStreamWriter::OPEN_EXISTING_FILE); case storage::kFileSystemTypeDeviceMediaAsFileStorage:
diff --git a/chrome/browser/chromeos/fileapi/recent_disk_source.cc b/chrome/browser/chromeos/fileapi/recent_disk_source.cc index c82752a..91766b9b 100644 --- a/chrome/browser/chromeos/fileapi/recent_disk_source.cc +++ b/chrome/browser/chromeos/fileapi/recent_disk_source.cc
@@ -33,7 +33,7 @@ bool has_more) { DCHECK_CURRENTLY_ON(BrowserThread::IO); - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {BrowserThread::UI}, base::BindOnce(callback, result, std::move(entries), has_more)); } @@ -54,8 +54,8 @@ const base::File::Info& info) { DCHECK_CURRENTLY_ON(BrowserThread::IO); - base::PostTaskWithTraits(FROM_HERE, {BrowserThread::UI}, - base::BindOnce(std::move(callback), result, info)); + base::PostTask(FROM_HERE, {BrowserThread::UI}, + base::BindOnce(std::move(callback), result, info)); } void GetMetadataOnIOThread( @@ -121,7 +121,7 @@ storage::FileSystemURL url = BuildDiskURL(path); ++inflight_readdirs_; - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {BrowserThread::IO}, base::BindOnce( &ReadDirectoryOnIOThread, @@ -156,7 +156,7 @@ } else { storage::FileSystemURL url = BuildDiskURL(subpath); ++inflight_stats_; - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {BrowserThread::IO}, base::BindOnce( &GetMetadataOnIOThread,
diff --git a/chrome/browser/chromeos/fileapi/recent_drive_source.cc b/chrome/browser/chromeos/fileapi/recent_drive_source.cc index 74f4441..934232ba 100644 --- a/chrome/browser/chromeos/fileapi/recent_drive_source.cc +++ b/chrome/browser/chromeos/fileapi/recent_drive_source.cc
@@ -35,8 +35,8 @@ const base::File::Info& info) { DCHECK_CURRENTLY_ON(BrowserThread::IO); - base::PostTaskWithTraits(FROM_HERE, {BrowserThread::UI}, - base::BindOnce(std::move(callback), result, info)); + base::PostTask(FROM_HERE, {BrowserThread::UI}, + base::BindOnce(std::move(callback), result, info)); } void GetMetadataOnIOThread( @@ -136,7 +136,7 @@ params_.value().origin(), storage::kFileSystemTypeExternal, virtual_path); ++num_inflight_stats_; - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {BrowserThread::IO}, base::BindOnce( &GetMetadataOnIOThread,
diff --git a/chrome/browser/chromeos/first_run/goodies_displayer.cc b/chrome/browser/chromeos/first_run/goodies_displayer.cc index 79425c0..53fe7d1f 100644 --- a/chrome/browser/chromeos/first_run/goodies_displayer.cc +++ b/chrome/browser/chromeos/first_run/goodies_displayer.cc
@@ -84,8 +84,9 @@ const bool can_show = g_browser_process->local_state()->GetBoolean( prefs::kCanShowOobeGoodiesPage); if (can_show) { - base::PostTaskWithTraitsAndReplyWithResult( - FROM_HERE, {base::MayBlock(), base::TaskPriority::BEST_EFFORT}, + base::PostTaskAndReplyWithResult( + FROM_HERE, + {base::ThreadPool(), base::MayBlock(), base::TaskPriority::BEST_EFFORT}, base::Bind(&CheckGoodiesPrefAgainstOobeTimestamp), base::Bind(&UpdateGoodiesPrefCantShow)); }
diff --git a/chrome/browser/chromeos/guest_os/guest_os_share_path.cc b/chrome/browser/chromeos/guest_os/guest_os_share_path.cc index 46a09b4..1f0606df 100644 --- a/chrome/browser/chromeos/guest_os/guest_os_share_path.cc +++ b/chrome/browser/chromeos/guest_os/guest_os_share_path.cc
@@ -165,8 +165,9 @@ GuestOsSharePath::GuestOsSharePath(Profile* profile) : profile_(profile), - sequenced_task_runner_(base::CreateSequencedTaskRunnerWithTraits( - {base::MayBlock(), base::TaskPriority::USER_VISIBLE})), + sequenced_task_runner_( + base::CreateSequencedTaskRunner({base::ThreadPool(), base::MayBlock(), + base::TaskPriority::USER_VISIBLE})), seneschal_callback_(base::BindRepeating(LogErrorResult)) { if (auto* vmgr = file_manager::VolumeManager::Get(profile_)) { vmgr->AddObserver(this); @@ -620,7 +621,7 @@ if (error || shared_paths_.count(path) == 0 || base::PathExists(path)) { return; } - base::PostTaskWithTraitsAndReplyWithResult( + base::PostTaskAndReplyWithResult( FROM_HERE, {content::BrowserThread::UI}, base::BindOnce(&GuestOsSharePath::GetVolumeMountOnUIThread, base::Unretained(this), path), @@ -652,7 +653,7 @@ // for our tests, but otherwise do nothing and assume an UnmountEvent is // coming. if (mount_path.empty() || !base::PathExists(mount_path)) { - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {content::BrowserThread::UI}, base::BindOnce(seneschal_callback_, "ignore-delete-before-unmount", path, path, true, ""));
diff --git a/chrome/browser/chromeos/hats/hats_dialog.cc b/chrome/browser/chromeos/hats/hats_dialog.cc index d05232d..1dbdecd 100644 --- a/chrome/browser/chromeos/hats/hats_dialog.cc +++ b/chrome/browser/chromeos/hats/hats_dialog.cc
@@ -129,8 +129,9 @@ if (!user_locale.length()) user_locale = kDefaultProfileLocale; - base::PostTaskWithTraitsAndReplyWithResult( - FROM_HERE, {base::MayBlock(), base::TaskPriority::BEST_EFFORT}, + base::PostTaskAndReplyWithResult( + FROM_HERE, + {base::ThreadPool(), base::MayBlock(), base::TaskPriority::BEST_EFFORT}, base::BindOnce(&GetFormattedSiteContext, user_locale, kDeviceInfoStopKeyword), base::BindOnce(&HatsDialog::Show, is_google_account));
diff --git a/chrome/browser/chromeos/hats/hats_notification_controller.cc b/chrome/browser/chromeos/hats/hats_notification_controller.cc index acb3e7a..76f7f34 100644 --- a/chrome/browser/chromeos/hats/hats_notification_controller.cc +++ b/chrome/browser/chromeos/hats/hats_notification_controller.cc
@@ -92,8 +92,9 @@ : profile_(profile), weak_pointer_factory_(this) { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); - base::PostTaskWithTraitsAndReplyWithResult( - FROM_HERE, {base::MayBlock(), base::TaskPriority::BEST_EFFORT}, + base::PostTaskAndReplyWithResult( + FROM_HERE, + {base::ThreadPool(), base::MayBlock(), base::TaskPriority::BEST_EFFORT}, base::BindOnce(&IsNewDevice), base::BindOnce(&HatsNotificationController::Initialize, weak_pointer_factory_.GetWeakPtr()));
diff --git a/chrome/browser/chromeos/input_method/component_extension_ime_manager_impl.cc b/chrome/browser/chromeos/input_method/component_extension_ime_manager_impl.cc index 2827393..1d18c78 100644 --- a/chrome/browser/chromeos/input_method/component_extension_ime_manager_impl.cc +++ b/chrome/browser/chromeos/input_method/component_extension_ime_manager_impl.cc
@@ -168,10 +168,11 @@ // and InputMethodEngine creation, so that the virtual keyboard web content // url won't be override by IME component extensions. base::FilePath* copied_file_path = new base::FilePath(file_path); - base::PostTaskWithTraitsAndReplyWithResult( + base::PostTaskAndReplyWithResult( // USER_BLOCKING because it is on the critical path of displaying the // virtual keyboard. See https://crbug.com/976542 - FROM_HERE, {base::MayBlock(), base::TaskPriority::USER_BLOCKING}, + FROM_HERE, + {base::ThreadPool(), base::MayBlock(), base::TaskPriority::USER_BLOCKING}, base::Bind(&CheckFilePath, base::Unretained(copied_file_path)), base::Bind(&OnFilePathChecked, base::Unretained(profile), base::Owned(new std::string(extension_id)),
diff --git a/chrome/browser/chromeos/input_method/input_method_syncer.cc b/chrome/browser/chromeos/input_method/input_method_syncer.cc index a27e9870..6001ef3 100644 --- a/chrome/browser/chromeos/input_method/input_method_syncer.cc +++ b/chrome/browser/chromeos/input_method/input_method_syncer.cc
@@ -230,8 +230,9 @@ std::string languages(AddSupportedInputMethodValues( preferred_languages_.GetValue(), preferred_languages_syncable, language::prefs::kPreferredLanguages)); - base::PostTaskWithTraitsAndReplyWithResult( - FROM_HERE, {base::MayBlock(), base::TaskPriority::BEST_EFFORT}, + base::PostTaskAndReplyWithResult( + FROM_HERE, + {base::ThreadPool(), base::MayBlock(), base::TaskPriority::BEST_EFFORT}, base::Bind(&CheckAndResolveLocales, languages), base::Bind(&InputMethodSyncer::FinishMerge, weak_factory_.GetWeakPtr())); }
diff --git a/chrome/browser/chromeos/logging.cc b/chrome/browser/chromeos/logging.cc index 9276551..7676a7ab 100644 --- a/chrome/browser/chromeos/logging.cc +++ b/chrome/browser/chromeos/logging.cc
@@ -40,9 +40,8 @@ settings.log_file = log_path.value().c_str(); if (!logging::InitLogging(settings)) { DLOG(ERROR) << "Unable to initialize logging to " << log_path.value(); - base::PostTaskWithTraits( - FROM_HERE, {base::MayBlock()}, - base::BindOnce(&RemoveSymlinkAndLog, log_path, target_path)); + base::PostTask(FROM_HERE, {base::ThreadPool(), base::MayBlock()}, + base::BindOnce(&RemoveSymlinkAndLog, log_path, target_path)); return; } chrome_logging_redirected_ = true; @@ -88,8 +87,8 @@ const base::FilePath log_path = GetSessionLogFile(command_line); // Always force a new symlink when redirecting. - base::PostTaskWithTraitsAndReplyWithResult( - FROM_HERE, {base::MayBlock()}, + base::PostTaskAndReplyWithResult( + FROM_HERE, {base::ThreadPool(), base::MayBlock()}, base::BindOnce(&SetUpSymlinkIfNeeded, log_path, true), base::BindOnce(&SymlinkSetUp, command_line, log_path)); }
diff --git a/chrome/browser/chromeos/login/app_launch_signin_screen.cc b/chrome/browser/chromeos/login/app_launch_signin_screen.cc index 21d50dd..345e990 100644 --- a/chrome/browser/chromeos/login/app_launch_signin_screen.cc +++ b/chrome/browser/chromeos/login/app_launch_signin_screen.cc
@@ -79,9 +79,9 @@ // Note: CreateAuthenticator doesn't necessarily create // a new Authenticator object, and could reuse an existing one. authenticator_ = UserSessionManager::GetInstance()->CreateAuthenticator(this); - base::PostTaskWithTraits(FROM_HERE, {content::BrowserThread::UI}, - base::BindOnce(&Authenticator::AuthenticateToUnlock, - authenticator_.get(), user_context)); + base::PostTask(FROM_HERE, {content::BrowserThread::UI}, + base::BindOnce(&Authenticator::AuthenticateToUnlock, + authenticator_.get(), user_context)); } void AppLaunchSigninScreen::OnSigninScreenReady() {}
diff --git a/chrome/browser/chromeos/login/auth/auth_prewarmer.cc b/chrome/browser/chromeos/login/auth/auth_prewarmer.cc index 3c64117..5edb3975 100644 --- a/chrome/browser/chromeos/login/auth/auth_prewarmer.cc +++ b/chrome/browser/chromeos/login/auth/auth_prewarmer.cc
@@ -71,8 +71,8 @@ net::NetworkIsolationKey()); } if (!completion_callback_.is_null()) { - base::PostTaskWithTraits(FROM_HERE, {content::BrowserThread::UI}, - std::move(completion_callback_)); + base::PostTask(FROM_HERE, {content::BrowserThread::UI}, + std::move(completion_callback_)); } }
diff --git a/chrome/browser/chromeos/login/demo_mode/demo_extensions_external_loader.cc b/chrome/browser/chromeos/login/demo_mode/demo_extensions_external_loader.cc index 0c09c388..0ff8d93 100644 --- a/chrome/browser/chromeos/login/demo_mode/demo_extensions_external_loader.cc +++ b/chrome/browser/chromeos/login/demo_mode/demo_extensions_external_loader.cc
@@ -142,9 +142,9 @@ return; } - base::PostTaskWithTraitsAndReplyWithResult( + base::PostTaskAndReplyWithResult( FROM_HERE, - {base::MayBlock(), base::TaskPriority::USER_VISIBLE, + {base::ThreadPool(), base::MayBlock(), base::TaskPriority::USER_VISIBLE, base::TaskShutdownBehavior::SKIP_ON_SHUTDOWN}, base::BindOnce(&LoadPrefsFromDisk, demo_extension_list), base::BindOnce(
diff --git a/chrome/browser/chromeos/login/demo_mode/demo_mode_resources_remover.cc b/chrome/browser/chromeos/login/demo_mode/demo_mode_resources_remover.cc index 6d80b6e..973d0c0 100644 --- a/chrome/browser/chromeos/login/demo_mode/demo_mode_resources_remover.cc +++ b/chrome/browser/chromeos/login/demo_mode/demo_mode_resources_remover.cc
@@ -229,9 +229,10 @@ return; removal_in_progress_ = true; - base::PostTaskWithTraitsAndReplyWithResult( + base::PostTaskAndReplyWithResult( FROM_HERE, - {base::MayBlock(), base::TaskShutdownBehavior::SKIP_ON_SHUTDOWN}, + {base::ThreadPool(), base::MayBlock(), + base::TaskShutdownBehavior::SKIP_ON_SHUTDOWN}, base::BindOnce(&RemoveDirectory, DemoResources::GetPreInstalledPath()), base::BindOnce(&DemoModeResourcesRemover::OnRemovalDone, weak_ptr_factory_.GetWeakPtr(), reason));
diff --git a/chrome/browser/chromeos/login/demo_mode/demo_session.cc b/chrome/browser/chromeos/login/demo_mode/demo_session.cc index 16c053fb3..4d09b5d 100644 --- a/chrome/browser/chromeos/login/demo_mode/demo_session.cc +++ b/chrome/browser/chromeos/login/demo_mode/demo_session.cc
@@ -453,8 +453,9 @@ DCHECK(profile); const base::FilePath downloads = file_manager::util::GetDownloadsFolderForProfile(profile); - base::PostTaskWithTraits( - FROM_HERE, {base::TaskPriority::USER_VISIBLE, base::MayBlock()}, + base::PostTask( + FROM_HERE, + {base::ThreadPool(), base::TaskPriority::USER_VISIBLE, base::MayBlock()}, base::BindOnce(&InstallDemoMedia, demo_resources_->path(), downloads)); }
diff --git a/chrome/browser/chromeos/login/demo_mode/demo_setup_controller.cc b/chrome/browser/chromeos/login/demo_mode/demo_setup_controller.cc index ce20008e..10844d9 100644 --- a/chrome/browser/chromeos/login/demo_mode/demo_setup_controller.cc +++ b/chrome/browser/chromeos/login/demo_mode/demo_setup_controller.cc
@@ -637,9 +637,10 @@ preinstalled_demo_resources_->GetAbsolutePath( base::FilePath(kOfflinePolicyDirectoryName) .AppendASCII(kOfflineDeviceLocalAccountPolicyFileName)); - base::PostTaskWithTraitsAndReplyWithResult( + base::PostTaskAndReplyWithResult( FROM_HERE, - {base::MayBlock(), base::TaskShutdownBehavior::SKIP_ON_SHUTDOWN}, + {base::ThreadPool(), base::MayBlock(), + base::TaskShutdownBehavior::SKIP_ON_SHUTDOWN}, base::BindOnce(&ReadFileToOptionalString, file_path), base::BindOnce(&DemoSetupController::OnDeviceLocalAccountPolicyLoaded, weak_ptr_factory_.GetWeakPtr()));
diff --git a/chrome/browser/chromeos/login/easy_unlock/easy_unlock_tpm_key_manager.cc b/chrome/browser/chromeos/login/easy_unlock/easy_unlock_tpm_key_manager.cc index 1d3a7a4..6ddfb4b 100644 --- a/chrome/browser/chromeos/login/easy_unlock/easy_unlock_tpm_key_manager.cc +++ b/chrome/browser/chromeos/login/easy_unlock/easy_unlock_tpm_key_manager.cc
@@ -238,7 +238,7 @@ base::Bind(&EasyUnlockTpmKeyManager::OnUserTPMInitialized, get_tpm_slot_weak_ptr_factory_.GetWeakPtr(), key); - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {content::BrowserThread::IO}, base::BindOnce(&EnsureUserTPMInitializedOnIOThread, username_hash_, base::ThreadTaskRunnerHandle::Get(), on_user_tpm_ready)); @@ -288,10 +288,10 @@ base::Bind(&EasyUnlockTpmKeyManager::SignDataWithSystemSlot, weak_ptr_factory_.GetWeakPtr(), key, data, callback); - base::PostTaskWithTraits(FROM_HERE, {content::BrowserThread::IO}, - base::BindOnce(&GetSystemSlotOnIOThread, - base::ThreadTaskRunnerHandle::Get(), - sign_with_system_slot)); + base::PostTask(FROM_HERE, {content::BrowserThread::IO}, + base::BindOnce(&GetSystemSlotOnIOThread, + base::ThreadTaskRunnerHandle::Get(), + sign_with_system_slot)); } bool EasyUnlockTpmKeyManager::StartedCreatingTpmKeys() const { @@ -319,10 +319,10 @@ base::Bind(&EasyUnlockTpmKeyManager::CreateKeyInSystemSlot, get_tpm_slot_weak_ptr_factory_.GetWeakPtr(), public_key); - base::PostTaskWithTraits(FROM_HERE, {content::BrowserThread::IO}, - base::BindOnce(&GetSystemSlotOnIOThread, - base::ThreadTaskRunnerHandle::Get(), - create_key_with_system_slot)); + base::PostTask(FROM_HERE, {content::BrowserThread::IO}, + base::BindOnce(&GetSystemSlotOnIOThread, + base::ThreadTaskRunnerHandle::Get(), + create_key_with_system_slot)); } void EasyUnlockTpmKeyManager::CreateKeyInSystemSlot( @@ -338,9 +338,10 @@ get_tpm_slot_weak_ptr_factory_.InvalidateWeakPtrs(); // This task interacts with the TPM, hence MayBlock(). - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, - {base::MayBlock(), base::TaskShutdownBehavior::CONTINUE_ON_SHUTDOWN}, + {base::ThreadPool(), base::MayBlock(), + base::TaskShutdownBehavior::CONTINUE_ON_SHUTDOWN}, base::BindOnce(&CreateTpmKeyPairOnWorkerThread, base::Passed(&system_slot), public_key, base::ThreadTaskRunnerHandle::Get(), @@ -356,9 +357,10 @@ CHECK(system_slot); // This task interacts with the TPM, hence MayBlock(). - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, - {base::MayBlock(), base::TaskShutdownBehavior::CONTINUE_ON_SHUTDOWN}, + {base::ThreadPool(), base::MayBlock(), + base::TaskShutdownBehavior::CONTINUE_ON_SHUTDOWN}, base::BindOnce(&SignDataOnWorkerThread, base::Passed(&system_slot), public_key, data, base::ThreadTaskRunnerHandle::Get(), base::Bind(&EasyUnlockTpmKeyManager::OnDataSigned,
diff --git a/chrome/browser/chromeos/login/easy_unlock/easy_unlock_tpm_key_manager_unittest.cc b/chrome/browser/chromeos/login/easy_unlock/easy_unlock_tpm_key_manager_unittest.cc index 4ca016d..6bf464fe 100644 --- a/chrome/browser/chromeos/login/easy_unlock/easy_unlock_tpm_key_manager_unittest.cc +++ b/chrome/browser/chromeos/login/easy_unlock/easy_unlock_tpm_key_manager_unittest.cc
@@ -235,7 +235,7 @@ bool success = false; base::RunLoop run_loop; // Has to be done on IO thread due to thread assertions in nss code. - base::PostTaskWithTraitsAndReply( + base::PostTaskAndReply( FROM_HERE, {content::BrowserThread::IO}, base::BindOnce(&EasyUnlockTpmKeyManagerTest::InitTestNssUserOnIOThread, base::Unretained(this), base::Unretained(&success)), @@ -259,7 +259,7 @@ base::RunLoop run_loop; // Has to be done on IO thread due to thread assertions in nss code. - base::PostTaskWithTraitsAndReply( + base::PostTaskAndReply( FROM_HERE, {content::BrowserThread::IO}, base::BindOnce( &EasyUnlockTpmKeyManagerTest::FinalizeTestNssUserOnIOThread, @@ -273,7 +273,7 @@ void ResetTestNssUser() { base::RunLoop run_loop; // Has to be done on IO thread due to thread assertions in nss code. - base::PostTaskWithTraitsAndReply( + base::PostTaskAndReply( FROM_HERE, {content::BrowserThread::IO}, base::BindOnce(&EasyUnlockTpmKeyManagerTest::ResetTestNssUserOnIOThread, base::Unretained(this)),
diff --git a/chrome/browser/chromeos/login/existing_user_controller.cc b/chrome/browser/chromeos/login/existing_user_controller.cc index 4af7571b..a6d915c 100644 --- a/chrome/browser/chromeos/login/existing_user_controller.cc +++ b/chrome/browser/chromeos/login/existing_user_controller.cc
@@ -171,8 +171,8 @@ VLOG(1) << "Main request context populated with authentication data."; // Last but not least tell the policy subsystem to refresh now as it might // have been stuck until now too. - base::PostTaskWithTraits(FROM_HERE, {content::BrowserThread::UI}, - base::BindOnce(&RefreshPoliciesOnUIThread)); + base::PostTask(FROM_HERE, {content::BrowserThread::UI}, + base::BindOnce(&RefreshPoliciesOnUIThread)); } void TransferHttpAuthCacheToSystemNetworkContext( @@ -883,7 +883,7 @@ // Using Untretained here is safe because SessionTerminationManager is // destroyed after the task runner, in // ChromeBrowserMainParts::PostDestroyThreads(). - base::PostDelayedTaskWithTraits( + base::PostDelayedTask( FROM_HERE, {content::BrowserThread::UI}, base::BindOnce(&SessionTerminationManager::StopSession, base::Unretained(SessionTerminationManager::Get())),
diff --git a/chrome/browser/chromeos/login/lock/screen_locker.cc b/chrome/browser/chromeos/login/lock/screen_locker.cc index 9b0b601b..c6b9c867 100644 --- a/chrome/browser/chromeos/login/lock/screen_locker.cc +++ b/chrome/browser/chromeos/login/lock/screen_locker.cc
@@ -453,7 +453,7 @@ ->GetSupervisedUserManager() ->GetAuthentication() ->TransformKey(user_context); - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {BrowserThread::UI}, base::BindOnce( &ExtendedAuthenticator::AuthenticateToCheck, @@ -477,7 +477,7 @@ user_context.GetKey()->GetSecret()); } - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {BrowserThread::UI}, base::BindOnce(&ExtendedAuthenticator::AuthenticateToCheck, extended_authenticator_.get(), user_context,
diff --git a/chrome/browser/chromeos/login/lock/screen_locker.h b/chrome/browser/chromeos/login/lock/screen_locker.h index 69587c9..31c28cc2 100644 --- a/chrome/browser/chromeos/login/lock/screen_locker.h +++ b/chrome/browser/chromeos/login/lock/screen_locker.h
@@ -21,6 +21,7 @@ #include "base/timer/timer.h" #include "chrome/browser/chromeos/login/challenge_response_auth_keys_loader.h" #include "chrome/browser/chromeos/login/help_app_launcher.h" +#include "chrome/browser/chromeos/login/security_token_pin_dialog_host_ash_impl.h" #include "chrome/browser/chromeos/login/ui/login_display.h" #include "chromeos/login/auth/auth_status_consumer.h" #include "chromeos/login/auth/challenge_response_key.h" @@ -286,6 +287,8 @@ ChallengeResponseAuthKeysLoader challenge_response_auth_keys_loader_; + SecurityTokenPinDialogHostAshImpl security_token_pin_dialog_host_ash_impl_; + base::WeakPtrFactory<ScreenLocker> weak_factory_; DISALLOW_COPY_AND_ASSIGN(ScreenLocker);
diff --git a/chrome/browser/chromeos/login/lock/screen_locker_unittest.cc b/chrome/browser/chromeos/login/lock/screen_locker_unittest.cc index 6752bf4..3036ab8c 100644 --- a/chrome/browser/chromeos/login/lock/screen_locker_unittest.cc +++ b/chrome/browser/chromeos/login/lock/screen_locker_unittest.cc
@@ -14,6 +14,7 @@ #include "chrome/browser/chromeos/input_method/mock_input_method_manager_impl.h" #include "chrome/browser/chromeos/lock_screen_apps/state_controller.h" #include "chrome/browser/chromeos/login/users/fake_chrome_user_manager.h" +#include "chrome/browser/chromeos/profiles/profile_helper.h" #include "chrome/browser/chromeos/settings/device_settings_test_helper.h" #include "chrome/browser/chromeos/settings/scoped_testing_cros_settings.h" #include "chrome/browser/ui/ash/accessibility/fake_accessibility_controller.h" @@ -85,6 +86,7 @@ chromeos::AccessibilityManager::Initialize(); // Initialize ScreenLocker dependencies: + chromeos::ProfileHelper::GetSigninProfile(); SystemSaltGetter::Initialize(); const AccountId account_id = AccountId::FromUserEmail("testemail@example.com");
diff --git a/chrome/browser/chromeos/login/login_utils_browsertest.cc b/chrome/browser/chromeos/login/login_utils_browsertest.cc index f1bf38b..e5cd3f3 100644 --- a/chrome/browser/chromeos/login/login_utils_browsertest.cc +++ b/chrome/browser/chromeos/login/login_utils_browsertest.cc
@@ -108,7 +108,7 @@ { base::RunLoop loop; base::string16 rlz_string; - base::PostTaskWithTraitsAndReply( + base::PostTaskAndReply( FROM_HERE, {base::MayBlock(), base::TaskPriority::BEST_EFFORT}, base::Bind(&GetAccessPointRlzInBackgroundThread, rlz::RLZTracker::ChromeHomePage(), &rlz_string),
diff --git a/chrome/browser/chromeos/login/saml/in_session_password_change_manager.cc b/chrome/browser/chromeos/login/saml/in_session_password_change_manager.cc index c806d39..43323412 100644 --- a/chrome/browser/chromeos/login/saml/in_session_password_change_manager.cc +++ b/chrome/browser/chromeos/login/saml/in_session_password_change_manager.cc
@@ -142,11 +142,10 @@ void RecheckPasswordExpiryTask::RecheckAfter(base::TimeDelta delay) { CancelPendingRecheck(); - base::PostDelayedTaskWithTraits( - FROM_HERE, kRecheckTaskTraits, - base::BindOnce(&RecheckPasswordExpiryTask::Recheck, - weak_ptr_factory_.GetWeakPtr()), - std::max(delay, kOneHour)); + base::PostDelayedTask(FROM_HERE, kRecheckTaskTraits, + base::BindOnce(&RecheckPasswordExpiryTask::Recheck, + weak_ptr_factory_.GetWeakPtr()), + std::max(delay, kOneHour)); // This always waits at least one hour before calling Recheck again - we don't // want some bug to cause this code to run every millisecond. }
diff --git a/chrome/browser/chromeos/login/screens/recommend_apps/recommend_apps_fetcher_impl.cc b/chrome/browser/chromeos/login/screens/recommend_apps/recommend_apps_fetcher_impl.cc index bf15225..39ec0435 100644 --- a/chrome/browser/chromeos/login/screens/recommend_apps/recommend_apps_fetcher_impl.cc +++ b/chrome/browser/chromeos/login/screens/recommend_apps/recommend_apps_fetcher_impl.cc
@@ -336,8 +336,9 @@ if (!ash_ready_ || !arc_features_ready_ || has_started_proto_processing_) return; - base::PostTaskWithTraitsAndReplyWithResult( - FROM_HERE, {base::MayBlock(), base::TaskPriority::BEST_EFFORT}, + base::PostTaskAndReplyWithResult( + FROM_HERE, + {base::ThreadPool(), base::MayBlock(), base::TaskPriority::BEST_EFFORT}, base::BindOnce(&CompressAndEncodeProtoMessageOnBlockingThread, std::move(device_config_)), base::BindOnce(
diff --git a/chrome/browser/chromeos/login/security_token_pin_dialog_host_ash_impl.cc b/chrome/browser/chromeos/login/security_token_pin_dialog_host_ash_impl.cc new file mode 100644 index 0000000..a6203d3e --- /dev/null +++ b/chrome/browser/chromeos/login/security_token_pin_dialog_host_ash_impl.cc
@@ -0,0 +1,99 @@ +// Copyright 2019 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "chrome/browser/chromeos/login/security_token_pin_dialog_host_ash_impl.h" + +#include <utility> + +#include "ash/public/cpp/login_screen.h" +#include "ash/public/cpp/login_screen_model.h" +#include "ash/public/cpp/login_types.h" +#include "base/bind.h" +#include "base/logging.h" +#include "chrome/browser/chromeos/certificate_provider/certificate_provider_service.h" +#include "chrome/browser/chromeos/certificate_provider/certificate_provider_service_factory.h" +#include "chrome/browser/chromeos/certificate_provider/pin_dialog_manager.h" +#include "chrome/browser/chromeos/profiles/profile_helper.h" +#include "chrome/browser/profiles/profile.h" + +namespace chromeos { + +namespace { + +PinDialogManager* GetLoginScreenPinDialogManager() { + DCHECK(ProfileHelper::IsSigninProfileInitialized()); + CertificateProviderService* certificate_provider_service = + CertificateProviderServiceFactory::GetForBrowserContext( + ProfileHelper::GetSigninProfile()); + return certificate_provider_service->pin_dialog_manager(); +} + +} // namespace + +SecurityTokenPinDialogHostAshImpl::SecurityTokenPinDialogHostAshImpl() { + GetLoginScreenPinDialogManager()->AddPinDialogHost(this); +} + +SecurityTokenPinDialogHostAshImpl::~SecurityTokenPinDialogHostAshImpl() { + GetLoginScreenPinDialogManager()->RemovePinDialogHost(this); +} + +void SecurityTokenPinDialogHostAshImpl::ShowSecurityTokenPinDialog( + const std::string& /*caller_extension_name*/, + SecurityTokenPinCodeType code_type, + bool enable_user_input, + SecurityTokenPinErrorLabel error_label, + int attempts_left, + const base::Optional<AccountId>& /*authenticating_user_account_id*/, + SecurityTokenPinEnteredCallback pin_entered_callback, + SecurityTokenPinDialogClosedCallback pin_dialog_closed_callback) { + DCHECK(!enable_user_input || attempts_left); + DCHECK_GE(attempts_left, -1); + DCHECK(!pin_entered_callback_); + DCHECK(!pin_dialog_closed_callback_); + + Reset(); + + pin_entered_callback_ = std::move(pin_entered_callback); + pin_dialog_closed_callback_ = std::move(pin_dialog_closed_callback); + + ash::SecurityTokenPinRequest request; + request.code_type = code_type; + request.enable_user_input = enable_user_input; + request.error_label = error_label; + request.attempts_left = attempts_left; + request.pin_entered_callback = + base::BindOnce(&SecurityTokenPinDialogHostAshImpl::OnUserInputReceived, + weak_ptr_factory_.GetWeakPtr()); + request.pin_ui_closed_callback = + base::BindOnce(&SecurityTokenPinDialogHostAshImpl::OnClosed, + weak_ptr_factory_.GetWeakPtr()); + + ash::LoginScreen::Get()->RequestSecurityTokenPin(std::move(request)); +} + +void SecurityTokenPinDialogHostAshImpl::CloseSecurityTokenPinDialog() { + Reset(); + ash::LoginScreen::Get()->ClearSecurityTokenPinRequest(); +} + +void SecurityTokenPinDialogHostAshImpl::OnUserInputReceived( + const std::string& user_input) { + DCHECK(!user_input.empty()); + std::move(pin_entered_callback_).Run(user_input); +} + +void SecurityTokenPinDialogHostAshImpl::OnClosed() { + auto closed_callback = std::move(pin_dialog_closed_callback_); + Reset(); + std::move(closed_callback).Run(); +} + +void SecurityTokenPinDialogHostAshImpl::Reset() { + pin_entered_callback_.Reset(); + pin_dialog_closed_callback_.Reset(); + weak_ptr_factory_.InvalidateWeakPtrs(); +} + +} // namespace chromeos
diff --git a/chrome/browser/chromeos/login/security_token_pin_dialog_host_ash_impl.h b/chrome/browser/chromeos/login/security_token_pin_dialog_host_ash_impl.h new file mode 100644 index 0000000..829036f --- /dev/null +++ b/chrome/browser/chromeos/login/security_token_pin_dialog_host_ash_impl.h
@@ -0,0 +1,59 @@ +// Copyright 2019 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef CHROME_BROWSER_CHROMEOS_LOGIN_SECURITY_TOKEN_PIN_DIALOG_HOST_ASH_IMPL_H_ +#define CHROME_BROWSER_CHROMEOS_LOGIN_SECURITY_TOKEN_PIN_DIALOG_HOST_ASH_IMPL_H_ + +#include <string> + +#include "base/callback.h" +#include "base/macros.h" +#include "base/memory/weak_ptr.h" +#include "chrome/browser/chromeos/certificate_provider/security_token_pin_dialog_host.h" + +namespace chromeos { + +// The Ash Login/Lock screen implementation of the security token PIN dialog +// host. It displays the PIN request embedded into the user pod. +class SecurityTokenPinDialogHostAshImpl final + : public SecurityTokenPinDialogHost { + public: + SecurityTokenPinDialogHostAshImpl(); + ~SecurityTokenPinDialogHostAshImpl() override; + + // SecurityTokenPinDialogHost: + void ShowSecurityTokenPinDialog( + const std::string& caller_extension_name, + SecurityTokenPinCodeType code_type, + bool enable_user_input, + SecurityTokenPinErrorLabel error_label, + int attempts_left, + const base::Optional<AccountId>& authenticating_user_account_id, + SecurityTokenPinEnteredCallback pin_entered_callback, + SecurityTokenPinDialogClosedCallback pin_dialog_closed_callback) override; + void CloseSecurityTokenPinDialog() override; + + private: + // Called when the PIN entered by the user is received from the Ash Login/Lock + // Screen UI. + void OnUserInputReceived(const std::string& user_input); + // Called when the PIN UI gets closed. + void OnClosed(); + + // Resets the internal state and weak pointers associated with the previously + // started requests. + void Reset(); + + SecurityTokenPinEnteredCallback pin_entered_callback_; + SecurityTokenPinDialogClosedCallback pin_dialog_closed_callback_; + + base::WeakPtrFactory<SecurityTokenPinDialogHostAshImpl> weak_ptr_factory_{ + this}; + + DISALLOW_COPY_AND_ASSIGN(SecurityTokenPinDialogHostAshImpl); +}; + +} // namespace chromeos + +#endif // CHROME_BROWSER_CHROMEOS_LOGIN_SECURITY_TOKEN_PIN_DIALOG_HOST_ASH_IMPL_H_
diff --git a/chrome/browser/chromeos/login/session/user_session_manager.cc b/chrome/browser/chromeos/login/session/user_session_manager.cc index 9593fdd..601a854 100644 --- a/chrome/browser/chromeos/login/session/user_session_manager.cc +++ b/chrome/browser/chromeos/login/session/user_session_manager.cc
@@ -704,7 +704,7 @@ base::Bind(&UserSessionManager::InitRlz, AsWeakPtr(), profile)); return; } - base::PostTaskWithTraitsAndReplyWithResult( + base::PostTaskAndReplyWithResult( FROM_HERE, {base::MayBlock(), base::TaskPriority::BEST_EFFORT, base::TaskShutdownBehavior::CONTINUE_ON_SHUTDOWN},
diff --git a/chrome/browser/chromeos/login/signin/oauth2_browsertest.cc b/chrome/browser/chromeos/login/signin/oauth2_browsertest.cc index e3519ef..8bf90fd 100644 --- a/chrome/browser/chromeos/login/signin/oauth2_browsertest.cc +++ b/chrome/browser/chromeos/login/signin/oauth2_browsertest.cc
@@ -214,10 +214,9 @@ void InterceptRequest(const HttpRequest& request) { start_event_.Signal(); - base::PostTaskWithTraits( - FROM_HERE, {content::BrowserThread::UI}, - base::BindOnce(&RequestDeferrer::QuitRunnerOnUIThread, - base::Unretained(this))); + base::PostTask(FROM_HERE, {content::BrowserThread::UI}, + base::BindOnce(&RequestDeferrer::QuitRunnerOnUIThread, + base::Unretained(this))); blocking_event_.Wait(); } @@ -807,9 +806,9 @@ std::unique_ptr<BasicHttpResponse> http_response(new BasicHttpResponse()); if (request_path == kHelloPagePath) { // Serving "google" page. start_event_.Signal(); - base::PostTaskWithTraits(FROM_HERE, {content::BrowserThread::UI}, - base::BindOnce(&FakeGoogle::QuitRunnerOnUIThread, - base::Unretained(this))); + base::PostTask(FROM_HERE, {content::BrowserThread::UI}, + base::BindOnce(&FakeGoogle::QuitRunnerOnUIThread, + base::Unretained(this))); http_response->set_code(net::HTTP_OK); http_response->set_content_type("text/html"); @@ -820,10 +819,9 @@ http_response->set_content(kRandomPageContent); } else if (hang_merge_session_ && request_path == kMergeSessionPath) { merge_session_event_.Signal(); - base::PostTaskWithTraits( - FROM_HERE, {content::BrowserThread::UI}, - base::BindOnce(&FakeGoogle::QuitMergeRunnerOnUIThread, - base::Unretained(this))); + base::PostTask(FROM_HERE, {content::BrowserThread::UI}, + base::BindOnce(&FakeGoogle::QuitMergeRunnerOnUIThread, + base::Unretained(this))); return std::make_unique<HungResponse>(); } else { return std::unique_ptr<HttpResponse>(); // Request not understood.
diff --git a/chrome/browser/chromeos/login/signin/oauth2_token_fetcher.cc b/chrome/browser/chromeos/login/signin/oauth2_token_fetcher.cc index 1f5a1b8..0c1c647 100644 --- a/chrome/browser/chromeos/login/signin/oauth2_token_fetcher.cc +++ b/chrome/browser/chromeos/login/signin/oauth2_token_fetcher.cc
@@ -76,7 +76,7 @@ DCHECK_CURRENTLY_ON(BrowserThread::UI); if (error.IsTransientError() && retry_count_ < kMaxRequestAttemptCount) { retry_count_++; - base::PostDelayedTaskWithTraits( + base::PostDelayedTask( FROM_HERE, {BrowserThread::UI}, task, base::TimeDelta::FromMilliseconds(kRequestRestartDelay)); return;
diff --git a/chrome/browser/chromeos/login/signin_partition_manager_unittest.cc b/chrome/browser/chromeos/login/signin_partition_manager_unittest.cc index 8755091..0ed89d57 100644 --- a/chrome/browser/chromeos/login/signin_partition_manager_unittest.cc +++ b/chrome/browser/chromeos/login/signin_partition_manager_unittest.cc
@@ -237,7 +237,7 @@ TEST_F(SigninPartitionManagerTest, HttpAuthCacheTransferred) { base::RunLoop loop_prepare; - base::PostTaskWithTraitsAndReply( + base::PostTaskAndReply( FROM_HERE, {content::BrowserThread::IO}, base::BindOnce(AddEntryToHttpAuthCache, base::Unretained(GetSystemNetworkContextImpl())), @@ -248,7 +248,7 @@ bool entry_found = false; base::RunLoop loop_check; - base::PostTaskWithTraitsAndReply( + base::PostTaskAndReply( FROM_HERE, {content::BrowserThread::IO}, base::BindOnce(IsEntryInHttpAuthCache, base::Unretained(GetSigninNetworkContextImpl()),
diff --git a/chrome/browser/chromeos/login/startup_utils.cc b/chrome/browser/chromeos/login/startup_utils.cc index 4f8c48e..266fffb 100644 --- a/chrome/browser/chromeos/login/startup_utils.cc +++ b/chrome/browser/chromeos/login/startup_utils.cc
@@ -138,8 +138,9 @@ g_browser_process->local_state()->GetInteger(prefs::kDeviceRegistered); if (value > 0) { // Recreate flag file in case it was lost. - base::PostTaskWithTraits( - FROM_HERE, {base::TaskPriority::BEST_EFFORT, base::MayBlock()}, + base::PostTask( + FROM_HERE, + {base::ThreadPool(), base::TaskPriority::BEST_EFFORT, base::MayBlock()}, base::BindOnce(&CreateOobeCompleteFlagFile)); return true; } else if (value == 0) { @@ -159,12 +160,14 @@ void StartupUtils::MarkDeviceRegistered(base::OnceClosure done_callback) { SaveIntegerPreferenceForced(prefs::kDeviceRegistered, 1); if (done_callback.is_null()) { - base::PostTaskWithTraits( - FROM_HERE, {base::TaskPriority::BEST_EFFORT, base::MayBlock()}, + base::PostTask( + FROM_HERE, + {base::ThreadPool(), base::TaskPriority::BEST_EFFORT, base::MayBlock()}, base::BindOnce(&CreateOobeCompleteFlagFile)); } else { - base::PostTaskWithTraitsAndReply( - FROM_HERE, {base::TaskPriority::BEST_EFFORT, base::MayBlock()}, + base::PostTaskAndReply( + FROM_HERE, + {base::ThreadPool(), base::TaskPriority::BEST_EFFORT, base::MayBlock()}, base::BindOnce(&CreateOobeCompleteFlagFile), std::move(done_callback)); } }
diff --git a/chrome/browser/chromeos/login/supervised/supervised_user_authentication.cc b/chrome/browser/chromeos/login/supervised/supervised_user_authentication.cc index 097c218c..8b894b1 100644 --- a/chrome/browser/chromeos/login/supervised/supervised_user_authentication.cc +++ b/chrome/browser/chromeos/login/supervised/supervised_user_authentication.cc
@@ -281,9 +281,9 @@ AccountId::FromUserEmail(user_id)); base::FilePath profile_path = ProfileHelper::GetProfilePathByUserIdHash(user->username_hash()); - PostTaskWithTraitsAndReplyWithResult( + PostTaskAndReplyWithResult( FROM_HERE, - {base::MayBlock(), base::TaskPriority::BEST_EFFORT, + {base::ThreadPool(), base::MayBlock(), base::TaskPriority::BEST_EFFORT, base::TaskShutdownBehavior::CONTINUE_ON_SHUTDOWN}, base::BindOnce(&LoadPasswordData, profile_path), base::BindOnce(&OnPasswordDataLoaded, success_callback,
diff --git a/chrome/browser/chromeos/login/users/avatar/user_image_manager_impl.cc b/chrome/browser/chromeos/login/users/avatar/user_image_manager_impl.cc index 25d532f8..9b99955d 100644 --- a/chrome/browser/chromeos/login/users/avatar/user_image_manager_impl.cc +++ b/chrome/browser/chromeos/login/users/avatar/user_image_manager_impl.cc
@@ -564,8 +564,8 @@ profile_image_requested_(false), has_managed_image_(false), weak_factory_(this) { - background_task_runner_ = base::CreateSequencedTaskRunnerWithTraits( - {base::MayBlock(), base::TaskPriority::BEST_EFFORT, + background_task_runner_ = base::CreateSequencedTaskRunner( + {base::ThreadPool(), base::MayBlock(), base::TaskPriority::BEST_EFFORT, base::TaskShutdownBehavior::CONTINUE_ON_SHUTDOWN}); }
diff --git a/chrome/browser/chromeos/login/users/chrome_user_manager_impl.cc b/chrome/browser/chromeos/login/users/chrome_user_manager_impl.cc index 663ee5c..578a46df 100644 --- a/chrome/browser/chromeos/login/users/chrome_user_manager_impl.cc +++ b/chrome/browser/chromeos/login/users/chrome_user_manager_impl.cc
@@ -1514,8 +1514,9 @@ const std::string& locale, base::OnceClosure on_resolved_callback, std::string* out_resolved_locale) const { - base::PostTaskWithTraitsAndReply( - FROM_HERE, {base::MayBlock(), base::TaskPriority::BEST_EFFORT}, + base::PostTaskAndReply( + FROM_HERE, + {base::ThreadPool(), base::MayBlock(), base::TaskPriority::BEST_EFFORT}, base::BindOnce(ResolveLocale, locale, base::Unretained(out_resolved_locale)), std::move(on_resolved_callback));
diff --git a/chrome/browser/chromeos/login/users/supervised_user_manager_impl.cc b/chrome/browser/chromeos/login/users/supervised_user_manager_impl.cc index f70347b6..d0c2183e 100644 --- a/chrome/browser/chromeos/login/users/supervised_user_manager_impl.cc +++ b/chrome/browser/chromeos/login/users/supervised_user_manager_impl.cc
@@ -505,9 +505,9 @@ base::FilePath profile_dir = ProfileHelper::GetProfilePathByUserIdHash( ProfileHelper::Get()->GetUserByProfile(profile)->username_hash()); PostTaskAndReplyWithResult( - base::CreateTaskRunnerWithTraits( - {base::MayBlock(), base::TaskPriority::BEST_EFFORT, - base::TaskShutdownBehavior::CONTINUE_ON_SHUTDOWN}) + base::CreateTaskRunner({base::ThreadPool(), base::MayBlock(), + base::TaskPriority::BEST_EFFORT, + base::TaskShutdownBehavior::CONTINUE_ON_SHUTDOWN}) .get(), FROM_HERE, base::Bind(&LoadSyncToken, profile_dir), callback); }
diff --git a/chrome/browser/chromeos/login/version_info_updater.cc b/chrome/browser/chromeos/login/version_info_updater.cc index c183b64..74f0ac9 100644 --- a/chrome/browser/chromeos/login/version_info_updater.cc +++ b/chrome/browser/chromeos/login/version_info_updater.cc
@@ -65,8 +65,9 @@ void VersionInfoUpdater::StartUpdate(bool is_official_build) { if (base::SysInfo::IsRunningOnChromeOS()) { - base::PostTaskWithTraitsAndReplyWithResult( - FROM_HERE, {base::MayBlock(), base::TaskPriority::BEST_EFFORT}, + base::PostTaskAndReplyWithResult( + FROM_HERE, + {base::ThreadPool(), base::MayBlock(), base::TaskPriority::BEST_EFFORT}, base::Bind(&version_loader::GetVersion, is_official_build ? version_loader::VERSION_SHORT_WITH_DATE : version_loader::VERSION_FULL),
diff --git a/chrome/browser/chromeos/login/webview_login_browsertest.cc b/chrome/browser/chromeos/login/webview_login_browsertest.cc index 631457d..6ed91c9 100644 --- a/chrome/browser/chromeos/login/webview_login_browsertest.cc +++ b/chrome/browser/chromeos/login/webview_login_browsertest.cc
@@ -433,7 +433,7 @@ { bool system_slot_constructed_successfully = false; base::RunLoop loop; - base::PostTaskWithTraitsAndReply( + base::PostTaskAndReply( FROM_HERE, {content::BrowserThread::IO}, base::BindOnce(&WebviewClientCertsLoginTest::SetUpTestSystemSlotOnIO, base::Unretained(this), @@ -585,7 +585,7 @@ return; base::RunLoop loop; - base::PostTaskWithTraitsAndReply( + base::PostTaskAndReply( FROM_HERE, {content::BrowserThread::IO}, base::BindOnce(&WebviewClientCertsLoginTest::TearDownTestSystemSlotOnIO, base::Unretained(this)),
diff --git a/chrome/browser/chromeos/login/wizard_controller.cc b/chrome/browser/chromeos/login/wizard_controller.cc index a8906adf..9cec108 100644 --- a/chrome/browser/chromeos/login/wizard_controller.cc +++ b/chrome/browser/chromeos/login/wizard_controller.cc
@@ -1121,9 +1121,8 @@ if (!enabled) return; #if defined(GOOGLE_CHROME_BUILD) - base::PostTaskWithTraits( - FROM_HERE, {base::MayBlock()}, - base::BindOnce(&breakpad::InitCrashReporter, std::string())); + base::PostTask(FROM_HERE, {base::MayBlock()}, + base::BindOnce(&breakpad::InitCrashReporter, std::string())); #endif } @@ -1161,7 +1160,7 @@ } // Launch browser and delete login host controller. - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {BrowserThread::UI}, base::BindOnce(&UserSessionManager::DoBrowserLaunch, base::Unretained(UserSessionManager::GetInstance()),
diff --git a/chrome/browser/chromeos/mobile/mobile_activator.cc b/chrome/browser/chromeos/mobile/mobile_activator.cc index 7e335283..039882a 100644 --- a/chrome/browser/chromeos/mobile/mobile_activator.cc +++ b/chrome/browser/chromeos/mobile/mobile_activator.cc
@@ -186,10 +186,9 @@ } void MobileActivator::OnSetTransactionStatus(bool success) { - base::PostTaskWithTraits( - FROM_HERE, {BrowserThread::UI}, - base::BindOnce(&MobileActivator::HandleSetTransactionStatus, - weak_ptr_factory_.GetWeakPtr(), success)); + base::PostTask(FROM_HERE, {BrowserThread::UI}, + base::BindOnce(&MobileActivator::HandleSetTransactionStatus, + weak_ptr_factory_.GetWeakPtr(), success)); } void MobileActivator::HandleSetTransactionStatus(bool success) { @@ -212,10 +211,9 @@ } void MobileActivator::OnPortalLoaded(bool success) { - base::PostTaskWithTraits( - FROM_HERE, {BrowserThread::UI}, - base::BindOnce(&MobileActivator::HandlePortalLoaded, - weak_ptr_factory_.GetWeakPtr(), success)); + base::PostTask(FROM_HERE, {BrowserThread::UI}, + base::BindOnce(&MobileActivator::HandlePortalLoaded, + weak_ptr_factory_.GetWeakPtr(), success)); } void MobileActivator::HandlePortalLoaded(bool success) { @@ -850,7 +848,7 @@ break; case PLAN_ACTIVATION_DELAY_OTASP: { UMA_HISTOGRAM_COUNTS_1M("Cellular.RetryOTASP", 1); - base::PostDelayedTaskWithTraits( + base::PostDelayedTask( FROM_HERE, {BrowserThread::UI}, base::BindOnce(&MobileActivator::RetryOTASP, weak_ptr_factory_.GetWeakPtr()),
diff --git a/chrome/browser/chromeos/net/client_cert_store_chromeos.cc b/chrome/browser/chromeos/net/client_cert_store_chromeos.cc index 18d0265..c854fbe 100644 --- a/chrome/browser/chromeos/net/client_cert_store_chromeos.cc +++ b/chrome/browser/chromeos/net/client_cert_store_chromeos.cc
@@ -67,9 +67,10 @@ scoped_refptr<crypto::CryptoModuleBlockingPasswordDelegate> password_delegate; if (!password_delegate_factory_.is_null()) password_delegate = password_delegate_factory_.Run(request->host_and_port); - base::PostTaskWithTraitsAndReplyWithResult( + base::PostTaskAndReplyWithResult( FROM_HERE, - {base::MayBlock(), base::TaskShutdownBehavior::CONTINUE_ON_SHUTDOWN}, + {base::ThreadPool(), base::MayBlock(), + base::TaskShutdownBehavior::CONTINUE_ON_SHUTDOWN}, base::BindOnce(&ClientCertStoreChromeOS::GetAndFilterCertsOnWorkerThread, base::Unretained(this), password_delegate, base::Unretained(request), std::move(additional_certs)),
diff --git a/chrome/browser/chromeos/net/delay_network_call.cc b/chrome/browser/chromeos/net/delay_network_call.cc index 1982ba62..717725b 100644 --- a/chrome/browser/chromeos/net/delay_network_call.cc +++ b/chrome/browser/chromeos/net/delay_network_call.cc
@@ -49,7 +49,7 @@ } } if (delay_network_call) { - base::PostDelayedTaskWithTraits( + base::PostDelayedTask( FROM_HERE, {content::BrowserThread::UI}, base::BindOnce(&chromeos::DelayNetworkCall, retry, std::move(callback)), retry);
diff --git a/chrome/browser/chromeos/ownership/owner_settings_service_chromeos.cc b/chrome/browser/chromeos/ownership/owner_settings_service_chromeos.cc index 0243816..c9cf6f1 100644 --- a/chrome/browser/chromeos/ownership/owner_settings_service_chromeos.cc +++ b/chrome/browser/chromeos/ownership/owner_settings_service_chromeos.cc
@@ -82,8 +82,8 @@ scoped_refptr<PublicKey> public_key; if (!owner_key_util->ImportPublicKey(&public_key_data)) { scoped_refptr<PrivateKey> private_key; - base::PostTaskWithTraits(FROM_HERE, {BrowserThread::UI}, - base::BindOnce(callback, public_key, private_key)); + base::PostTask(FROM_HERE, {BrowserThread::UI}, + base::BindOnce(callback, public_key, private_key)); return; } public_key = new PublicKey(); @@ -104,8 +104,8 @@ private_key = new PrivateKey(owner_key_util->FindPrivateKeyInSlot( public_key->data(), public_slot.get())); } - base::PostTaskWithTraits(FROM_HERE, {BrowserThread::UI}, - base::BindOnce(callback, public_key, private_key)); + base::PostTask(FROM_HERE, {BrowserThread::UI}, + base::BindOnce(callback, public_key, private_key)); } void ContinueLoadPrivateKeyOnIOThread( @@ -118,10 +118,9 @@ // TODO(eseckler): It seems loading the key is important for the UsersPrivate // extension API to work correctly during startup, which is why we cannot // currently use the BEST_EFFORT TaskPriority here. - scoped_refptr<base::TaskRunner> task_runner = - base::CreateTaskRunnerWithTraits( - {base::MayBlock(), base::TaskPriority::USER_VISIBLE, - base::TaskShutdownBehavior::SKIP_ON_SHUTDOWN}); + scoped_refptr<base::TaskRunner> task_runner = base::CreateTaskRunner( + {base::ThreadPool(), base::MayBlock(), base::TaskPriority::USER_VISIBLE, + base::TaskShutdownBehavior::SKIP_ON_SHUTDOWN}); task_runner->PostTask( FROM_HERE, base::BindOnce(&LoadPrivateKeyByPublicKeyOnWorkerThread, owner_key_util, @@ -165,10 +164,9 @@ callback.Run(false); return; } - scoped_refptr<base::TaskRunner> task_runner = - base::CreateTaskRunnerWithTraits( - {base::MayBlock(), base::TaskPriority::BEST_EFFORT, - base::TaskShutdownBehavior::SKIP_ON_SHUTDOWN}); + scoped_refptr<base::TaskRunner> task_runner = base::CreateTaskRunner( + {base::ThreadPool(), base::MayBlock(), base::TaskPriority::BEST_EFFORT, + base::TaskShutdownBehavior::SKIP_ON_SHUTDOWN}); base::PostTaskAndReplyWithResult( task_runner.get(), FROM_HERE, @@ -399,7 +397,7 @@ // Make sure NSS is initialized and NSS DB is loaded for the user before // searching for the owner key. - base::PostTaskWithTraitsAndReply( + base::PostTaskAndReply( FROM_HERE, {BrowserThread::IO}, base::Bind(base::IgnoreResult(&crypto::InitializeNSSForChromeOSUser), user_hash, @@ -702,7 +700,7 @@ return; } - bool rv = base::PostTaskWithTraits( + bool rv = base::PostTask( FROM_HERE, {BrowserThread::IO}, base::BindOnce(&LoadPrivateKeyOnIOThread, owner_key_util_, ProfileHelper::GetUserIdHashFromProfile(profile_), @@ -744,7 +742,7 @@ has_pending_fixups_ = false; scoped_refptr<base::TaskRunner> task_runner = - base::CreateTaskRunnerWithTraits({base::MayBlock()}); + base::CreateTaskRunner({base::ThreadPool(), base::MayBlock()}); bool rv = AssembleAndSignPolicyAsync( task_runner.get(), std::move(policy), base::Bind(&OwnerSettingsServiceChromeOS::OnPolicyAssembledAndSigned,
diff --git a/chrome/browser/chromeos/platform_keys/platform_keys.cc b/chrome/browser/chromeos/platform_keys/platform_keys.cc index dc6be27..22bcfa7 100644 --- a/chrome/browser/chromeos/platform_keys/platform_keys.cc +++ b/chrome/browser/chromeos/platform_keys/platform_keys.cc
@@ -69,9 +69,9 @@ // This is triggered by a call to the // chrome.platformKeys.selectClientCertificates extensions API. Completion // does not affect browser responsiveness, hence the BEST_EFFORT priority. - base::PostTaskWithTraitsAndReply( + base::PostTaskAndReply( FROM_HERE, - {base::TaskPriority::BEST_EFFORT, + {base::ThreadPool(), base::TaskPriority::BEST_EFFORT, base::TaskShutdownBehavior::CONTINUE_ON_SHUTDOWN}, base::Bind(&IntersectOnWorkerThread, certs1, certs2, intersection_ptr), base::Bind(callback, base::Passed(&intersection)));
diff --git a/chrome/browser/chromeos/platform_keys/platform_keys_nss.cc b/chrome/browser/chromeos/platform_keys/platform_keys_nss.cc index 7762043..575331b 100644 --- a/chrome/browser/chromeos/platform_keys/platform_keys_nss.cc +++ b/chrome/browser/chromeos/platform_keys/platform_keys_nss.cc
@@ -149,10 +149,9 @@ const GetCertDBCallback& callback, BrowserContext* browser_context, NSSOperationState* state) { - base::PostTaskWithTraits( - FROM_HERE, {BrowserThread::IO}, - base::BindOnce(&GetCertDatabaseOnIOThread, token_id, callback, - browser_context->GetResourceContext(), state)); + base::PostTask(FROM_HERE, {BrowserThread::IO}, + base::BindOnce(&GetCertDatabaseOnIOThread, token_id, callback, + browser_context->GetResourceContext(), state)); } class GenerateRSAKeyState : public NSSOperationState { @@ -472,9 +471,9 @@ DCHECK_CURRENTLY_ON(BrowserThread::IO); // Only the slot and not the NSSCertDatabase is required. Ignore |cert_db|. // This task interacts with the TPM, hence MayBlock(). - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, - {base::MayBlock(), base::TaskPriority::BEST_EFFORT, + {base::ThreadPool(), base::MayBlock(), base::TaskPriority::BEST_EFFORT, base::TaskShutdownBehavior::CONTINUE_ON_SHUTDOWN}, base::BindOnce(&GenerateRSAKeyOnWorkerThread, std::move(state))); } @@ -566,9 +565,9 @@ DCHECK_CURRENTLY_ON(BrowserThread::IO); // Only the slot and not the NSSCertDatabase is required. Ignore |cert_db|. // This task interacts with the TPM, hence MayBlock(). - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, - {base::MayBlock(), base::TaskPriority::BEST_EFFORT, + {base::ThreadPool(), base::MayBlock(), base::TaskPriority::BEST_EFFORT, base::TaskShutdownBehavior::CONTINUE_ON_SHUTDOWN}, base::BindOnce(&SignRSAOnWorkerThread, std::move(state))); } @@ -650,9 +649,9 @@ DCHECK_CURRENTLY_ON(BrowserThread::IO); state->certs_ = std::move(all_certs); // This task interacts with the TPM, hence MayBlock(). - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, - {base::MayBlock(), base::TaskPriority::BEST_EFFORT, + {base::ThreadPool(), base::MayBlock(), base::TaskPriority::BEST_EFFORT, base::TaskShutdownBehavior::CONTINUE_ON_SHUTDOWN}, base::BindOnce(&FilterCertificatesOnWorkerThread, std::move(state))); } @@ -892,7 +891,7 @@ std::unique_ptr<SelectCertificatesState> state(new SelectCertificatesState( user->username_hash(), use_system_key_slot, cert_request_info, callback)); - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {BrowserThread::IO}, base::BindOnce(&SelectCertificatesOnIOThread, std::move(state))); }
diff --git a/chrome/browser/chromeos/plugin_vm/plugin_vm_files.cc b/chrome/browser/chromeos/plugin_vm/plugin_vm_files.cc index 2e53a046..ae8d1fe 100644 --- a/chrome/browser/chromeos/plugin_vm/plugin_vm_files.cc +++ b/chrome/browser/chromeos/plugin_vm/plugin_vm_files.cc
@@ -36,7 +36,7 @@ LOG(ERROR) << "Failed to create PluginVm shared dir " << dir.value() << ": " << base::File::ErrorToString(error); } - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {content::BrowserThread::UI}, base::BindOnce(&DirExistsResult, dir, result, std::move(callback))); } @@ -51,9 +51,8 @@ base::FilePath dir = file_manager::util::GetMyFilesFolderForProfile(profile).Append( kPluginVmName); - base::PostTaskWithTraits( - FROM_HERE, {base::MayBlock()}, - base::BindOnce(&EnsureDirExists, dir, std::move(callback))); + base::PostTask(FROM_HERE, {base::ThreadPool(), base::MayBlock()}, + base::BindOnce(&EnsureDirExists, dir, std::move(callback))); } } // namespace plugin_vm
diff --git a/chrome/browser/chromeos/plugin_vm/plugin_vm_image_manager.cc b/chrome/browser/chromeos/plugin_vm/plugin_vm_image_manager.cc index 74c60c4..e5b43ae 100644 --- a/chrome/browser/chromeos/plugin_vm/plugin_vm_image_manager.cc +++ b/chrome/browser/chromeos/plugin_vm/plugin_vm_image_manager.cc
@@ -178,8 +178,9 @@ "signals are connected"; GetConciergeClient()->AddDiskImageObserver(this); - base::PostTaskWithTraitsAndReplyWithResult( - FROM_HERE, {base::TaskPriority::USER_VISIBLE, base::MayBlock()}, + base::PostTaskAndReplyWithResult( + FROM_HERE, + {base::ThreadPool(), base::TaskPriority::USER_VISIBLE, base::MayBlock()}, base::BindOnce(&PluginVmImageManager::PrepareFD, base::Unretained(this)), base::BindOnce(&PluginVmImageManager::OnFDPrepared, weak_ptr_factory_.GetWeakPtr())); @@ -528,8 +529,10 @@ void PluginVmImageManager::RemoveTemporaryPluginVmImageArchiveIfExists() { if (!downloaded_plugin_vm_image_archive_.empty()) { - base::PostTaskWithTraitsAndReplyWithResult( - FROM_HERE, {base::TaskPriority::USER_VISIBLE, base::MayBlock()}, + base::PostTaskAndReplyWithResult( + FROM_HERE, + {base::ThreadPool(), base::TaskPriority::USER_VISIBLE, + base::MayBlock()}, base::BindOnce(&base::DeleteFile, downloaded_plugin_vm_image_archive_, false /* recursive */), base::BindOnce(
diff --git a/chrome/browser/chromeos/policy/affiliated_invalidation_service_provider_impl.cc b/chrome/browser/chromeos/policy/affiliated_invalidation_service_provider_impl.cc index 1c496f0..6786e8e 100644 --- a/chrome/browser/chromeos/policy/affiliated_invalidation_service_provider_impl.cc +++ b/chrome/browser/chromeos/policy/affiliated_invalidation_service_provider_impl.cc
@@ -78,10 +78,9 @@ void RequestProxyResolvingSocketFactory( base::WeakPtr<invalidation::TiclInvalidationService> owner, network::mojom::ProxyResolvingSocketFactoryRequest request) { - base::PostTaskWithTraits( - FROM_HERE, {content::BrowserThread::UI}, - base::BindOnce(&RequestProxyResolvingSocketFactoryOnUIThread, owner, - std::move(request))); + base::PostTask(FROM_HERE, {content::BrowserThread::UI}, + base::BindOnce(&RequestProxyResolvingSocketFactoryOnUIThread, + owner, std::move(request))); } } // namespace @@ -422,8 +421,7 @@ GetUserAgent(), device_identity_provider_.get(), g_browser_process->gcm_driver(), base::BindRepeating(&RequestProxyResolvingSocketFactory), - base::CreateSingleThreadTaskRunnerWithTraits( - {content::BrowserThread::IO}), + base::CreateSingleThreadTaskRunner({content::BrowserThread::IO}), std::move(url_loader_factory), content::GetNetworkConnectionTracker());
diff --git a/chrome/browser/chromeos/policy/app_install_event_log_manager.cc b/chrome/browser/chromeos/policy/app_install_event_log_manager.cc index a9f8384a0..07b97c7 100644 --- a/chrome/browser/chromeos/policy/app_install_event_log_manager.cc +++ b/chrome/browser/chromeos/policy/app_install_event_log_manager.cc
@@ -66,8 +66,9 @@ scoped_refptr<base::SequencedTaskRunner> AppInstallEventLogManager::LogTaskRunnerWrapper::GetTaskRunner() { if (!task_runner_) { - task_runner_ = base::CreateSequencedTaskRunnerWithTraits( - {base::TaskShutdownBehavior::BLOCK_SHUTDOWN, base::MayBlock()}); + task_runner_ = base::CreateSequencedTaskRunner( + {base::ThreadPool(), base::TaskShutdownBehavior::BLOCK_SHUTDOWN, + base::MayBlock()}); } return task_runner_;
diff --git a/chrome/browser/chromeos/policy/app_install_event_logger.cc b/chrome/browser/chromeos/policy/app_install_event_logger.cc index 6684f3f..338c5ecb 100644 --- a/chrome/browser/chromeos/policy/app_install_event_logger.cc +++ b/chrome/browser/chromeos/policy/app_install_event_logger.cc
@@ -303,8 +303,8 @@ void AppInstallEventLogger::AddForSetOfPackagesWithDiskSpaceInfo( const std::set<std::string>& packages, std::unique_ptr<em::AppInstallReportLogEvent> event) { - base::PostTaskWithTraitsAndReplyWithResult( - FROM_HERE, {base::MayBlock()}, + base::PostTaskAndReplyWithResult( + FROM_HERE, {base::ThreadPool(), base::MayBlock()}, base::BindOnce(&AddDiskSpaceInfoToEvent, std::move(event)), base::BindOnce(&AppInstallEventLogger::AddForSetOfPackages, weak_factory_.GetWeakPtr(), packages));
diff --git a/chrome/browser/chromeos/policy/browser_policy_connector_chromeos.cc b/chrome/browser/chromeos/policy/browser_policy_connector_chromeos.cc index 5f145ee..c9bad6b5 100644 --- a/chrome/browser/chromeos/policy/browser_policy_connector_chromeos.cc +++ b/chrome/browser/chromeos/policy/browser_policy_connector_chromeos.cc
@@ -85,8 +85,8 @@ // Helper that returns a new BACKGROUND SequencedTaskRunner. Each // SequencedTaskRunner returned is independent from the others. scoped_refptr<base::SequencedTaskRunner> GetBackgroundTaskRunner() { - return base::CreateSequencedTaskRunnerWithTraits( - {base::MayBlock(), base::TaskPriority::BEST_EFFORT, + return base::CreateSequencedTaskRunner( + {base::ThreadPool(), base::MayBlock(), base::TaskPriority::BEST_EFFORT, base::TaskShutdownBehavior::SKIP_ON_SHUTDOWN}); }
diff --git a/chrome/browser/chromeos/policy/device_local_account_policy_service.cc b/chrome/browser/chromeos/policy/device_local_account_policy_service.cc index dab5d0e..b99b50f 100644 --- a/chrome/browser/chromeos/policy/device_local_account_policy_service.cc +++ b/chrome/browser/chromeos/policy/device_local_account_policy_service.cc
@@ -283,8 +283,9 @@ orphan_extension_cache_deletion_state_(NOT_STARTED), store_background_task_runner_(store_background_task_runner), extension_cache_task_runner_(extension_cache_task_runner), - resource_cache_task_runner_(base::CreateSequencedTaskRunnerWithTraits( - {base::MayBlock(), base::TaskPriority::BEST_EFFORT})), + resource_cache_task_runner_( + base::CreateSequencedTaskRunner({base::ThreadPool(), base::MayBlock(), + base::TaskPriority::BEST_EFFORT})), url_loader_factory_(url_loader_factory), local_accounts_subscription_(cros_settings_->AddSettingsObserver( chromeos::kAccountsPrefDeviceLocalAccounts,
diff --git a/chrome/browser/chromeos/policy/dm_token_storage.cc b/chrome/browser/chromeos/policy/dm_token_storage.cc index 1c58ba6..6d70e0c 100644 --- a/chrome/browser/chromeos/policy/dm_token_storage.cc +++ b/chrome/browser/chromeos/policy/dm_token_storage.cc
@@ -127,8 +127,9 @@ DCHECK_CURRENTLY_ON(content::BrowserThread::UI); DCHECK(!system_salt_.empty()); DCHECK(!dm_token_.empty()); - base::PostTaskWithTraitsAndReplyWithResult( - FROM_HERE, {base::MayBlock(), base::TaskPriority::BEST_EFFORT}, + base::PostTaskAndReplyWithResult( + FROM_HERE, + {base::ThreadPool(), base::MayBlock(), base::TaskPriority::BEST_EFFORT}, base::Bind(&EncryptToken, system_salt_, dm_token_), base::Bind(&DMTokenStorage::OnTokenEncrypted, weak_ptr_factory_.GetWeakPtr())); @@ -150,8 +151,9 @@ std::string encrypted_dm_token = local_state_->GetString(prefs::kDeviceDMToken); if (!encrypted_dm_token.empty()) { - base::PostTaskWithTraitsAndReplyWithResult( - FROM_HERE, {base::MayBlock(), base::TaskPriority::BEST_EFFORT}, + base::PostTaskAndReplyWithResult( + FROM_HERE, + {base::ThreadPool(), base::MayBlock(), base::TaskPriority::BEST_EFFORT}, base::Bind(&DecryptToken, system_salt_, encrypted_dm_token), base::Bind(&DMTokenStorage::FlushRetrieveTokenCallback, weak_ptr_factory_.GetWeakPtr()));
diff --git a/chrome/browser/chromeos/policy/enrollment_handler_chromeos.cc b/chrome/browser/chromeos/policy/enrollment_handler_chromeos.cc index 41413d0..0066dbd 100644 --- a/chrome/browser/chromeos/policy/enrollment_handler_chromeos.cc +++ b/chrome/browser/chromeos/policy/enrollment_handler_chromeos.cc
@@ -482,9 +482,10 @@ skip_robot_auth_ = true; SetStep(STEP_POLICY_FETCH); - base::PostTaskWithTraitsAndReplyWithResult( + base::PostTaskAndReplyWithResult( FROM_HERE, - {base::MayBlock(), base::TaskShutdownBehavior::SKIP_ON_SHUTDOWN}, + {base::ThreadPool(), base::MayBlock(), + base::TaskShutdownBehavior::SKIP_ON_SHUTDOWN}, base::BindOnce(&ReadFileToOptionalString, enrollment_config_.offline_policy_path), base::BindOnce(&EnrollmentHandlerChromeOS::OnOfflinePolicyBlobLoaded,
diff --git a/chrome/browser/chromeos/policy/policy_oauth2_token_fetcher.cc b/chrome/browser/chromeos/policy/policy_oauth2_token_fetcher.cc index db08a2e..4cd65be 100644 --- a/chrome/browser/chromeos/policy/policy_oauth2_token_fetcher.cc +++ b/chrome/browser/chromeos/policy/policy_oauth2_token_fetcher.cc
@@ -220,7 +220,7 @@ DCHECK_CURRENTLY_ON(BrowserThread::UI); if (error.IsTransientError() && retry_count_ < kMaxRequestAttemptCount) { retry_count_++; - base::PostDelayedTaskWithTraits( + base::PostDelayedTask( FROM_HERE, {BrowserThread::UI}, task, base::TimeDelta::FromMilliseconds(kRequestRestartDelay)); return;
diff --git a/chrome/browser/chromeos/policy/pre_signin_policy_fetcher.cc b/chrome/browser/chromeos/policy/pre_signin_policy_fetcher.cc index c6b0e3e..bfb7cc1 100644 --- a/chrome/browser/chromeos/policy/pre_signin_policy_fetcher.cc +++ b/chrome/browser/chromeos/policy/pre_signin_policy_fetcher.cc
@@ -37,7 +37,7 @@ // Traits for the tasks posted in pre-signin policy fetch. As this blocks // signin, the tasks have user-visible priority. -constexpr base::TaskTraits kTaskTraits = {base::MayBlock(), +constexpr base::TaskTraits kTaskTraits = {base::ThreadPool(), base::MayBlock(), base::TaskPriority::USER_VISIBLE}; } // namespace @@ -54,7 +54,7 @@ is_active_directory_managed_(is_active_directory_managed), account_id_(account_id), auth_key_(auth_key), - task_runner_(base::CreateSequencedTaskRunnerWithTraits(kTaskTraits)), + task_runner_(base::CreateSequencedTaskRunner(kTaskTraits)), weak_ptr_factory_(this) { DCHECK(account_id_.GetAccountType() != AccountType::ACTIVE_DIRECTORY || is_active_directory_managed_);
diff --git a/chrome/browser/chromeos/policy/remote_commands/crd_host_delegate.cc b/chrome/browser/chromeos/policy/remote_commands/crd_host_delegate.cc index cbf6a4c1..3749d4f 100644 --- a/chrome/browser/chromeos/policy/remote_commands/crd_host_delegate.cc +++ b/chrome/browser/chromeos/policy/remote_commands/crd_host_delegate.cc
@@ -321,10 +321,8 @@ // TODO(antrim): set up watchdog timer (reasonable cutoff). host_ = remoting::CreateIt2MeNativeMessagingHostForChromeOS( - base::CreateSingleThreadTaskRunnerWithTraits( - {content::BrowserThread::IO}), - base::CreateSingleThreadTaskRunnerWithTraits( - {content::BrowserThread::UI}), + base::CreateSingleThreadTaskRunner({content::BrowserThread::IO}), + base::CreateSingleThreadTaskRunner({content::BrowserThread::UI}), g_browser_process->policy_service()); host_->Start(this);
diff --git a/chrome/browser/chromeos/policy/status_collector/child_status_collector.cc b/chrome/browser/chromeos/policy/status_collector/child_status_collector.cc index a6ea925..7c418f8 100644 --- a/chrome/browser/chromeos/policy/status_collector/child_status_collector.cc +++ b/chrome/browser/chromeos/policy/status_collector/child_status_collector.cc
@@ -178,8 +178,9 @@ UpdateReportingSettings(); // Get the OS version. - base::PostTaskWithTraitsAndReplyWithResult( - FROM_HERE, {base::MayBlock(), base::TaskPriority::BEST_EFFORT}, + base::PostTaskAndReplyWithResult( + FROM_HERE, + {base::ThreadPool(), base::MayBlock(), base::TaskPriority::BEST_EFFORT}, base::BindRepeating(&chromeos::version_loader::GetVersion, chromeos::version_loader::VERSION_FULL), base::BindRepeating(&ChildStatusCollector::OnOSVersion,
diff --git a/chrome/browser/chromeos/policy/status_collector/device_status_collector.cc b/chrome/browser/chromeos/policy/status_collector/device_status_collector.cc index 420bfb0..0a1b7ed 100644 --- a/chrome/browser/chromeos/policy/status_collector/device_status_collector.cc +++ b/chrome/browser/chromeos/policy/status_collector/device_status_collector.cc
@@ -508,8 +508,9 @@ } // Call out to the blocking pool to sample disk volume info. - base::PostTaskWithTraitsAndReplyWithResult( - FROM_HERE, {base::MayBlock(), base::TaskPriority::BEST_EFFORT}, + base::PostTaskAndReplyWithResult( + FROM_HERE, + {base::ThreadPool(), base::MayBlock(), base::TaskPriority::BEST_EFFORT}, base::Bind(volume_info_fetcher, mount_points), base::Bind(&DeviceStatusCollectorState::OnVolumeInfoReceived, this)); } @@ -518,8 +519,9 @@ void SampleCPUTempInfo( const DeviceStatusCollector::CPUTempFetcher& cpu_temp_fetcher) { // Call out to the blocking pool to sample CPU temp. - base::PostTaskWithTraitsAndReplyWithResult( - FROM_HERE, {base::MayBlock(), base::TaskPriority::BEST_EFFORT}, + base::PostTaskAndReplyWithResult( + FROM_HERE, + {base::ThreadPool(), base::MayBlock(), base::TaskPriority::BEST_EFFORT}, cpu_temp_fetcher, base::Bind(&DeviceStatusCollectorState::OnCPUTempInfoReceived, this)); } @@ -546,8 +548,9 @@ const policy::DeviceStatusCollector::EMMCLifetimeFetcher& emmc_lifetime_fetcher) { // Call out to the blocking pool to read disklifetimeestimation. - base::PostTaskWithTraitsAndReplyWithResult( - FROM_HERE, {base::MayBlock(), base::TaskPriority::BEST_EFFORT}, + base::PostTaskAndReplyWithResult( + FROM_HERE, + {base::ThreadPool(), base::MayBlock(), base::TaskPriority::BEST_EFFORT}, base::BindOnce(emmc_lifetime_fetcher), base::BindOnce(&DeviceStatusCollectorState::OnEMMCLifetimeReceived, this)); @@ -852,14 +855,16 @@ UpdateReportingSettings(); // Get the OS, firmware, and TPM version info. - base::PostTaskWithTraitsAndReplyWithResult( - FROM_HERE, {base::MayBlock(), base::TaskPriority::BEST_EFFORT}, + base::PostTaskAndReplyWithResult( + FROM_HERE, + {base::ThreadPool(), base::MayBlock(), base::TaskPriority::BEST_EFFORT}, base::Bind(&chromeos::version_loader::GetVersion, chromeos::version_loader::VERSION_FULL), base::Bind(&DeviceStatusCollector::OnOSVersion, weak_factory_.GetWeakPtr())); - base::PostTaskWithTraitsAndReplyWithResult( - FROM_HERE, {base::MayBlock(), base::TaskPriority::BEST_EFFORT}, + base::PostTaskAndReplyWithResult( + FROM_HERE, + {base::ThreadPool(), base::MayBlock(), base::TaskPriority::BEST_EFFORT}, base::Bind(&chromeos::version_loader::GetFirmware), base::Bind(&DeviceStatusCollector::OnOSFirmware, weak_factory_.GetWeakPtr())); @@ -1140,8 +1145,9 @@ return; // Call out to the blocking pool to sample CPU stats. - base::PostTaskWithTraitsAndReplyWithResult( - FROM_HERE, {base::MayBlock(), base::TaskPriority::BEST_EFFORT}, + base::PostTaskAndReplyWithResult( + FROM_HERE, + {base::ThreadPool(), base::MayBlock(), base::TaskPriority::BEST_EFFORT}, cpu_statistics_fetcher_, base::Bind(&DeviceStatusCollector::ReceiveCPUStatistics, weak_factory_.GetWeakPtr(), base::Time::Now())); @@ -1211,8 +1217,9 @@ weak_factory_.GetWeakPtr(), std::move(sample), SamplingProbeResultCallback())); } else { - base::PostTaskWithTraitsAndReplyWithResult( - FROM_HERE, {base::MayBlock(), base::TaskPriority::BEST_EFFORT}, + base::PostTaskAndReplyWithResult( + FROM_HERE, + {base::ThreadPool(), base::MayBlock(), base::TaskPriority::BEST_EFFORT}, base::BindOnce(&InvokeCpuTempFetcher, cpu_temp_fetcher_), base::BindOnce(&DeviceStatusCollector::ReceiveCPUTemperature, weak_factory_.GetWeakPtr(), std::move(sample), @@ -1284,8 +1291,9 @@ } } - base::PostTaskWithTraitsAndReplyWithResult( - FROM_HERE, {base::MayBlock(), base::TaskPriority::BEST_EFFORT}, + base::PostTaskAndReplyWithResult( + FROM_HERE, + {base::ThreadPool(), base::MayBlock(), base::TaskPriority::BEST_EFFORT}, base::BindOnce(&InvokeCpuTempFetcher, cpu_temp_fetcher_), base::BindOnce(&DeviceStatusCollector::ReceiveCPUTemperature, weak_factory_.GetWeakPtr(), std::move(sample),
diff --git a/chrome/browser/chromeos/policy/system_log_uploader.cc b/chrome/browser/chromeos/policy/system_log_uploader.cc index 7e743376..fa712d9 100644 --- a/chrome/browser/chromeos/policy/system_log_uploader.cc +++ b/chrome/browser/chromeos/policy/system_log_uploader.cc
@@ -184,8 +184,9 @@ void SystemLogDelegate::LoadSystemLogs(LogUploadCallback upload_callback) { // Run ReadFiles() in the thread that interacts with the file system and // return system logs to |upload_callback| on the current thread. - base::PostTaskWithTraitsAndReplyWithResult( - FROM_HERE, {base::MayBlock(), base::TaskPriority::BEST_EFFORT}, + base::PostTaskAndReplyWithResult( + FROM_HERE, + {base::ThreadPool(), base::MayBlock(), base::TaskPriority::BEST_EFFORT}, base::BindOnce(&ReadFiles), std::move(upload_callback)); } @@ -231,8 +232,9 @@ void SystemLogDelegate::ZipSystemLogs( std::unique_ptr<SystemLogUploader::SystemLogs> system_logs, ZippedLogUploadCallback upload_callback) { - base::PostTaskWithTraitsAndReplyWithResult( - FROM_HERE, {base::MayBlock(), base::TaskPriority::BEST_EFFORT}, + base::PostTaskAndReplyWithResult( + FROM_HERE, + {base::ThreadPool(), base::MayBlock(), base::TaskPriority::BEST_EFFORT}, base::BindOnce(&ZipFiles, std::move(system_logs)), std::move(upload_callback)); }
diff --git a/chrome/browser/chromeos/policy/user_affiliation_browsertest.cc b/chrome/browser/chromeos/policy/user_affiliation_browsertest.cc index 93fc05e3..7c92b87 100644 --- a/chrome/browser/chromeos/policy/user_affiliation_browsertest.cc +++ b/chrome/browser/chromeos/policy/user_affiliation_browsertest.cc
@@ -108,7 +108,7 @@ DCHECK_CURRENTLY_ON(content::BrowserThread::UI); base::RunLoop run_loop; bool system_slot_available = false; - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {content::BrowserThread::IO}, base::BindOnce(CheckIsSystemSlotAvailableOnIOThread, profile->GetResourceContext(), &system_slot_available, @@ -224,7 +224,7 @@ void SetUpTestSystemSlot() { bool system_slot_constructed_successfully = false; base::RunLoop loop; - base::PostTaskWithTraitsAndReply( + base::PostTaskAndReply( FROM_HERE, {content::BrowserThread::IO}, base::BindOnce(&UserAffiliationBrowserTest::SetUpTestSystemSlotOnIO, base::Unretained(this), @@ -261,7 +261,7 @@ return; base::RunLoop loop; - base::PostTaskWithTraitsAndReply( + base::PostTaskAndReply( FROM_HERE, {content::BrowserThread::IO}, base::BindOnce(&UserAffiliationBrowserTest::TearDownTestSystemSlotOnIO, base::Unretained(this)),
diff --git a/chrome/browser/chromeos/policy/user_network_configuration_updater.cc b/chrome/browser/chromeos/policy/user_network_configuration_updater.cc index f84e0f2..fc17d06 100644 --- a/chrome/browser/chromeos/policy/user_network_configuration_updater.cc +++ b/chrome/browser/chromeos/policy/user_network_configuration_updater.cc
@@ -146,8 +146,7 @@ DCHECK(database); SetClientCertificateImporter( std::make_unique<chromeos::onc::CertificateImporterImpl>( - base::CreateSingleThreadTaskRunnerWithTraits( - {content::BrowserThread::IO}), + base::CreateSingleThreadTaskRunner({content::BrowserThread::IO}), database)); }
diff --git a/chrome/browser/chromeos/policy/user_network_configuration_updater_factory_browsertest.cc b/chrome/browser/chromeos/policy/user_network_configuration_updater_factory_browsertest.cc index 129c5832..2639542 100644 --- a/chrome/browser/chromeos/policy/user_network_configuration_updater_factory_browsertest.cc +++ b/chrome/browser/chromeos/policy/user_network_configuration_updater_factory_browsertest.cc
@@ -342,7 +342,7 @@ DCHECK_CURRENTLY_ON(content::BrowserThread::UI); base::RunLoop run_loop; bool cert_found = false; - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {content::BrowserThread::IO}, base::BindOnce(IsCertInNSSDatabaseOnIOThread, profile->GetResourceContext(), subject_common_name,
diff --git a/chrome/browser/chromeos/policy/user_policy_manager_builder_chromeos.cc b/chrome/browser/chromeos/policy/user_policy_manager_builder_chromeos.cc index e931647..e554d3c 100644 --- a/chrome/browser/chromeos/policy/user_policy_manager_builder_chromeos.cc +++ b/chrome/browser/chromeos/policy/user_policy_manager_builder_chromeos.cc
@@ -277,8 +277,9 @@ account_id, policy_key_dir, is_active_directory); scoped_refptr<base::SequencedTaskRunner> backend_task_runner = - base::CreateSequencedTaskRunnerWithTraits( - {base::MayBlock(), base::TaskPriority::BEST_EFFORT, + base::CreateSequencedTaskRunner( + {base::ThreadPool(), base::MayBlock(), + base::TaskPriority::BEST_EFFORT, base::TaskShutdownBehavior::SKIP_ON_SHUTDOWN}); std::unique_ptr<CloudExternalDataManager> external_data_manager( new UserCloudExternalDataManager(
diff --git a/chrome/browser/chromeos/power/auto_screen_brightness/als_reader_impl.cc b/chrome/browser/chromeos/power/auto_screen_brightness/als_reader_impl.cc index fa270185..0ee3f42 100644 --- a/chrome/browser/chromeos/power/auto_screen_brightness/als_reader_impl.cc +++ b/chrome/browser/chromeos/power/auto_screen_brightness/als_reader_impl.cc
@@ -85,8 +85,9 @@ constexpr base::TimeDelta AlsReaderImpl::kAlsPollInterval; AlsReaderImpl::AlsReaderImpl() - : blocking_task_runner_(base::CreateSequencedTaskRunnerWithTraits( - {base::TaskPriority::BEST_EFFORT, base::MayBlock(), + : blocking_task_runner_(base::CreateSequencedTaskRunner( + {base::ThreadPool(), base::TaskPriority::BEST_EFFORT, + base::MayBlock(), base::TaskShutdownBehavior::CONTINUE_ON_SHUTDOWN})), weak_ptr_factory_(this) {}
diff --git a/chrome/browser/chromeos/power/auto_screen_brightness/model_config_loader_impl.cc b/chrome/browser/chromeos/power/auto_screen_brightness/model_config_loader_impl.cc index 3fa5587..96e1c22 100644 --- a/chrome/browser/chromeos/power/auto_screen_brightness/model_config_loader_impl.cc +++ b/chrome/browser/chromeos/power/auto_screen_brightness/model_config_loader_impl.cc
@@ -90,8 +90,9 @@ : ModelConfigLoaderImpl( base::FilePath( "/usr/share/chromeos-assets/autobrightness/model_params.json"), - base::CreateSequencedTaskRunnerWithTraits( - {base::TaskPriority::USER_VISIBLE, base::MayBlock(), + base::CreateSequencedTaskRunner( + {base::ThreadPool(), base::TaskPriority::USER_VISIBLE, + base::MayBlock(), base::TaskShutdownBehavior::CONTINUE_ON_SHUTDOWN}), false /* is_testing */) {}
diff --git a/chrome/browser/chromeos/power/auto_screen_brightness/modeller_impl.cc b/chrome/browser/chromeos/power/auto_screen_brightness/modeller_impl.cc index d50a4b6..3a47aeaf 100644 --- a/chrome/browser/chromeos/power/auto_screen_brightness/modeller_impl.cc +++ b/chrome/browser/chromeos/power/auto_screen_brightness/modeller_impl.cc
@@ -202,8 +202,9 @@ model_config_loader, user_activity_detector, std::move(trainer), - base::CreateSequencedTaskRunnerWithTraits( - {base::TaskPriority::BEST_EFFORT, base::MayBlock(), + base::CreateSequencedTaskRunner( + {base::ThreadPool(), base::TaskPriority::BEST_EFFORT, + base::MayBlock(), base::TaskShutdownBehavior::CONTINUE_ON_SHUTDOWN}), base::DefaultTickClock::GetInstance()) {}
diff --git a/chrome/browser/chromeos/power/cpu_data_collector.cc b/chrome/browser/chromeos/power/cpu_data_collector.cc index 558eaa9..5dc8bfd 100644 --- a/chrome/browser/chromeos/power/cpu_data_collector.cc +++ b/chrome/browser/chromeos/power/cpu_data_collector.cc
@@ -457,8 +457,9 @@ std::vector<StateOccupancySample>* freq_samples = new std::vector<StateOccupancySample>; - base::PostTaskWithTraitsAndReply( - FROM_HERE, {base::MayBlock(), base::TaskPriority::BEST_EFFORT}, + base::PostTaskAndReply( + FROM_HERE, + {base::ThreadPool(), base::MayBlock(), base::TaskPriority::BEST_EFFORT}, base::Bind(&SampleCpuStateAsync, base::Unretained(cpu_count), base::Unretained(cpu_idle_state_names), base::Unretained(idle_samples),
diff --git a/chrome/browser/chromeos/power/freezer_cgroup_process_manager.cc b/chrome/browser/chromeos/power/freezer_cgroup_process_manager.cc index cbf3c8c..8b2b7ea1 100644 --- a/chrome/browser/chromeos/power/freezer_cgroup_process_manager.cc +++ b/chrome/browser/chromeos/power/freezer_cgroup_process_manager.cc
@@ -35,8 +35,8 @@ public: // Called on UI thread. explicit FileWorker(scoped_refptr<base::SequencedTaskRunner> file_thread) - : ui_thread_(base::CreateSingleThreadTaskRunnerWithTraits( - {content::BrowserThread::UI})), + : ui_thread_( + base::CreateSingleThreadTaskRunner({content::BrowserThread::UI})), file_thread_(file_thread), enabled_(false), froze_successfully_(false) { @@ -157,8 +157,9 @@ }; FreezerCgroupProcessManager::FreezerCgroupProcessManager() - : file_thread_(base::CreateSequencedTaskRunnerWithTraits( - {base::TaskPriority::BEST_EFFORT, base::MayBlock()})), + : file_thread_(base::CreateSequencedTaskRunner( + {base::ThreadPool(), base::TaskPriority::BEST_EFFORT, + base::MayBlock()})), file_worker_(new FileWorker(file_thread_)) { file_thread_->PostTask( FROM_HERE,
diff --git a/chrome/browser/chromeos/power/process_data_collector.cc b/chrome/browser/chromeos/power/process_data_collector.cc index 0366d06..d1e997b 100644 --- a/chrome/browser/chromeos/power/process_data_collector.cc +++ b/chrome/browser/chromeos/power/process_data_collector.cc
@@ -346,8 +346,8 @@ ProcessDataCollector::~ProcessDataCollector() = default; void ProcessDataCollector::StartSamplingCpuUsage() { - cpu_data_task_runner_ = base::CreateSequencedTaskRunnerWithTraits( - {base::MayBlock(), base::TaskPriority::BEST_EFFORT}); + cpu_data_task_runner_ = base::CreateSequencedTaskRunner( + {base::ThreadPool(), base::MayBlock(), base::TaskPriority::BEST_EFFORT}); cpu_data_timer_.Start(FROM_HERE, config_.sample_delay, this, &ProcessDataCollector::SampleCpuUsage); }
diff --git a/chrome/browser/chromeos/printing/bulk_printers_calculator.cc b/chrome/browser/chromeos/printing/bulk_printers_calculator.cc index 0d17cc74..04b37ec16 100644 --- a/chrome/browser/chromeos/printing/bulk_printers_calculator.cc +++ b/chrome/browser/chromeos/printing/bulk_printers_calculator.cc
@@ -222,9 +222,9 @@ public: BulkPrintersCalculatorImpl() : restrictions_(base::MakeRefCounted<Restrictions>()), - restrictions_runner_(base::CreateSequencedTaskRunnerWithTraits( - {base::TaskPriority::BEST_EFFORT, base::MayBlock(), - base::TaskShutdownBehavior::SKIP_ON_SHUTDOWN})), + restrictions_runner_(base::CreateSequencedTaskRunner( + {base::ThreadPool(), base::TaskPriority::BEST_EFFORT, + base::MayBlock(), base::TaskShutdownBehavior::SKIP_ON_SHUTDOWN})), weak_ptr_factory_(this) {} void AddObserver(Observer* observer) override {
diff --git a/chrome/browser/chromeos/printing/cups_print_job_manager_impl.cc b/chrome/browser/chromeos/printing/cups_print_job_manager_impl.cc index feb2a08..c60aa080 100644 --- a/chrome/browser/chromeos/printing/cups_print_job_manager_impl.cc +++ b/chrome/browser/chromeos/printing/cups_print_job_manager_impl.cc
@@ -259,15 +259,14 @@ public: explicit CupsPrintJobManagerImpl(Profile* profile) : CupsPrintJobManager(profile), - query_runner_(base::CreateSequencedTaskRunnerWithTraits( - base::TaskTraits(base::TaskPriority::BEST_EFFORT, - base::MayBlock(), - base::TaskShutdownBehavior::SKIP_ON_SHUTDOWN))), + query_runner_(base::CreateSequencedTaskRunner(base::TaskTraits{ + base::ThreadPool(), base::TaskPriority::BEST_EFFORT, + base::MayBlock(), base::TaskShutdownBehavior::SKIP_ON_SHUTDOWN})), cups_wrapper_(new CupsWrapper(), base::OnTaskRunnerDeleter(query_runner_)), weak_ptr_factory_(this) { - timer_.SetTaskRunner(base::CreateSingleThreadTaskRunnerWithTraits( - {content::BrowserThread::UI})); + timer_.SetTaskRunner( + base::CreateSingleThreadTaskRunner({content::BrowserThread::UI})); registrar_.Add(this, chrome::NOTIFICATION_PRINT_JOB_EVENT, content::NotificationService::AllSources()); } @@ -352,7 +351,7 @@ NotifyJobUpdated(job->GetWeakPtr()); // Run a query now. - base::CreateSingleThreadTaskRunnerWithTraits({content::BrowserThread::UI}) + base::CreateSingleThreadTaskRunner({content::BrowserThread::UI}) ->PostTask(FROM_HERE, base::BindOnce(&CupsPrintJobManagerImpl::PostQuery, weak_ptr_factory_.GetWeakPtr()));
diff --git a/chrome/browser/chromeos/printing/cups_proxy_service_delegate_impl.cc b/chrome/browser/chromeos/printing/cups_proxy_service_delegate_impl.cc index e8c16a3..2672d42b0 100644 --- a/chrome/browser/chromeos/printing/cups_proxy_service_delegate_impl.cc +++ b/chrome/browser/chromeos/printing/cups_proxy_service_delegate_impl.cc
@@ -57,7 +57,7 @@ // Grab current runner to post |cb| to. auto cb_runner = base::SequencedTaskRunnerHandle::Get(); - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {content::BrowserThread::UI}, base::BindOnce(&CupsProxyServiceDelegateImpl::SetupPrinterOnThread, weak_factory_.GetWeakPtr(), printer,
diff --git a/chrome/browser/chromeos/printing/print_servers_provider.cc b/chrome/browser/chromeos/printing/print_servers_provider.cc index 5520720c..6ffe22f6 100644 --- a/chrome/browser/chromeos/printing/print_servers_provider.cc +++ b/chrome/browser/chromeos/printing/print_servers_provider.cc
@@ -135,9 +135,9 @@ class PrintServersProviderImpl : public PrintServersProvider { public: PrintServersProviderImpl() - : task_runner_(base::CreateSequencedTaskRunnerWithTraits( - {base::TaskPriority::BEST_EFFORT, base::MayBlock(), - base::TaskShutdownBehavior::SKIP_ON_SHUTDOWN})), + : task_runner_(base::CreateSequencedTaskRunner( + {base::ThreadPool(), base::TaskPriority::BEST_EFFORT, + base::MayBlock(), base::TaskShutdownBehavior::SKIP_ON_SHUTDOWN})), weak_ptr_factory_(this) { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); }
diff --git a/chrome/browser/chromeos/printing/printer_info_cups.cc b/chrome/browser/chromeos/printing/printer_info_cups.cc index 2b9a6178..050e858 100644 --- a/chrome/browser/chromeos/printing/printer_info_cups.cc +++ b/chrome/browser/chromeos/printing/printer_info_cups.cc
@@ -144,9 +144,10 @@ // QueryPrinterImpl could block on a network call for a noticable amount of // time (100s of ms). Also the user is waiting on this result. Thus, run at // USER_VISIBLE with MayBlock. - base::PostTaskWithTraitsAndReplyWithResult( + base::PostTaskAndReplyWithResult( FROM_HERE, - base::TaskTraits(base::TaskPriority::USER_VISIBLE, base::MayBlock()), + base::TaskTraits{base::ThreadPool(), base::TaskPriority::USER_VISIBLE, + base::MayBlock()}, base::BindOnce(&QueryPrinterImpl, host, port, path, encrypted), base::BindOnce(&OnPrinterQueried, std::move(callback))); }
diff --git a/chrome/browser/chromeos/proxy_config_service_impl_unittest.cc b/chrome/browser/chromeos/proxy_config_service_impl_unittest.cc index 7507aa4..219d931 100644 --- a/chrome/browser/chromeos/proxy_config_service_impl_unittest.cc +++ b/chrome/browser/chromeos/proxy_config_service_impl_unittest.cc
@@ -276,7 +276,7 @@ void SetUpProxyConfigService(PrefService* profile_prefs) { config_service_impl_.reset(new ProxyConfigServiceImpl( profile_prefs, &pref_service_, - base::CreateSingleThreadTaskRunnerWithTraits({BrowserThread::IO}))); + base::CreateSingleThreadTaskRunner({BrowserThread::IO}))); proxy_config_service_ = config_service_impl_->CreateTrackingProxyConfigService( std::unique_ptr<net::ProxyConfigService>());
diff --git a/chrome/browser/chromeos/settings/session_manager_operation.cc b/chrome/browser/chromeos/settings/session_manager_operation.cc index da2ca784..5fc3809 100644 --- a/chrome/browser/chromeos/settings/session_manager_operation.cc +++ b/chrome/browser/chromeos/settings/session_manager_operation.cc
@@ -89,9 +89,9 @@ void SessionManagerOperation::EnsurePublicKey(const base::Closure& callback) { if (force_key_load_ || !public_key_ || !public_key_->is_loaded()) { - base::PostTaskWithTraitsAndReplyWithResult( + base::PostTaskAndReplyWithResult( FROM_HERE, - {base::MayBlock(), base::TaskPriority::BEST_EFFORT, + {base::ThreadPool(), base::MayBlock(), base::TaskPriority::BEST_EFFORT, base::TaskShutdownBehavior::SKIP_ON_SHUTDOWN}, base::BindOnce(&SessionManagerOperation::LoadPublicKey, owner_key_util_, force_key_load_ ? nullptr : public_key_), @@ -162,8 +162,9 @@ } scoped_refptr<base::SequencedTaskRunner> background_task_runner = - base::CreateSequencedTaskRunnerWithTraits( - {base::MayBlock(), base::TaskPriority::USER_BLOCKING, + base::CreateSequencedTaskRunner( + {base::ThreadPool(), base::MayBlock(), + base::TaskPriority::USER_BLOCKING, base::TaskShutdownBehavior::SKIP_ON_SHUTDOWN}); std::unique_ptr<policy::DeviceCloudPolicyValidator> validator =
diff --git a/chrome/browser/chromeos/smb_client/discovery/mdns_host_locator.cc b/chrome/browser/chromeos/smb_client/discovery/mdns_host_locator.cc index 7ad6bc0..c8348bcc 100644 --- a/chrome/browser/chromeos/smb_client/discovery/mdns_host_locator.cc +++ b/chrome/browser/chromeos/smb_client/discovery/mdns_host_locator.cc
@@ -123,8 +123,8 @@ }; MDnsHostLocator::MDnsHostLocator() - : io_task_runner_(base::CreateSingleThreadTaskRunnerWithTraits( - {content::BrowserThread::IO})), + : io_task_runner_( + base::CreateSingleThreadTaskRunner({content::BrowserThread::IO})), impl_(nullptr, base::OnTaskRunnerDeleter(io_task_runner_)), weak_factory_(this) {}
diff --git a/chrome/browser/chromeos/smb_client/smb_file_system.cc b/chrome/browser/chromeos/smb_client/smb_file_system.cc index 32bfffd7..3c01855a 100644 --- a/chrome/browser/chromeos/smb_client/smb_file_system.cc +++ b/chrome/browser/chromeos/smb_client/smb_file_system.cc
@@ -446,14 +446,14 @@ void SmbFileSystem::CreateTempFileManagerAndExecuteTask(SmbTask task) { // CreateTempFileManager() has to be called on a separate thread since it // contains a call that requires a blockable thread. - base::TaskTraits task_traits = {base::MayBlock(), + base::TaskTraits task_traits = {base::ThreadPool(), base::MayBlock(), base::TaskPriority::USER_BLOCKING, base::TaskShutdownBehavior::SKIP_ON_SHUTDOWN}; auto init_task = base::BindOnce(&CreateTempFileManager); auto reply = base::BindOnce(&SmbFileSystem::InitTempFileManagerAndExecuteTask, AsWeakPtr(), std::move(task)); - base::PostTaskWithTraitsAndReplyWithResult( - FROM_HERE, task_traits, std::move(init_task), std::move(reply)); + base::PostTaskAndReplyWithResult(FROM_HERE, task_traits, std::move(init_task), + std::move(reply)); } void SmbFileSystem::InitTempFileManagerAndExecuteTask(
diff --git a/chrome/browser/chromeos/smb_client/smb_service.cc b/chrome/browser/chromeos/smb_client/smb_service.cc index e4a07d3..ca2004d 100644 --- a/chrome/browser/chromeos/smb_client/smb_service.cc +++ b/chrome/browser/chromeos/smb_client/smb_service.cc
@@ -584,14 +584,14 @@ void SmbService::SetupTempFileManagerAndCompleteSetup() { // CreateTempFileManager() has to be called on a separate thread since it // contains a call that requires a blockable thread. - base::TaskTraits task_traits = {base::MayBlock(), + base::TaskTraits task_traits = {base::ThreadPool(), base::MayBlock(), base::TaskPriority::USER_BLOCKING, base::TaskShutdownBehavior::SKIP_ON_SHUTDOWN}; auto task = base::BindOnce(&CreateTempFileManager); auto reply = base::BindOnce(&SmbService::CompleteSetup, AsWeakPtr()); - base::PostTaskWithTraitsAndReplyWithResult(FROM_HERE, task_traits, - std::move(task), std::move(reply)); + base::PostTaskAndReplyWithResult(FROM_HERE, task_traits, std::move(task), + std::move(reply)); } void SmbService::OnSetupKerberosResponse(bool success) {
diff --git a/chrome/browser/chromeos/system/automatic_reboot_manager.cc b/chrome/browser/chromeos/system/automatic_reboot_manager.cc index 7dbddeb..1573dcf5 100644 --- a/chrome/browser/chromeos/system/automatic_reboot_manager.cc +++ b/chrome/browser/chromeos/system/automatic_reboot_manager.cc
@@ -170,9 +170,10 @@ OnUserActivity(nullptr); } - base::PostTaskWithTraitsAndReplyWithResult( + base::PostTaskAndReplyWithResult( FROM_HERE, - {base::TaskShutdownBehavior::SKIP_ON_SHUTDOWN, base::MayBlock()}, + {base::ThreadPool(), base::TaskShutdownBehavior::SKIP_ON_SHUTDOWN, + base::MayBlock()}, base::BindOnce(&internal::GetSystemEventTimes), base::BindOnce(&AutomaticRebootManager::Init, weak_ptr_factory_.GetWeakPtr())); @@ -218,10 +219,11 @@ return; } - base::PostTaskWithTraits(FROM_HERE, - {base::MayBlock(), base::TaskPriority::BEST_EFFORT, - base::TaskShutdownBehavior::BLOCK_SHUTDOWN}, - base::BindOnce(&SaveUpdateRebootNeededUptime)); + base::PostTask( + FROM_HERE, + {base::ThreadPool(), base::MayBlock(), base::TaskPriority::BEST_EFFORT, + base::TaskShutdownBehavior::BLOCK_SHUTDOWN}, + base::BindOnce(&SaveUpdateRebootNeededUptime)); update_reboot_needed_time_ = clock_->NowTicks();
diff --git a/chrome/browser/chromeos/system_logs/command_line_log_source.cc b/chrome/browser/chromeos/system_logs/command_line_log_source.cc index ec7fa5d..e70ce04 100644 --- a/chrome/browser/chromeos/system_logs/command_line_log_source.cc +++ b/chrome/browser/chromeos/system_logs/command_line_log_source.cc
@@ -101,8 +101,9 @@ auto response = std::make_unique<SystemLogsResponse>(); SystemLogsResponse* response_ptr = response.get(); - base::PostTaskWithTraitsAndReply( - FROM_HERE, {base::MayBlock(), base::TaskPriority::BEST_EFFORT}, + base::PostTaskAndReply( + FROM_HERE, + {base::ThreadPool(), base::MayBlock(), base::TaskPriority::BEST_EFFORT}, base::BindOnce(&ExecuteCommandLines, response_ptr), base::BindOnce(std::move(callback), std::move(response))); }
diff --git a/chrome/browser/chromeos/system_logs/debug_daemon_log_source.cc b/chrome/browser/chromeos/system_logs/debug_daemon_log_source.cc index 12056c44..7d20f73e 100644 --- a/chrome/browser/chromeos/system_logs/debug_daemon_log_source.cc +++ b/chrome/browser/chromeos/system_logs/debug_daemon_log_source.cc
@@ -154,8 +154,9 @@ auto response = std::make_unique<SystemLogsResponse>(); SystemLogsResponse* response_ptr = response.get(); - base::PostTaskWithTraitsAndReply( - FROM_HERE, {base::MayBlock(), base::TaskPriority::BEST_EFFORT}, + base::PostTaskAndReply( + FROM_HERE, + {base::ThreadPool(), base::MayBlock(), base::TaskPriority::BEST_EFFORT}, base::BindOnce(&ReadUserLogFiles, profile_dirs, response_ptr), base::BindOnce(&DebugDaemonLogSource::MergeUserLogFilesResponse, weak_ptr_factory_.GetWeakPtr(), std::move(response)));
diff --git a/chrome/browser/chromeos/system_logs/debug_log_writer.cc b/chrome/browser/chromeos/system_logs/debug_log_writer.cc index 860e903..29ee057 100644 --- a/chrome/browser/chromeos/system_logs/debug_log_writer.cc +++ b/chrome/browser/chromeos/system_logs/debug_log_writer.cc
@@ -116,7 +116,7 @@ bool compression_command_success) { if (!compression_command_success) { LOG(ERROR) << "Failed compressing " << compressed_output_path.value(); - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {content::BrowserThread::UI}, base::BindOnce(std::move(callback), base::FilePath(), false)); base::DeleteFile(tar_file_path, false); @@ -124,7 +124,7 @@ return; } - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {content::BrowserThread::UI}, base::BindOnce(std::move(callback), compressed_output_path, true)); } @@ -136,7 +136,7 @@ bool add_user_logs_command_success) { if (!add_user_logs_command_success) { LOG(ERROR) << "Failed adding user logs to " << tar_file_path.value(); - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {content::BrowserThread::UI}, base::BindOnce(std::move(callback), base::FilePath(), false)); base::DeleteFile(tar_file_path, false); @@ -182,8 +182,9 @@ base::FilePath user_log_dir = logging::GetSessionLogDir(*base::CommandLine::ForCurrentProcess()); - base::PostTaskWithTraits( - FROM_HERE, {base::MayBlock(), base::TaskPriority::BEST_EFFORT}, + base::PostTask( + FROM_HERE, + {base::ThreadPool(), base::MayBlock(), base::TaskPriority::BEST_EFFORT}, base::BindOnce(&AddUserLogsToArchive, user_log_dir, tar_file_path, compressed_output_path, std::move(callback))); }
diff --git a/chrome/browser/chromeos/system_logs/iwlwifi_dump_log_source.cc b/chrome/browser/chromeos/system_logs/iwlwifi_dump_log_source.cc index e8654c7..72ddc66 100644 --- a/chrome/browser/chromeos/system_logs/iwlwifi_dump_log_source.cc +++ b/chrome/browser/chromeos/system_logs/iwlwifi_dump_log_source.cc
@@ -46,9 +46,10 @@ DCHECK_CURRENTLY_ON(content::BrowserThread::UI); DCHECK(!callback.is_null()); - base::PostTaskWithTraitsAndReplyWithResult( + base::PostTaskAndReplyWithResult( FROM_HERE, - base::TaskTraits(base::MayBlock(), base::TaskPriority::BEST_EFFORT), + base::TaskTraits({base::ThreadPool(), base::MayBlock(), + base::TaskPriority::BEST_EFFORT}), base::BindOnce(&CheckExistenceOnBlockingTaskRunner), base::BindOnce(std::move(callback))); } @@ -62,9 +63,10 @@ DCHECK_CURRENTLY_ON(content::BrowserThread::UI); DCHECK(!callback.is_null()); - base::PostTaskWithTraitsAndReplyWithResult( + base::PostTaskAndReplyWithResult( FROM_HERE, - base::TaskTraits(base::MayBlock(), base::TaskPriority::BEST_EFFORT), + base::TaskTraits({base::ThreadPool(), base::MayBlock(), + base::TaskPriority::BEST_EFFORT}), base::BindOnce(&ReadDumpOnBlockingTaskRunner), base::BindOnce(std::move(callback))); }
diff --git a/chrome/browser/chromeos/system_logs/single_log_file_log_source.cc b/chrome/browser/chromeos/system_logs/single_log_file_log_source.cc index 1810875..88260bb 100644 --- a/chrome/browser/chromeos/system_logs/single_log_file_log_source.cc +++ b/chrome/browser/chromeos/system_logs/single_log_file_log_source.cc
@@ -99,9 +99,10 @@ auto response = std::make_unique<SystemLogsResponse>(); auto* response_ptr = response.get(); - base::PostTaskWithTraitsAndReply( + base::PostTaskAndReply( FROM_HERE, - base::TaskTraits(base::MayBlock(), base::TaskPriority::BEST_EFFORT), + base::TaskTraits({base::ThreadPool(), base::MayBlock(), + base::TaskPriority::BEST_EFFORT}), base::BindOnce(&SingleLogFileLogSource::ReadFile, weak_ptr_factory_.GetWeakPtr(), kMaxNumAllowedLogRotationsDuringFileRead, response_ptr),
diff --git a/chrome/browser/chromeos/system_logs/touch_log_source.cc b/chrome/browser/chromeos/system_logs/touch_log_source.cc index ba7f368..6970c7a 100644 --- a/chrome/browser/chromeos/system_logs/touch_log_source.cc +++ b/chrome/browser/chromeos/system_logs/touch_log_source.cc
@@ -126,9 +126,10 @@ } // Cleanup these temporary log files. - base::PostTaskWithTraits(FROM_HERE, - {base::MayBlock(), base::TaskPriority::BEST_EFFORT}, - base::BindOnce(CleanupEventLog, log_paths)); + base::PostTask( + FROM_HERE, + {base::ThreadPool(), base::MayBlock(), base::TaskPriority::BEST_EFFORT}, + base::BindOnce(CleanupEventLog, log_paths)); } // Callback for handing the outcome of GetTouchEventLog(). @@ -140,8 +141,9 @@ const std::vector<base::FilePath>& log_paths) { DCHECK_CURRENTLY_ON(BrowserThread::UI); system_logs::SystemLogsResponse* response_ptr = response.get(); - base::PostTaskWithTraitsAndReply( - FROM_HERE, {base::MayBlock(), base::TaskPriority::BEST_EFFORT}, + base::PostTaskAndReply( + FROM_HERE, + {base::ThreadPool(), base::MayBlock(), base::TaskPriority::BEST_EFFORT}, base::BindOnce(&PackEventLog, response_ptr, log_paths), base::BindOnce(std::move(callback), std::move(response))); }
diff --git a/chrome/browser/chromeos/tpm_firmware_update.cc b/chrome/browser/chromeos/tpm_firmware_update.cc index 905973fc..2d99c46 100644 --- a/chrome/browser/chromeos/tpm_firmware_update.cc +++ b/chrome/browser/chromeos/tpm_firmware_update.cc
@@ -117,8 +117,9 @@ // Don't call this directly, but use Start(). explicit AvailabilityChecker(ResponseCallback callback) : callback_(std::move(callback)), - background_task_runner_(base::CreateSequencedTaskRunnerWithTraits( - {base::MayBlock(), base::TaskPriority::USER_VISIBLE})), + background_task_runner_(base::CreateSequencedTaskRunner( + {base::ThreadPool(), base::MayBlock(), + base::TaskPriority::USER_VISIBLE})), watcher_(new base::FilePathWatcher()), weak_ptr_factory_(this) { auto watch_callback = base::BindRepeating(
diff --git a/chrome/browser/component_updater/component_patcher_operation_browsertest.cc b/chrome/browser/component_updater/component_patcher_operation_browsertest.cc index 5a750789..14e7fef 100644 --- a/chrome/browser/component_updater/component_patcher_operation_browsertest.cc +++ b/chrome/browser/component_updater/component_patcher_operation_browsertest.cc
@@ -28,7 +28,7 @@ namespace { constexpr base::TaskTraits kTaskTraits = { - base::MayBlock(), base::TaskPriority::BEST_EFFORT, + base::ThreadPool(), base::MayBlock(), base::TaskPriority::BEST_EFFORT, base::TaskShutdownBehavior::SKIP_ON_SHUTDOWN}; } // namespace @@ -55,7 +55,7 @@ base::FilePath path = installed_dir_.GetPath().AppendASCII(name); base::RunLoop run_loop; - base::PostTaskWithTraitsAndReply( + base::PostTaskAndReply( FROM_HERE, kTaskTraits, base::BindOnce(&PatchTest::CopyFile, TestFile(name), path), run_loop.QuitClosure()); @@ -68,7 +68,7 @@ base::FilePath path = input_dir_.GetPath().AppendASCII(name); base::RunLoop run_loop; - base::PostTaskWithTraitsAndReply( + base::PostTaskAndReply( FROM_HERE, kTaskTraits, base::BindOnce(&PatchTest::CopyFile, TestFile(name), path), run_loop.QuitClosure()); @@ -94,7 +94,7 @@ quit_closure_ = run_loop.QuitClosure(); done_called_ = false; - base::CreateSequencedTaskRunnerWithTraits(kTaskTraits) + base::CreateSequencedTaskRunner(kTaskTraits) ->PostTask(FROM_HERE, base::BindOnce(&PatchTest::PatchAsyncSequencedTaskRunner, base::Unretained(this), operation, input, @@ -118,7 +118,7 @@ void PatchDone(int expected, int result) { EXPECT_EQ(expected, result); done_called_ = true; - base::CreateSingleThreadTaskRunnerWithTraits({content::BrowserThread::UI}) + base::CreateSingleThreadTaskRunner({content::BrowserThread::UI}) ->PostTask(FROM_HERE, std::move(quit_closure_)); }
diff --git a/chrome/browser/component_updater/crl_set_component_installer.cc b/chrome/browser/component_updater/crl_set_component_installer.cc index dbcc6b4..d47e310 100644 --- a/chrome/browser/component_updater/crl_set_component_installer.cc +++ b/chrome/browser/component_updater/crl_set_component_installer.cc
@@ -79,8 +79,9 @@ if (crl_set_path_.empty()) return; - base::PostTaskWithTraitsAndReplyWithResult( - FROM_HERE, {base::TaskPriority::BEST_EFFORT, base::MayBlock()}, + base::PostTaskAndReplyWithResult( + FROM_HERE, + {base::ThreadPool(), base::TaskPriority::BEST_EFFORT, base::MayBlock()}, base::BindOnce(&LoadCRLSet, crl_set_path_), base::BindOnce(&CRLSetData::UpdateCRLSetOnUI, base::Unretained(this))); }
diff --git a/chrome/browser/component_updater/cros_component_installer_chromeos.cc b/chrome/browser/component_updater/cros_component_installer_chromeos.cc index 12998621..6c60c845 100644 --- a/chrome/browser/component_updater/cros_component_installer_chromeos.cc +++ b/chrome/browser/component_updater/cros_component_installer_chromeos.cc
@@ -152,9 +152,8 @@ void CrOSComponentInstallerPolicy::OnCustomUninstall() { cros_component_installer_->UnregisterCompatiblePath(name_); - base::PostTaskWithTraits( - FROM_HERE, {content::BrowserThread::UI}, - base::BindOnce(&FinishCustomUninstallOnUIThread, name_)); + base::PostTask(FROM_HERE, {content::BrowserThread::UI}, + base::BindOnce(&FinishCustomUninstallOnUIThread, name_)); } void CrOSComponentInstallerPolicy::ComponentReady( @@ -256,8 +255,9 @@ } void CrOSComponentInstaller::RegisterInstalled() { - base::PostTaskWithTraitsAndReplyWithResult( - FROM_HERE, {base::MayBlock()}, base::BindOnce(GetInstalled), + base::PostTaskAndReplyWithResult( + FROM_HERE, {base::ThreadPool(), base::MayBlock()}, + base::BindOnce(GetInstalled), base::BindOnce(&CrOSComponentInstaller::RegisterN, base::Unretained(this))); }
diff --git a/chrome/browser/component_updater/cros_component_installer_chromeos_unittest.cc b/chrome/browser/component_updater/cros_component_installer_chromeos_unittest.cc index 523630b..5e3bc847 100644 --- a/chrome/browser/component_updater/cros_component_installer_chromeos_unittest.cc +++ b/chrome/browser/component_updater/cros_component_installer_chromeos_unittest.cc
@@ -152,8 +152,8 @@ if (!installer) return false; - base::PostTaskWithTraits( - FROM_HERE, {base::MayBlock()}, + base::PostTask( + FROM_HERE, {base::ThreadPool(), base::MayBlock()}, base::BindOnce( &update_client::CrxInstaller::Install, installer, unpacked_path, "", base::BindOnce(&WrapInstallerCallback, std::move(callback))));
diff --git a/chrome/browser/component_updater/file_type_policies_component_installer.cc b/chrome/browser/component_updater/file_type_policies_component_installer.cc index 48f96c4..c1e18273 100644 --- a/chrome/browser/component_updater/file_type_policies_component_installer.cc +++ b/chrome/browser/component_updater/file_type_policies_component_installer.cc
@@ -89,8 +89,9 @@ VLOG(1) << "Component ready, version " << version.GetString() << " in " << install_dir.value(); - base::PostTaskWithTraits( - FROM_HERE, {base::MayBlock(), base::TaskPriority::BEST_EFFORT}, + base::PostTask( + FROM_HERE, + {base::ThreadPool(), base::MayBlock(), base::TaskPriority::BEST_EFFORT}, base::BindOnce(&LoadFileTypesFromDisk, GetInstalledPath(install_dir))); }
diff --git a/chrome/browser/component_updater/mei_preload_component_installer.cc b/chrome/browser/component_updater/mei_preload_component_installer.cc index c196676..4052572 100644 --- a/chrome/browser/component_updater/mei_preload_component_installer.cc +++ b/chrome/browser/component_updater/mei_preload_component_installer.cc
@@ -83,16 +83,16 @@ const base::FilePath& install_dir, std::unique_ptr<base::DictionaryValue> manifest) { base::TaskTraits task_traits = { - base::MayBlock(), base::TaskPriority::BEST_EFFORT, + base::ThreadPool(), base::MayBlock(), base::TaskPriority::BEST_EFFORT, base::TaskShutdownBehavior::CONTINUE_ON_SHUTDOWN}; base::OnceClosure task = base::BindOnce(&LoadPreloadedDataFromDisk, GetInstalledPath(install_dir)); if (!on_load_closure_) { - base::PostTaskWithTraits(FROM_HERE, task_traits, std::move(task)); + base::PostTask(FROM_HERE, task_traits, std::move(task)); } else { - base::PostTaskWithTraitsAndReply(FROM_HERE, task_traits, std::move(task), - std::move(on_load_closure_)); + base::PostTaskAndReply(FROM_HERE, task_traits, std::move(task), + std::move(on_load_closure_)); } }
diff --git a/chrome/browser/component_updater/pepper_flash_component_installer.cc b/chrome/browser/component_updater/pepper_flash_component_installer.cc index 35c38d6..9528584 100644 --- a/chrome/browser/component_updater/pepper_flash_component_installer.cc +++ b/chrome/browser/component_updater/pepper_flash_component_installer.cc
@@ -291,7 +291,7 @@ } #if defined(OS_CHROMEOS) - base::CreateSingleThreadTaskRunnerWithTraits({content::BrowserThread::UI}) + base::CreateSingleThreadTaskRunner({content::BrowserThread::UI}) ->PostTask(FROM_HERE, base::BindOnce(&ImageLoaderRegistration, version, install_dir)); #elif defined(OS_LINUX) @@ -319,9 +319,10 @@ // Flash version, so we do not do this. RegisterPepperFlashWithChrome(path.Append(chrome::kPepperFlashPluginFilename), version); - base::PostTaskWithTraits(FROM_HERE, - {base::TaskPriority::BEST_EFFORT, base::MayBlock()}, - base::BindOnce(&UpdatePathService, path)); + base::PostTask( + FROM_HERE, + {base::ThreadPool(), base::TaskPriority::BEST_EFFORT, base::MayBlock()}, + base::BindOnce(&UpdatePathService, path)); #endif // !defined(OS_LINUX) }
diff --git a/chrome/browser/component_updater/pnacl_component_installer.cc b/chrome/browser/component_updater/pnacl_component_installer.cc index fe8134b8f..731eba2 100644 --- a/chrome/browser/component_updater/pnacl_component_installer.cc +++ b/chrome/browser/component_updater/pnacl_component_installer.cc
@@ -226,8 +226,9 @@ const base::FilePath& install_dir, std::unique_ptr<base::DictionaryValue> manifest) { CheckVersionCompatiblity(version); - base::PostTaskWithTraits( - FROM_HERE, {base::TaskPriority::BEST_EFFORT, base::MayBlock()}, + base::PostTask( + FROM_HERE, + {base::ThreadPool(), base::TaskPriority::BEST_EFFORT, base::MayBlock()}, base::BindOnce(&OverrideDirPnaclComponent, install_dir)); }
diff --git a/chrome/browser/component_updater/recovery_component_installer.cc b/chrome/browser/component_updater/recovery_component_installer.cc index 22980638..4f141e4 100644 --- a/chrome/browser/component_updater/recovery_component_installer.cc +++ b/chrome/browser/component_updater/recovery_component_installer.cc
@@ -232,18 +232,18 @@ base::Process process = base::Process::Open(pid); #endif // This task joins a process, hence .WithBaseSyncPrimitives(). - base::PostTaskWithTraits( - FROM_HERE, - {base::WithBaseSyncPrimitives(), base::TaskPriority::BEST_EFFORT, - base::TaskShutdownBehavior::CONTINUE_ON_SHUTDOWN}, - base::BindOnce(&WaitForElevatedInstallToComplete, - base::Passed(&process))); + base::PostTask(FROM_HERE, + {base::ThreadPool(), base::WithBaseSyncPrimitives(), + base::TaskPriority::BEST_EFFORT, + base::TaskShutdownBehavior::CONTINUE_ON_SHUTDOWN}, + base::BindOnce(&WaitForElevatedInstallToComplete, + base::Passed(&process))); } void ElevatedInstallRecoveryComponent(const base::FilePath& installer_path) { - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, - {base::MayBlock(), base::TaskPriority::BEST_EFFORT, + {base::ThreadPool(), base::MayBlock(), base::TaskPriority::BEST_EFFORT, base::TaskShutdownBehavior::CONTINUE_ON_SHUTDOWN}, base::BindOnce(&DoElevatedInstallRecoveryComponent, installer_path)); } @@ -346,10 +346,9 @@ if (installer_exit_code == EXIT_CODE_ELEVATION_NEEDED) { RecordRecoveryComponentUMAEvent(RCE_ELEVATION_NEEDED); - base::PostTaskWithTraits( - FROM_HERE, {BrowserThread::UI}, - base::BindOnce(&SetPrefsForElevatedRecoveryInstall, installer_folder, - prefs)); + base::PostTask(FROM_HERE, {BrowserThread::UI}, + base::BindOnce(&SetPrefsForElevatedRecoveryInstall, + installer_folder, prefs)); } else if (installer_exit_code == EXIT_CODE_RECOVERY_SUCCEEDED) { RecordRecoveryComponentUMAEvent(RCE_SUCCEEDED); } else if (installer_exit_code == EXIT_CODE_RECOVERY_SKIPPED) { @@ -375,9 +374,10 @@ // Let worker pool thread wait for us so we don't block Chrome shutdown. // This task joins a process, hence .WithBaseSyncPrimitives(). - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, - {base::WithBaseSyncPrimitives(), base::TaskPriority::BEST_EFFORT, + {base::ThreadPool(), base::WithBaseSyncPrimitives(), + base::TaskPriority::BEST_EFFORT, base::TaskShutdownBehavior::CONTINUE_ON_SHUTDOWN}, base::BindOnce(&WaitForInstallToComplete, base::Passed(&process), installer_folder, prefs_)); @@ -470,7 +470,7 @@ current_version_ = version; if (prefs_) { - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {BrowserThread::UI}, base::BindOnce(&RecoveryUpdateVersionHelper, version, prefs_)); } @@ -495,17 +495,15 @@ #if defined(GOOGLE_CHROME_BUILD) #if defined(OS_WIN) || defined(OS_MACOSX) if (SimulatingElevatedRecovery()) { - base::PostTaskWithTraits( - FROM_HERE, {BrowserThread::UI}, - base::BindOnce(&SimulateElevatedRecoveryHelper, prefs)); + base::PostTask(FROM_HERE, {BrowserThread::UI}, + base::BindOnce(&SimulateElevatedRecoveryHelper, prefs)); } // We delay execute the registration because we are not required in // the critical path during browser startup. - base::PostDelayedTaskWithTraits( - FROM_HERE, {BrowserThread::UI}, - base::BindOnce(&RecoveryRegisterHelper, cus, prefs), - base::TimeDelta::FromSeconds(6)); + base::PostDelayedTask(FROM_HERE, {BrowserThread::UI}, + base::BindOnce(&RecoveryRegisterHelper, cus, prefs), + base::TimeDelta::FromSeconds(6)); #endif #endif }
diff --git a/chrome/browser/component_updater/safety_tips_component_installer.cc b/chrome/browser/component_updater/safety_tips_component_installer.cc index 2b98359..aa45151 100644 --- a/chrome/browser/component_updater/safety_tips_component_installer.cc +++ b/chrome/browser/component_updater/safety_tips_component_installer.cc
@@ -97,8 +97,9 @@ // The default proto will always be a placeholder since the updated versions // are not checked in to the repo. Simply load whatever the component updater // gave us without checking the default proto from the resource bundle. - base::PostTaskWithTraitsAndReplyWithResult( - FROM_HERE, {base::MayBlock(), base::TaskPriority::BEST_EFFORT}, + base::PostTaskAndReplyWithResult( + FROM_HERE, + {base::ThreadPool(), base::MayBlock(), base::TaskPriority::BEST_EFFORT}, base::BindOnce(&LoadSafetyTipsProtoFromDisk, pb_path), base::BindOnce(&safety_tips::SetProto)); }
diff --git a/chrome/browser/component_updater/ssl_error_assistant_component_installer.cc b/chrome/browser/component_updater/ssl_error_assistant_component_installer.cc index fe3d6b53..018be7c 100644 --- a/chrome/browser/component_updater/ssl_error_assistant_component_installer.cc +++ b/chrome/browser/component_updater/ssl_error_assistant_component_installer.cc
@@ -58,7 +58,7 @@ proto = std::move(default_proto); } - base::CreateSingleThreadTaskRunnerWithTraits({content::BrowserThread::UI}) + base::CreateSingleThreadTaskRunner({content::BrowserThread::UI}) ->PostTask(FROM_HERE, base::BindOnce(&SSLErrorHandler::SetErrorAssistantProto, std::move(proto))); @@ -99,8 +99,9 @@ DVLOG(1) << "Component ready, version " << version.GetString() << " in " << install_dir.value(); - base::PostTaskWithTraits( - FROM_HERE, {base::MayBlock(), base::TaskPriority::BEST_EFFORT}, + base::PostTask( + FROM_HERE, + {base::ThreadPool(), base::MayBlock(), base::TaskPriority::BEST_EFFORT}, base::BindOnce(&LoadProtoFromDisk, GetInstalledPath(install_dir))); }
diff --git a/chrome/browser/component_updater/sth_set_component_remover.cc b/chrome/browser/component_updater/sth_set_component_remover.cc index 2e3791c..3f6283f 100644 --- a/chrome/browser/component_updater/sth_set_component_remover.cc +++ b/chrome/browser/component_updater/sth_set_component_remover.cc
@@ -42,8 +42,9 @@ } // namespace void DeleteLegacySTHSet(const base::FilePath& user_data_dir) { - base::PostTaskWithTraits( - FROM_HERE, {base::TaskPriority::BEST_EFFORT, base::MayBlock()}, + base::PostTask( + FROM_HERE, + {base::ThreadPool(), base::TaskPriority::BEST_EFFORT, base::MayBlock()}, base::BindOnce(&CleanupOnWorker, user_data_dir.Append(FILE_PATH_LITERAL( "CertificateTransparency")))); }
diff --git a/chrome/browser/component_updater/supervised_user_whitelist_installer.cc b/chrome/browser/component_updater/supervised_user_whitelist_installer.cc index a58d0161..c6ab4e3 100644 --- a/chrome/browser/component_updater/supervised_user_whitelist_installer.cc +++ b/chrome/browser/component_updater/supervised_user_whitelist_installer.cc
@@ -68,7 +68,7 @@ const char kExtensionLargeIcon[] = "128"; constexpr base::TaskTraits kTaskTraits = { - base::MayBlock(), base::TaskPriority::BEST_EFFORT, + base::ThreadPool(), base::MayBlock(), base::TaskPriority::BEST_EFFORT, base::TaskShutdownBehavior::SKIP_ON_SHUTDOWN}; base::string16 GetWhitelistTitle(const base::DictionaryValue& manifest) { @@ -122,7 +122,7 @@ } void RecordUncleanUninstall() { - base::CreateSingleThreadTaskRunnerWithTraits({content::BrowserThread::UI}) + base::CreateSingleThreadTaskRunner({content::BrowserThread::UI}) ->PostTask( FROM_HERE, base::BindOnce(&base::RecordAction, @@ -403,7 +403,7 @@ observer_; scoped_refptr<base::SequencedTaskRunner> sequenced_task_runner_ = - base::CreateSequencedTaskRunnerWithTraits(kTaskTraits); + base::CreateSequencedTaskRunner(kTaskTraits); base::WeakPtrFactory<SupervisedUserWhitelistInstallerImpl> weak_ptr_factory_{ this}; @@ -476,7 +476,7 @@ const base::FilePath& large_icon_path, const base::FilePath& whitelist_path) { // TODO(sorin): avoid using a single thread task runner crbug.com/744718. - auto task_runner = base::CreateSingleThreadTaskRunnerWithTraits( + auto task_runner = base::CreateSingleThreadTaskRunner( kTaskTraits, base::SingleThreadTaskRunnerThreadMode::SHARED); task_runner->PostTask( FROM_HERE,
diff --git a/chrome/browser/component_updater/sw_reporter_installer_win.cc b/chrome/browser/component_updater/sw_reporter_installer_win.cc index 7bbc4a0..21ec393 100644 --- a/chrome/browser/component_updater/sw_reporter_installer_win.cc +++ b/chrome/browser/component_updater/sw_reporter_installer_win.cc
@@ -415,7 +415,7 @@ // Once the component is ready and browser startup is complete, run // |safe_browsing::OnSwReporterReady|. auto lambda = [](safe_browsing::SwReporterInvocationSequence&& invocations) { - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {content::BrowserThread::UI, base::TaskPriority::BEST_EFFORT}, base::BindOnce(
diff --git a/chrome/browser/component_updater/widevine_cdm_component_installer.cc b/chrome/browser/component_updater/widevine_cdm_component_installer.cc index f554dade..1976e71 100644 --- a/chrome/browser/component_updater/widevine_cdm_component_installer.cc +++ b/chrome/browser/component_updater/widevine_cdm_component_installer.cc
@@ -464,8 +464,9 @@ // Widevine CDM affects encrypted media playback, hence USER_VISIBLE. // See http://crbug.com/900169 for the context. - base::PostTaskWithTraits( - FROM_HERE, {base::MayBlock(), base::TaskPriority::USER_VISIBLE}, + base::PostTask( + FROM_HERE, + {base::ThreadPool(), base::MayBlock(), base::TaskPriority::USER_VISIBLE}, base::BindOnce(&WidevineCdmComponentInstallerPolicy::UpdateCdmPath, base::Unretained(this), version, path, base::Passed(&manifest))); @@ -523,7 +524,7 @@ return; } - base::CreateSingleThreadTaskRunnerWithTraits({content::BrowserThread::UI}) + base::CreateSingleThreadTaskRunner({content::BrowserThread::UI}) ->PostTask( FROM_HERE, base::BindOnce(&RegisterWidevineCdmWithChrome, cdm_version,
diff --git a/chrome/browser/extensions/api/bookmarks/bookmarks_api.cc b/chrome/browser/extensions/api/bookmarks/bookmarks_api.cc index 3ee9269..12113c4f 100644 --- a/chrome/browser/extensions/api/bookmarks/bookmarks_api.cc +++ b/chrome/browser/extensions/api/bookmarks/bookmarks_api.cc
@@ -794,9 +794,9 @@ // extensions use user gesture for export, so use USER_VISIBLE priority. // GetDefaultFilepathForBookmarkExport() might have to touch filesystem // (stat or access, for example), so this requires IO. - base::PostTaskWithTraitsAndReplyWithResult( + base::PostTaskAndReplyWithResult( FROM_HERE, - {base::MayBlock(), base::TaskPriority::USER_VISIBLE, + {base::ThreadPool(), base::MayBlock(), base::TaskPriority::USER_VISIBLE, base::TaskShutdownBehavior::SKIP_ON_SHUTDOWN}, base::BindOnce(&GetDefaultFilepathForBookmarkExport), base::BindOnce(&BookmarksIOFunction::ShowSelectFileDialog, this,
diff --git a/chrome/browser/extensions/api/braille_display_private/braille_controller_brlapi.cc b/chrome/browser/extensions/api/braille_display_private/braille_controller_brlapi.cc index d222c335..09b44ef1 100644 --- a/chrome/browser/extensions/api/braille_display_private/braille_controller_brlapi.cc +++ b/chrome/browser/extensions/api/braille_display_private/braille_controller_brlapi.cc
@@ -134,10 +134,9 @@ void BrailleControllerImpl::AddObserver(BrailleObserver* observer) { DCHECK_CURRENTLY_ON(BrowserThread::UI); - if (!base::PostTaskWithTraits( - FROM_HERE, {BrowserThread::IO}, - base::BindOnce(&BrailleControllerImpl::StartConnecting, - base::Unretained(this)))) { + if (!base::PostTask(FROM_HERE, {BrowserThread::IO}, + base::BindOnce(&BrailleControllerImpl::StartConnecting, + base::Unretained(this)))) { NOTREACHED(); } observers_.AddObserver(observer); @@ -174,8 +173,9 @@ } if (!sequenced_task_runner_) { - sequenced_task_runner_ = base::CreateSequencedTaskRunnerWithTraits( - {base::MayBlock(), base::TaskPriority::USER_VISIBLE}); + sequenced_task_runner_ = + base::CreateSequencedTaskRunner({base::ThreadPool(), base::MayBlock(), + base::TaskPriority::USER_VISIBLE}); } // Only try to connect after we've started to watch the @@ -213,7 +213,7 @@ LOG(ERROR) << "Error watching brlapi directory: " << path.value(); return; } - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {BrowserThread::IO}, base::BindOnce(&BrailleControllerImpl::OnSocketDirChangedOnIOThread, base::Unretained(this))); @@ -272,11 +272,10 @@ } VLOG(1) << "Scheduling connection retry to brlapi"; connect_scheduled_ = true; - base::PostDelayedTaskWithTraits( - FROM_HERE, {BrowserThread::IO}, - base::BindOnce(&BrailleControllerImpl::TryToConnect, - base::Unretained(this)), - kConnectionDelay); + base::PostDelayedTask(FROM_HERE, {BrowserThread::IO}, + base::BindOnce(&BrailleControllerImpl::TryToConnect, + base::Unretained(this)), + kConnectionDelay); } void BrailleControllerImpl::Disconnect() { @@ -318,7 +317,7 @@ void BrailleControllerImpl::DispatchKeyEvent(std::unique_ptr<KeyEvent> event) { if (!BrowserThread::CurrentlyOn(BrowserThread::UI)) { - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {BrowserThread::UI}, base::BindOnce(&BrailleControllerImpl::DispatchKeyEvent, base::Unretained(this), base::Passed(&event))); @@ -332,7 +331,7 @@ void BrailleControllerImpl::DispatchOnDisplayStateChanged( std::unique_ptr<DisplayState> new_state) { if (!BrowserThread::CurrentlyOn(BrowserThread::UI)) { - if (!base::PostTaskWithTraits( + if (!base::PostTask( FROM_HERE, {BrowserThread::UI}, base::BindOnce( &BrailleControllerImpl::DispatchOnDisplayStateChanged,
diff --git a/chrome/browser/extensions/api/braille_display_private/braille_display_private_apitest.cc b/chrome/browser/extensions/api/braille_display_private/braille_display_private_apitest.cc index e9efd7d..037d634 100644 --- a/chrome/browser/extensions/api/braille_display_private/braille_display_private_apitest.cc +++ b/chrome/browser/extensions/api/braille_display_private/braille_display_private_apitest.cc
@@ -68,10 +68,9 @@ data_->connected = true; on_data_ready_ = on_data_ready; if (!data_->pending_keys.empty()) { - base::PostTaskWithTraits( - FROM_HERE, {content::BrowserThread::IO}, - base::BindOnce(&MockBrlapiConnection::NotifyDataReady, - base::Unretained(this))); + base::PostTask(FROM_HERE, {content::BrowserThread::IO}, + base::BindOnce(&MockBrlapiConnection::NotifyDataReady, + base::Unretained(this))); } return CONNECT_SUCCESS; } @@ -80,7 +79,7 @@ data_->connected = false; if (data_->reappear_on_disconnect) { data_->display_columns *= 2; - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {content::BrowserThread::IO}, base::BindOnce( &BrailleControllerImpl::PokeSocketDirForTesting, @@ -129,10 +128,9 @@ void NotifyDataReady() { on_data_ready_.Run(); if (!data_->pending_keys.empty()) { - base::PostTaskWithTraits( - FROM_HERE, {content::BrowserThread::IO}, - base::BindOnce(&MockBrlapiConnection::NotifyDataReady, - base::Unretained(this))); + base::PostTask(FROM_HERE, {content::BrowserThread::IO}, + base::BindOnce(&MockBrlapiConnection::NotifyDataReady, + base::Unretained(this))); } }
diff --git a/chrome/browser/extensions/api/browsing_data/browsing_data_api.cc b/chrome/browser/extensions/api/browsing_data/browsing_data_api.cc index cd22764..e73cd3f3 100644 --- a/chrome/browser/extensions/api/browsing_data/browsing_data_api.cc +++ b/chrome/browser/extensions/api/browsing_data/browsing_data_api.cc
@@ -351,13 +351,13 @@ ChromeBrowsingDataRemoverDelegate::DATA_TYPE_PLUGIN_DATA) { // If we're being asked to remove plugin data, check whether it's actually // supported. - PostTaskWithTraits( - FROM_HERE, - {base::MayBlock(), base::TaskShutdownBehavior::SKIP_ON_SHUTDOWN, - base::TaskPriority::USER_VISIBLE}, - base::BindOnce( - &BrowsingDataRemoverFunction::CheckRemovingPluginDataSupported, - this, PluginPrefs::GetForProfile(GetProfile()))); + PostTask(FROM_HERE, + {base::ThreadPool(), base::MayBlock(), + base::TaskShutdownBehavior::SKIP_ON_SHUTDOWN, + base::TaskPriority::USER_VISIBLE}, + base::BindOnce( + &BrowsingDataRemoverFunction::CheckRemovingPluginDataSupported, + this, PluginPrefs::GetForProfile(GetProfile()))); } else { StartRemoving(); } @@ -377,7 +377,7 @@ if (!PluginDataRemoverHelper::IsSupported(plugin_prefs.get())) removal_mask_ &= ~ChromeBrowsingDataRemoverDelegate::DATA_TYPE_PLUGIN_DATA; - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {BrowserThread::UI}, base::BindOnce(&BrowsingDataRemoverFunction::StartRemoving, this)); }
diff --git a/chrome/browser/extensions/api/certificate_provider/certificate_provider_apitest.cc b/chrome/browser/extensions/api/certificate_provider/certificate_provider_apitest.cc index 808fad9..1611eb4a 100644 --- a/chrome/browser/extensions/api/certificate_provider/certificate_provider_apitest.cc +++ b/chrome/browser/extensions/api/certificate_provider/certificate_provider_apitest.cc
@@ -173,7 +173,7 @@ void AddFakeSignRequest() { cert_provider_service_->pin_dialog_manager()->AddSignRequestId( - extension_->id(), kFakeSignRequestId); + extension_->id(), kFakeSignRequestId, {}); } void NavigateTo(const std::string& test_page_file_name) {
diff --git a/chrome/browser/extensions/api/content_settings/content_settings_api.cc b/chrome/browser/extensions/api/content_settings/content_settings_api.cc index f245875..0f87e20f 100644 --- a/chrome/browser/extensions/api/content_settings/content_settings_api.cc +++ b/chrome/browser/extensions/api/content_settings/content_settings_api.cc
@@ -347,7 +347,7 @@ list->Append(std::move(dict)); } SetResult(std::move(list)); - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {BrowserThread::UI}, base::BindOnce( &ContentSettingsContentSettingGetResourceIdentifiersFunction::
diff --git a/chrome/browser/extensions/api/debugger/debugger_api.cc b/chrome/browser/extensions/api/debugger/debugger_api.cc index 9b092996..6c79f077 100644 --- a/chrome/browser/extensions/api/debugger/debugger_api.cc +++ b/chrome/browser/extensions/api/debugger/debugger_api.cc
@@ -668,7 +668,7 @@ bool DebuggerGetTargetsFunction::RunAsync() { content::DevToolsAgentHost::List list = DevToolsAgentHost::GetOrCreateAll(); - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {content::BrowserThread::UI}, base::BindOnce(&DebuggerGetTargetsFunction::SendTargetList, this, list)); return true;
diff --git a/chrome/browser/extensions/api/declarative/rules_registry_service_unittest.cc b/chrome/browser/extensions/api/declarative/rules_registry_service_unittest.cc index 29f627d..f25a3e5 100644 --- a/chrome/browser/extensions/api/declarative/rules_registry_service_unittest.cc +++ b/chrome/browser/extensions/api/declarative/rules_registry_service_unittest.cc
@@ -85,22 +85,22 @@ EXPECT_TRUE(registry_service.GetRulesRegistry(key, "io").get()); EXPECT_FALSE(registry_service.GetRulesRegistry(key, "foo").get()); - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {content::BrowserThread::UI}, base::BindOnce(&InsertRule, registry_service.GetRulesRegistry(key, "ui"), "ui_task")); - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {content::BrowserThread::IO}, base::BindOnce(&InsertRule, registry_service.GetRulesRegistry(key, "io"), "io_task")); - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {content::BrowserThread::UI}, base::BindOnce(&VerifyNumberOfRules, registry_service.GetRulesRegistry(key, "ui"), 1)); - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {content::BrowserThread::IO}, base::BindOnce(&VerifyNumberOfRules, registry_service.GetRulesRegistry(key, "io"), 1)); @@ -121,12 +121,12 @@ .Build(); registry_service.SimulateExtensionUninstalled(extension.get()); - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {content::BrowserThread::UI}, base::BindOnce(&VerifyNumberOfRules, registry_service.GetRulesRegistry(key, "ui"), 0)); - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {content::BrowserThread::IO}, base::BindOnce(&VerifyNumberOfRules, registry_service.GetRulesRegistry(key, "io"), 0));
diff --git a/chrome/browser/extensions/api/developer_private/developer_private_api.cc b/chrome/browser/extensions/api/developer_private/developer_private_api.cc index a923c4d2..60bb1f43 100644 --- a/chrome/browser/extensions/api/developer_private/developer_private_api.cc +++ b/chrome/browser/extensions/api/developer_private/developer_private_api.cc
@@ -176,8 +176,9 @@ // This will read the manifest and call AddFailure with the read manifest // contents. - base::PostTaskWithTraitsAndReplyWithResult( - FROM_HERE, {base::MayBlock(), base::TaskPriority::USER_BLOCKING}, + base::PostTaskAndReplyWithResult( + FROM_HERE, + {base::ThreadPool(), base::MayBlock(), base::TaskPriority::USER_BLOCKING}, base::BindOnce(&ReadFileToString, extension_path.Append(kManifestFilename)), base::BindOnce(std::move(callback), extension_path, error, line)); @@ -1472,9 +1473,10 @@ project_base_path_ = project_path; - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, - {base::MayBlock(), base::TaskShutdownBehavior::SKIP_ON_SHUTDOWN}, + {base::ThreadPool(), base::MayBlock(), + base::TaskShutdownBehavior::SKIP_ON_SHUTDOWN}, base::BindOnce( &DeveloperPrivateLoadDirectoryFunction::ClearExistingDirectoryContent, this, project_base_path_)); @@ -1498,7 +1500,7 @@ pending_copy_operations_count_ = 1; - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {content::BrowserThread::IO}, base::BindOnce( &DeveloperPrivateLoadDirectoryFunction::ReadDirectoryByFileSystemAPI, @@ -1563,7 +1565,7 @@ pending_copy_operations_count_--; if (!pending_copy_operations_count_) { - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {content::BrowserThread::UI}, base::BindOnce(&DeveloperPrivateLoadDirectoryFunction::SendResponse, this, success_)); @@ -1583,9 +1585,10 @@ return; } - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, - {base::MayBlock(), base::TaskShutdownBehavior::SKIP_ON_SHUTDOWN}, + {base::ThreadPool(), base::MayBlock(), + base::TaskShutdownBehavior::SKIP_ON_SHUTDOWN}, base::BindOnce(&DeveloperPrivateLoadDirectoryFunction::CopyFile, this, src_path, target_path)); } @@ -1605,7 +1608,7 @@ pending_copy_operations_count_--; if (!pending_copy_operations_count_) { - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {content::BrowserThread::UI}, base::BindOnce(&DeveloperPrivateLoadDirectoryFunction::Load, this)); } @@ -1710,8 +1713,9 @@ if (properties.path_suffix == kManifestFile && !properties.manifest_key) return RespondNow(Error(kManifestKeyIsRequiredError)); - base::PostTaskWithTraitsAndReplyWithResult( - FROM_HERE, {base::MayBlock(), base::TaskPriority::USER_VISIBLE}, + base::PostTaskAndReplyWithResult( + FROM_HERE, + {base::ThreadPool(), base::MayBlock(), base::TaskPriority::USER_VISIBLE}, base::Bind(&ReadFileToString, extension->path().Append(path_suffix)), base::Bind(&DeveloperPrivateRequestFileSourceFunction::Finish, this));
diff --git a/chrome/browser/extensions/api/developer_private/entry_picker.cc b/chrome/browser/extensions/api/developer_private/entry_picker.cc index f886ffd..afb404e563 100644 --- a/chrome/browser/extensions/api/developer_private/entry_picker.cc +++ b/chrome/browser/extensions/api/developer_private/entry_picker.cc
@@ -37,13 +37,13 @@ : client_(client) { if (g_skip_picker_for_test) { if (g_path_to_be_picked_for_test) { - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {content::BrowserThread::UI}, base::BindOnce(&EntryPicker::FileSelected, base::Unretained(this), *g_path_to_be_picked_for_test, 1, static_cast<void*>(nullptr))); } else { - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {content::BrowserThread::UI}, base::BindOnce(&EntryPicker::FileSelectionCanceled, base::Unretained(this), static_cast<void*>(nullptr)));
diff --git a/chrome/browser/extensions/api/downloads/downloads_api_browsertest.cc b/chrome/browser/extensions/api/downloads/downloads_api_browsertest.cc index ec08b6cc..3854457 100644 --- a/chrome/browser/extensions/api/downloads/downloads_api_browsertest.cc +++ b/chrome/browser/extensions/api/downloads/downloads_api_browsertest.cc
@@ -111,7 +111,7 @@ DownloadOpenPrompt* prompt) { EXPECT_FALSE(item->GetOpened()); // Posts a task to accept the DownloadOpenPrompt. - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {BrowserThread::UI}, base::BindOnce(&DownloadOpenPrompt::AcceptConfirmationDialogForTesting, base::Unretained(prompt))); @@ -706,10 +706,9 @@ if (expected_path_ == path && expected_icon_size_ == icon_size) { callback_ = callback; - base::PostTaskWithTraits( - FROM_HERE, {BrowserThread::UI}, - base::BindOnce(&MockIconExtractorImpl::RunCallback, - base::Unretained(this))); + base::PostTask(FROM_HERE, {BrowserThread::UI}, + base::BindOnce(&MockIconExtractorImpl::RunCallback, + base::Unretained(this))); return true; } else { return false; @@ -791,7 +790,7 @@ // Invoke the fileapi to copy it into the sandboxed filesystem. bool result = false; base::RunLoop run_loop; - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {BrowserThread::IO}, base::BindOnce(&CreateFileForTestingOnIOThread, base::Unretained(context), path, temp_file, @@ -808,7 +807,7 @@ base::File::Error error) { DCHECK_CURRENTLY_ON(BrowserThread::IO); *result = error == base::File::FILE_OK; - base::PostTaskWithTraits(FROM_HERE, {BrowserThread::UI}, quit_closure); + base::PostTask(FROM_HERE, {BrowserThread::UI}, quit_closure); } static void CreateFileForTestingOnIOThread(
diff --git a/chrome/browser/extensions/api/enterprise_platform_keys/enterprise_platform_keys_api.cc b/chrome/browser/extensions/api/enterprise_platform_keys/enterprise_platform_keys_api.cc index cc48d23d..2932c70 100644 --- a/chrome/browser/extensions/api/enterprise_platform_keys/enterprise_platform_keys_api.cc +++ b/chrome/browser/extensions/api/enterprise_platform_keys/enterprise_platform_keys_api.cc
@@ -286,7 +286,7 @@ scoped_refptr<ExtensionFunction>(this), callback, StringFromVector(params->challenge), params->register_key ? *params->register_key : false); - base::PostTaskWithTraits(FROM_HERE, {content::BrowserThread::UI}, task); + base::PostTask(FROM_HERE, {content::BrowserThread::UI}, task); return RespondLater(); } @@ -326,7 +326,7 @@ base::Bind(&EPKPChallengeUserKey::Run, base::Unretained(impl_), scoped_refptr<ExtensionFunction>(this), callback, StringFromVector(params->challenge), params->register_key); - base::PostTaskWithTraits(FROM_HERE, {content::BrowserThread::UI}, task); + base::PostTask(FROM_HERE, {content::BrowserThread::UI}, task); return RespondLater(); }
diff --git a/chrome/browser/extensions/api/enterprise_platform_keys_private/enterprise_platform_keys_private_api.cc b/chrome/browser/extensions/api/enterprise_platform_keys_private/enterprise_platform_keys_private_api.cc index 514a9e0..d46a285 100644 --- a/chrome/browser/extensions/api/enterprise_platform_keys_private/enterprise_platform_keys_private_api.cc +++ b/chrome/browser/extensions/api/enterprise_platform_keys_private/enterprise_platform_keys_private_api.cc
@@ -647,7 +647,7 @@ base::Unretained(impl_), scoped_refptr<ExtensionFunction>(this), callback, params->challenge, false); - base::PostTaskWithTraits(FROM_HERE, {content::BrowserThread::UI}, task); + base::PostTask(FROM_HERE, {content::BrowserThread::UI}, task); return RespondLater(); } @@ -690,7 +690,7 @@ base::Bind(&EPKPChallengeUserKey::DecodeAndRun, base::Unretained(impl_), scoped_refptr<ExtensionFunction>(this), callback, params->challenge, params->register_key); - base::PostTaskWithTraits(FROM_HERE, {content::BrowserThread::UI}, task); + base::PostTask(FROM_HERE, {content::BrowserThread::UI}, task); return RespondLater(); }
diff --git a/chrome/browser/extensions/api/identity/identity_get_auth_token_function.cc b/chrome/browser/extensions/api/identity/identity_get_auth_token_function.cc index 4e79acc..1de99c2 100644 --- a/chrome/browser/extensions/api/identity/identity_get_auth_token_function.cc +++ b/chrome/browser/extensions/api/identity/identity_get_auth_token_function.cc
@@ -145,14 +145,14 @@ if (gaia_id.empty() || IsPrimaryAccountOnly()) { // Try the primary account. // TODO(https://crbug.com/932400): collapse the asynchronicity - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {content::BrowserThread::UI}, base::BindOnce( &IdentityGetAuthTokenFunction::GetAuthTokenForPrimaryAccount, weak_ptr_factory_.GetWeakPtr(), gaia_id)); } else { // Get the AccountInfo for the account that the extension wishes to use. - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {content::BrowserThread::UI}, base::BindOnce(&IdentityGetAuthTokenFunction::FetchExtensionAccountInfo, weak_ptr_factory_.GetWeakPtr(), gaia_id));
diff --git a/chrome/browser/extensions/api/image_writer_private/image_writer_utility_client_browsertest.cc b/chrome/browser/extensions/api/image_writer_private/image_writer_utility_client_browsertest.cc index ff16813..797239e 100644 --- a/chrome/browser/extensions/api/image_writer_private/image_writer_utility_client_browsertest.cc +++ b/chrome/browser/extensions/api/image_writer_private/image_writer_utility_client_browsertest.cc
@@ -41,8 +41,8 @@ EXPECT_TRUE(base::CreateTemporaryFileInDir(temp_dir_.GetPath(), &image_)); base::RunLoop run_loop; - base::PostTaskWithTraitsAndReply( - FROM_HERE, {base::MayBlock()}, + base::PostTaskAndReply( + FROM_HERE, {base::ThreadPool(), base::MayBlock()}, base::BindOnce(&ImageWriterUtilityClientTest::FillFile, image_, pattern), run_loop.QuitClosure()); @@ -54,8 +54,8 @@ device_ = image_.ReplaceExtension(FILE_PATH_LITERAL("out")); base::RunLoop run_loop; - base::PostTaskWithTraitsAndReply( - FROM_HERE, {base::MayBlock()}, + base::PostTaskAndReply( + FROM_HERE, {base::ThreadPool(), base::MayBlock()}, base::BindOnce(&ImageWriterUtilityClientTest::FillFile, device_, pattern), run_loop.QuitClosure()); @@ -199,8 +199,7 @@ success_ = cancel_; quit_called_ = true; - base::PostTaskWithTraits(FROM_HERE, {content::BrowserThread::UI}, - quit_closure_); + base::PostTask(FROM_HERE, {content::BrowserThread::UI}, quit_closure_); } void Shutdown() { @@ -209,8 +208,7 @@ image_writer_utility_client_->Shutdown(); quit_called_ = true; - base::PostTaskWithTraits(FROM_HERE, {content::BrowserThread::UI}, - quit_closure_); + base::PostTask(FROM_HERE, {content::BrowserThread::UI}, quit_closure_); } static void FillFile(const base::FilePath& path, char pattern) { @@ -220,8 +218,8 @@ base::SequencedTaskRunner* CreateTaskRunner() { DCHECK(!task_runner_.get()); - task_runner_ = base::CreateSequencedTaskRunnerWithTraits( - Operation::blocking_task_traits()); + task_runner_ = + base::CreateSequencedTaskRunner(Operation::blocking_task_traits()); return task_runner_.get(); }
diff --git a/chrome/browser/extensions/api/image_writer_private/operation.cc b/chrome/browser/extensions/api/image_writer_private/operation.cc index 2107847d..330d582a 100644 --- a/chrome/browser/extensions/api/image_writer_private/operation.cc +++ b/chrome/browser/extensions/api/image_writer_private/operation.cc
@@ -42,8 +42,7 @@ stage_(image_writer_api::STAGE_UNKNOWN), progress_(0), download_folder_(download_folder), - task_runner_( - base::CreateSequencedTaskRunnerWithTraits(blocking_task_traits())) { + task_runner_(base::CreateSequencedTaskRunner(blocking_task_traits())) { } Operation::~Operation() { @@ -128,7 +127,7 @@ CleanUp(); - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {BrowserThread::UI}, base::BindOnce(&OperationManager::OnComplete, manager_, extension_id_)); } @@ -136,7 +135,7 @@ void Operation::Error(const std::string& error_message) { DCHECK(IsRunningInCorrectSequence()); - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {BrowserThread::UI}, base::BindOnce(&OperationManager::OnError, manager_, extension_id_, stage_, progress_, error_message)); @@ -157,10 +156,9 @@ progress_ = progress; - base::PostTaskWithTraits( - FROM_HERE, {BrowserThread::UI}, - base::BindOnce(&OperationManager::OnProgress, manager_, extension_id_, - stage_, progress_)); + base::PostTask(FROM_HERE, {BrowserThread::UI}, + base::BindOnce(&OperationManager::OnProgress, manager_, + extension_id_, stage_, progress_)); } void Operation::SetStage(image_writer_api::Stage stage) { @@ -172,10 +170,9 @@ stage_ = stage; progress_ = 0; - base::PostTaskWithTraits( - FROM_HERE, {BrowserThread::UI}, - base::BindOnce(&OperationManager::OnProgress, manager_, extension_id_, - stage_, progress_)); + base::PostTask(FROM_HERE, {BrowserThread::UI}, + base::BindOnce(&OperationManager::OnProgress, manager_, + extension_id_, stage_, progress_)); } bool Operation::IsCancelled() {
diff --git a/chrome/browser/extensions/api/image_writer_private/operation.h b/chrome/browser/extensions/api/image_writer_private/operation.h index 575d2c3..7444da74 100644 --- a/chrome/browser/extensions/api/image_writer_private/operation.h +++ b/chrome/browser/extensions/api/image_writer_private/operation.h
@@ -229,6 +229,7 @@ static constexpr base::TaskTraits blocking_task_traits() { return { + base::ThreadPool(), // Requires I/O. base::MayBlock(), // Apps (e.g. Chromebook Recovery Utility) present UI feedback based on
diff --git a/chrome/browser/extensions/api/image_writer_private/operation_chromeos.cc b/chrome/browser/extensions/api/image_writer_private/operation_chromeos.cc index 60ea32e..9144e4d 100644 --- a/chrome/browser/extensions/api/image_writer_private/operation_chromeos.cc +++ b/chrome/browser/extensions/api/image_writer_private/operation_chromeos.cc
@@ -26,8 +26,8 @@ void ClearImageBurner() { if (!BrowserThread::CurrentlyOn(BrowserThread::UI)) { - base::PostTaskWithTraits(FROM_HERE, {BrowserThread::UI}, - base::BindOnce(&ClearImageBurner)); + base::PostTask(FROM_HERE, {BrowserThread::UI}, + base::BindOnce(&ClearImageBurner)); return; } @@ -45,7 +45,7 @@ // Note this has to be run on the FILE thread to avoid concurrent access. AddCleanUpFunction(base::Bind(&ClearImageBurner)); - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {BrowserThread::UI}, base::BindOnce(&Operation::UnmountVolumes, this, continuation)); }
diff --git a/chrome/browser/extensions/api/image_writer_private/removable_storage_provider.cc b/chrome/browser/extensions/api/image_writer_private/removable_storage_provider.cc index 39dee11b..ec433f68 100644 --- a/chrome/browser/extensions/api/image_writer_private/removable_storage_provider.cc +++ b/chrome/browser/extensions/api/image_writer_private/removable_storage_provider.cc
@@ -28,9 +28,9 @@ return; } // We need to do some file i/o to get the device block size - base::PostTaskWithTraitsAndReplyWithResult( + base::PostTaskAndReplyWithResult( FROM_HERE, - {base::MayBlock(), base::TaskPriority::USER_VISIBLE, + {base::ThreadPool(), base::MayBlock(), base::TaskPriority::USER_VISIBLE, base::TaskShutdownBehavior::SKIP_ON_SHUTDOWN}, base::BindOnce(&RemovableStorageProvider::PopulateDeviceList), std::move(callback));
diff --git a/chrome/browser/extensions/api/image_writer_private/test_utils.cc b/chrome/browser/extensions/api/image_writer_private/test_utils.cc index 17643fe1..27c09d7 100644 --- a/chrome/browser/extensions/api/image_writer_private/test_utils.cc +++ b/chrome/browser/extensions/api/image_writer_private/test_utils.cc
@@ -91,8 +91,9 @@ default; FakeImageWriterClient::FakeImageWriterClient() - : ImageWriterUtilityClient(base::CreateSequencedTaskRunnerWithTraits( - {base::MayBlock(), base::TaskPriority::USER_VISIBLE, + : ImageWriterUtilityClient(base::CreateSequencedTaskRunner( + {base::ThreadPool(), base::MayBlock(), + base::TaskPriority::USER_VISIBLE, base::TaskShutdownBehavior::SKIP_ON_SHUTDOWN})) {} FakeImageWriterClient::~FakeImageWriterClient() {}
diff --git a/chrome/browser/extensions/api/image_writer_private/unzip_helper.cc b/chrome/browser/extensions/api/image_writer_private/unzip_helper.cc index f80ddf9d..4ae7b054 100644 --- a/chrome/browser/extensions/api/image_writer_private/unzip_helper.cc +++ b/chrome/browser/extensions/api/image_writer_private/unzip_helper.cc
@@ -34,8 +34,8 @@ void UnzipHelper::Unzip(const base::FilePath& image_path, const base::FilePath& temp_dir_path) { scoped_refptr<base::SingleThreadTaskRunner> task_runner = - base::CreateSingleThreadTaskRunnerWithTraits( - {base::MayBlock(), base::TaskPriority::USER_VISIBLE}); + base::CreateSingleThreadTaskRunner({base::ThreadPool(), base::MayBlock(), + base::TaskPriority::USER_VISIBLE}); task_runner->PostTask(FROM_HERE, base::BindOnce(&UnzipHelper::UnzipImpl, this, image_path, temp_dir_path)); }
diff --git a/chrome/browser/extensions/api/image_writer_private/write_from_url_operation_unittest.cc b/chrome/browser/extensions/api/image_writer_private/write_from_url_operation_unittest.cc index 5c87a075f..fd04e40 100644 --- a/chrome/browser/extensions/api/image_writer_private/write_from_url_operation_unittest.cc +++ b/chrome/browser/extensions/api/image_writer_private/write_from_url_operation_unittest.cc
@@ -241,7 +241,7 @@ // soon. operation->VerifyDownload(base::Bind( [](base::OnceClosure quit_closure) { - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {content::BrowserThread::UI, base::TaskPriority::USER_VISIBLE}, std::move(quit_closure));
diff --git a/chrome/browser/extensions/api/messaging/native_message_host_chromeos.cc b/chrome/browser/extensions/api/messaging/native_message_host_chromeos.cc index 078befe..e030517 100644 --- a/chrome/browser/extensions/api/messaging/native_message_host_chromeos.cc +++ b/chrome/browser/extensions/api/messaging/native_message_host_chromeos.cc
@@ -95,10 +95,8 @@ std::unique_ptr<NativeMessageHost> CreateIt2MeHost() { return remoting::CreateIt2MeNativeMessagingHostForChromeOS( - base::CreateSingleThreadTaskRunnerWithTraits( - {content::BrowserThread::IO}), - base::CreateSingleThreadTaskRunnerWithTraits( - {content::BrowserThread::UI}), + base::CreateSingleThreadTaskRunner({content::BrowserThread::IO}), + base::CreateSingleThreadTaskRunner({content::BrowserThread::UI}), g_browser_process->policy_service()); }
diff --git a/chrome/browser/extensions/api/messaging/native_message_process_host.cc b/chrome/browser/extensions/api/messaging/native_message_process_host.cc index b6e5a3e..fa65b8fd 100644 --- a/chrome/browser/extensions/api/messaging/native_message_process_host.cc +++ b/chrome/browser/extensions/api/messaging/native_message_process_host.cc
@@ -71,8 +71,8 @@ write_pending_(false) { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); - task_runner_ = base::CreateSingleThreadTaskRunnerWithTraits( - {content::BrowserThread::IO}); + task_runner_ = + base::CreateSingleThreadTaskRunner({content::BrowserThread::IO}); } NativeMessageProcessHost::~NativeMessageProcessHost() { @@ -83,8 +83,9 @@ // TODO(https://crbug.com/806451): On OSX EnsureProcessTerminated() may // block, so we have to post a task on the blocking pool. #if defined(OS_MACOSX) - base::PostTaskWithTraits( - FROM_HERE, {base::MayBlock(), base::TaskPriority::BEST_EFFORT}, + base::PostTask( + FROM_HERE, + {base::ThreadPool(), base::MayBlock(), base::TaskPriority::BEST_EFFORT}, base::BindOnce(&base::EnsureProcessTerminated, Passed(&process_))); #else base::EnsureProcessTerminated(std::move(process_)); @@ -162,8 +163,8 @@ read_file_ = read_file.GetPlatformFile(); #endif - scoped_refptr<base::TaskRunner> task_runner(base::CreateTaskRunnerWithTraits( - {base::MayBlock(), base::TaskPriority::USER_VISIBLE, + scoped_refptr<base::TaskRunner> task_runner(base::CreateTaskRunner( + {base::ThreadPool(), base::MayBlock(), base::TaskPriority::USER_VISIBLE, base::TaskShutdownBehavior::SKIP_ON_SHUTDOWN})); read_stream_.reset(new net::FileStream(std::move(read_file), task_runner));
diff --git a/chrome/browser/extensions/api/messaging/native_process_launcher.cc b/chrome/browser/extensions/api/messaging/native_process_launcher.cc index fc731d68..c0d8491b 100644 --- a/chrome/browser/extensions/api/messaging/native_process_launcher.cc +++ b/chrome/browser/extensions/api/messaging/native_process_launcher.cc
@@ -132,10 +132,11 @@ const GURL& origin, const std::string& native_host_name, const LaunchedCallback& callback) { - base::PostTaskWithTraits(FROM_HERE, - {base::MayBlock(), base::TaskPriority::USER_VISIBLE}, - base::BindOnce(&Core::DoLaunchOnThreadPool, this, - origin, native_host_name, callback)); + base::PostTask( + FROM_HERE, + {base::ThreadPool(), base::MayBlock(), base::TaskPriority::USER_VISIBLE}, + base::BindOnce(&Core::DoLaunchOnThreadPool, this, origin, + native_host_name, callback)); } void NativeProcessLauncherImpl::Core::DoLaunchOnThreadPool( @@ -290,7 +291,7 @@ void NativeProcessLauncherImpl::Core::PostErrorResult( const LaunchedCallback& callback, LaunchResult error) { - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {content::BrowserThread::IO}, base::BindOnce(&NativeProcessLauncherImpl::Core::CallCallbackOnIOThread, this, callback, error, base::Process(), base::File(), @@ -302,7 +303,7 @@ base::Process process, base::File read_file, base::File write_file) { - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {content::BrowserThread::IO}, base::BindOnce(&NativeProcessLauncherImpl::Core::CallCallbackOnIOThread, this, callback, RESULT_SUCCESS, std::move(process),
diff --git a/chrome/browser/extensions/api/networking_cast_private/chrome_networking_cast_private_delegate.cc b/chrome/browser/extensions/api/networking_cast_private/chrome_networking_cast_private_delegate.cc index 27060f8c..db66f4b2 100644 --- a/chrome/browser/extensions/api/networking_cast_private/chrome_networking_cast_private_delegate.cc +++ b/chrome/browser/extensions/api/networking_cast_private/chrome_networking_cast_private_delegate.cc
@@ -133,8 +133,9 @@ std::unique_ptr<Credentials> credentials, const VerifiedCallback& success_callback, const FailureCallback& failure_callback) { - base::PostTaskWithTraitsAndReplyWithResult( - FROM_HERE, {base::MayBlock(), base::TaskPriority::USER_VISIBLE}, + base::PostTaskAndReplyWithResult( + FROM_HERE, + {base::ThreadPool(), base::MayBlock(), base::TaskPriority::USER_VISIBLE}, base::Bind(&RunDecodeAndVerifyCredentials, base::Passed(&credentials)), base::Bind(&VerifyDestinationCompleted, success_callback, failure_callback)); @@ -145,8 +146,9 @@ std::unique_ptr<Credentials> credentials, const DataCallback& success_callback, const FailureCallback& failure_callback) { - base::PostTaskWithTraitsAndReplyWithResult( - FROM_HERE, {base::MayBlock(), base::TaskPriority::USER_VISIBLE}, + base::PostTaskAndReplyWithResult( + FROM_HERE, + {base::ThreadPool(), base::MayBlock(), base::TaskPriority::USER_VISIBLE}, base::Bind(&RunVerifyAndEncryptData, data, base::Passed(&credentials)), base::Bind(&VerifyAndEncryptDataCompleted, success_callback, failure_callback));
diff --git a/chrome/browser/extensions/api/page_capture/page_capture_api.cc b/chrome/browser/extensions/api/page_capture/page_capture_api.cc index 1d92fae..9ea3a3c7 100644 --- a/chrome/browser/extensions/api/page_capture/page_capture_api.cc +++ b/chrome/browser/extensions/api/page_capture/page_capture_api.cc
@@ -52,6 +52,7 @@ const char kUserDenied[] = "User denied request."; #endif constexpr base::TaskTraits kCreateTemporaryFileTaskTraits = { + base::ThreadPool(), // Requires IO. base::MayBlock(), @@ -74,7 +75,7 @@ PageCaptureSaveAsMHTMLFunction::~PageCaptureSaveAsMHTMLFunction() { if (mhtml_file_.get()) { - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {BrowserThread::IO}, base::BindOnce(&ClearFileReferenceOnIOThread, std::move(mhtml_file_))); } @@ -118,7 +119,7 @@ if (!CanCaptureCurrentPage()) { return false; } - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, kCreateTemporaryFileTaskTraits, base::BindOnce(&PageCaptureSaveAsMHTMLFunction::CreateTemporaryFile, this)); @@ -179,7 +180,7 @@ void PageCaptureSaveAsMHTMLFunction::ResolvePermissionRequest( const PermissionIDSet& allowed_permissions) { if (allowed_permissions.ContainsID(APIPermission::kPageCapture)) { - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, kCreateTemporaryFileTaskTraits, base::BindOnce(&PageCaptureSaveAsMHTMLFunction::CreateTemporaryFile, this)); @@ -191,7 +192,7 @@ void PageCaptureSaveAsMHTMLFunction::CreateTemporaryFile() { bool success = base::CreateTemporaryFile(&mhtml_path_); - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {BrowserThread::IO}, base::BindOnce(&PageCaptureSaveAsMHTMLFunction::TemporaryFileCreatedOnIO, this, success)); @@ -204,8 +205,8 @@ // once it is no longer used. mhtml_file_ = ShareableFileReference::GetOrCreate( mhtml_path_, ShareableFileReference::DELETE_ON_FINAL_RELEASE, - base::CreateSequencedTaskRunnerWithTraits( - {// Requires IO. + base::CreateSequencedTaskRunner( + {base::ThreadPool(), // Requires IO. base::MayBlock(), // TaskPriority: Inherit. @@ -217,7 +218,7 @@ base::TaskShutdownBehavior::BLOCK_SHUTDOWN}) .get()); } - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {BrowserThread::UI}, base::BindOnce(&PageCaptureSaveAsMHTMLFunction::TemporaryFileCreatedOnUI, this, success));
diff --git a/chrome/browser/extensions/api/passwords_private/passwords_private_apitest.cc b/chrome/browser/extensions/api/passwords_private/passwords_private_apitest.cc index 5ac9e7e8..94758ce1 100644 --- a/chrome/browser/extensions/api/passwords_private/passwords_private_apitest.cc +++ b/chrome/browser/extensions/api/passwords_private/passwords_private_apitest.cc
@@ -69,24 +69,10 @@ } ~TestDelegate() override {} - void SendSavedPasswordsList() override { - PasswordsPrivateEventRouter* router = - PasswordsPrivateEventRouterFactory::GetForProfile(profile_); - if (router) - router->OnSavedPasswordsListChanged(current_entries_); - } - void GetSavedPasswordsList(UiEntriesCallback callback) override { std::move(callback).Run(current_entries_); } - void SendPasswordExceptionsList() override { - PasswordsPrivateEventRouter* router = - PasswordsPrivateEventRouterFactory::GetForProfile(profile_); - if (router) - router->OnPasswordExceptionsListChanged(current_exceptions_); - } - void GetPasswordExceptionsList( const ExceptionEntriesCallback& callback) override { callback.Run(current_exceptions_); @@ -181,6 +167,20 @@ bool cancelExportPasswordsTriggered = false; private: + void SendSavedPasswordsList() { + PasswordsPrivateEventRouter* router = + PasswordsPrivateEventRouterFactory::GetForProfile(profile_); + if (router) + router->OnSavedPasswordsListChanged(current_entries_); + } + + void SendPasswordExceptionsList() { + PasswordsPrivateEventRouter* router = + PasswordsPrivateEventRouterFactory::GetForProfile(profile_); + if (router) + router->OnPasswordExceptionsListChanged(current_exceptions_); + } + // The current list of entries/exceptions. Cached here so that when new // observers are added, this delegate can send the current lists without // having to request them from |password_manager_presenter_| again.
diff --git a/chrome/browser/extensions/api/passwords_private/passwords_private_delegate.h b/chrome/browser/extensions/api/passwords_private/passwords_private_delegate.h index 9ea44f8d..5c4bb10 100644 --- a/chrome/browser/extensions/api/passwords_private/passwords_private_delegate.h +++ b/chrome/browser/extensions/api/passwords_private/passwords_private_delegate.h
@@ -27,9 +27,9 @@ namespace extensions { -// Delegate used by the chrome.passwordsPrivate API to facilitate removing saved -// passwords and password exceptions and to notify listeners when these values -// have changed. +// Delegate used by the chrome.passwordsPrivate API to facilitate working with +// saved passwords and password exceptions (reading, changing, removing, +// import/export) and to notify listeners when these values have changed. class PasswordsPrivateDelegate : public KeyedService { public: using PlaintextPasswordCallback = @@ -37,17 +37,11 @@ ~PasswordsPrivateDelegate() override {} - // Sends the saved passwords list to the event router. - virtual void SendSavedPasswordsList() = 0; - // Gets the saved passwords list. using UiEntries = std::vector<api::passwords_private::PasswordUiEntry>; using UiEntriesCallback = base::OnceCallback<void(const UiEntries&)>; virtual void GetSavedPasswordsList(UiEntriesCallback callback) = 0; - // Sends the password exceptions list to the event router. - virtual void SendPasswordExceptionsList() = 0; - // Gets the password exceptions list. using ExceptionEntries = std::vector<api::passwords_private::ExceptionEntry>; using ExceptionEntriesCallback =
diff --git a/chrome/browser/extensions/api/passwords_private/passwords_private_delegate_impl.h b/chrome/browser/extensions/api/passwords_private/passwords_private_delegate_impl.h index 105f7e63..03d191b7 100644 --- a/chrome/browser/extensions/api/passwords_private/passwords_private_delegate_impl.h +++ b/chrome/browser/extensions/api/passwords_private/passwords_private_delegate_impl.h
@@ -44,9 +44,7 @@ ~PasswordsPrivateDelegateImpl() override; // PasswordsPrivateDelegate implementation. - void SendSavedPasswordsList() override; void GetSavedPasswordsList(UiEntriesCallback callback) override; - void SendPasswordExceptionsList() override; void GetPasswordExceptionsList( const ExceptionEntriesCallback& callback) override; void ChangeSavedPassword( @@ -99,6 +97,9 @@ // has been initialized or by deferring it until initialization has completed. void ExecuteFunction(const base::Closure& callback); + void SendSavedPasswordsList(); + void SendPasswordExceptionsList(); + void RemoveSavedPasswordInternal(int id); void RemovePasswordExceptionInternal(int id); void UndoRemoveSavedPasswordOrExceptionInternal();
diff --git a/chrome/browser/extensions/api/platform_keys/platform_keys_apitest_nss.cc b/chrome/browser/extensions/api/platform_keys/platform_keys_apitest_nss.cc index f6600316d..74e95cb0 100644 --- a/chrome/browser/extensions/api/platform_keys/platform_keys_apitest_nss.cc +++ b/chrome/browser/extensions/api/platform_keys/platform_keys_apitest_nss.cc
@@ -53,7 +53,7 @@ // |PlatformKeysTestBase::SetUpOnMainThread| triggers the user sign-in. ASSERT_TRUE(user_private_slot_db_.is_open()); base::RunLoop loop; - base::PostTaskWithTraitsAndReply( + base::PostTaskAndReply( FROM_HERE, {content::BrowserThread::IO}, base::BindOnce(&PlatformKeysTest::SetPrivateSoftwareSlotOnIO, base::Unretained(this),
diff --git a/chrome/browser/extensions/api/platform_keys/platform_keys_test_base.cc b/chrome/browser/extensions/api/platform_keys/platform_keys_test_base.cc index 305c68f..166d76a 100644 --- a/chrome/browser/extensions/api/platform_keys/platform_keys_test_base.cc +++ b/chrome/browser/extensions/api/platform_keys/platform_keys_test_base.cc
@@ -155,7 +155,7 @@ if (system_token_status() == SystemTokenStatus::EXISTS) { base::RunLoop loop; - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {content::BrowserThread::IO}, base::BindOnce(&PlatformKeysTestBase::SetUpTestSystemSlotOnIO, base::Unretained(this), loop.QuitClosure())); @@ -170,7 +170,7 @@ if (system_token_status() == SystemTokenStatus::EXISTS) { base::RunLoop loop; - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {content::BrowserThread::IO}, base::BindOnce(&PlatformKeysTestBase::TearDownTestSystemSlotOnIO, base::Unretained(this), loop.QuitClosure())); @@ -211,14 +211,14 @@ PrepareTestSystemSlotOnIO(test_system_slot_.get()); - base::PostTaskWithTraits(FROM_HERE, {content::BrowserThread::UI}, - std::move(done_callback)); + base::PostTask(FROM_HERE, {content::BrowserThread::UI}, + std::move(done_callback)); } void PlatformKeysTestBase::TearDownTestSystemSlotOnIO( base::OnceClosure done_callback) { test_system_slot_.reset(); - base::PostTaskWithTraits(FROM_HERE, {content::BrowserThread::UI}, - std::move(done_callback)); + base::PostTask(FROM_HERE, {content::BrowserThread::UI}, + std::move(done_callback)); }
diff --git a/chrome/browser/extensions/api/platform_keys/verify_trust_api.cc b/chrome/browser/extensions/api/platform_keys/verify_trust_api.cc index d05673e9..59c40015 100644 --- a/chrome/browser/extensions/api/platform_keys/verify_trust_api.cc +++ b/chrome/browser/extensions/api/platform_keys/verify_trust_api.cc
@@ -112,7 +112,7 @@ &CallBackOnUI, base::Bind(&VerifyTrustAPI::FinishedVerificationOnUI, weak_factory_.GetWeakPtr(), ui_callback))); - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {content::BrowserThread::IO}, base::BindOnce(&IOPart::Verify, base::Unretained(io_part_.get()), base::Passed(¶ms), extension_id, finish_callback)); @@ -122,7 +122,7 @@ content::BrowserContext* browser_context, const Extension* extension, UnloadedExtensionReason reason) { - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {content::BrowserThread::IO}, base::BindOnce(&IOPart::OnExtensionUnloaded, base::Unretained(io_part_.get()), extension->id())); @@ -142,9 +142,8 @@ const std::string& error, int return_value, int cert_status) { - base::PostTaskWithTraits( - FROM_HERE, {content::BrowserThread::UI}, - base::BindOnce(ui_callback, error, return_value, cert_status)); + base::PostTask(FROM_HERE, {content::BrowserThread::UI}, + base::BindOnce(ui_callback, error, return_value, cert_status)); } VerifyTrustAPI::IOPart::~IOPart() {
diff --git a/chrome/browser/extensions/api/processes/processes_api.cc b/chrome/browser/extensions/api/processes/processes_api.cc index 462bda6..093fa4f 100644 --- a/chrome/browser/extensions/api/processes/processes_api.cc +++ b/chrome/browser/extensions/api/processes/processes_api.cc
@@ -509,7 +509,7 @@ // This could be a non-renderer child process like a plugin or a nacl // process. Try to get its handle from the BrowserChildProcessHost on the // IO thread. - base::PostTaskWithTraitsAndReplyWithResult( + base::PostTaskAndReplyWithResult( FROM_HERE, {content::BrowserThread::IO}, base::Bind(&ProcessesTerminateFunction::GetProcessHandleOnIO, this, child_process_host_id_),
diff --git a/chrome/browser/extensions/api/storage/managed_value_store_cache.cc b/chrome/browser/extensions/api/storage/managed_value_store_cache.cc index ef8acf121..91b42ed 100644 --- a/chrome/browser/extensions/api/storage/managed_value_store_cache.cc +++ b/chrome/browser/extensions/api/storage/managed_value_store_cache.cc
@@ -205,9 +205,9 @@ (*components)[(*it)->id()] = schema; } - base::PostTaskWithTraits(FROM_HERE, {BrowserThread::UI}, - base::BindOnce(&ExtensionTracker::Register, self, - base::Owned(components.release()))); + base::PostTask(FROM_HERE, {BrowserThread::UI}, + base::BindOnce(&ExtensionTracker::Register, self, + base::Owned(components.release()))); } void ManagedValueStoreCache::ExtensionTracker::Register(
diff --git a/chrome/browser/extensions/api/terminal/terminal_private_api.cc b/chrome/browser/extensions/api/terminal/terminal_private_api.cc index 1dc03aa..ee10fd33 100644 --- a/chrome/browser/extensions/api/terminal/terminal_private_api.cc +++ b/chrome/browser/extensions/api/terminal/terminal_private_api.cc
@@ -84,10 +84,9 @@ const std::string& output_type, const std::string& output) { if (!content::BrowserThread::CurrentlyOn(content::BrowserThread::UI)) { - base::PostTaskWithTraits( - FROM_HERE, {content::BrowserThread::UI}, - base::BindOnce(&NotifyProcessOutput, browser_context, tab_id, - terminal_id, output_type, output)); + base::PostTask(FROM_HERE, {content::BrowserThread::UI}, + base::BindOnce(&NotifyProcessOutput, browser_context, tab_id, + terminal_id, output_type, output)); return; } @@ -197,8 +196,8 @@ bool success = registry->OpenProcess(cmdline, user_id_hash, output_callback, &terminal_id); - base::PostTaskWithTraits(FROM_HERE, {content::BrowserThread::UI}, - base::BindOnce(callback, success, terminal_id)); + base::PostTask(FROM_HERE, {content::BrowserThread::UI}, + base::BindOnce(callback, success, terminal_id)); } TerminalPrivateSendInputFunction::~TerminalPrivateSendInputFunction() {} @@ -232,7 +231,7 @@ bool success = chromeos::ProcessProxyRegistry::Get()->SendInput(terminal_id, text); - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {content::BrowserThread::UI}, base::BindOnce(&TerminalPrivateSendInputFunction::RespondOnUIThread, this, success)); @@ -265,7 +264,7 @@ bool success = chromeos::ProcessProxyRegistry::Get()->CloseProcess(terminal_id); - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {content::BrowserThread::UI}, base::BindOnce( &TerminalPrivateCloseTerminalProcessFunction::RespondOnUIThread, this, @@ -303,7 +302,7 @@ bool success = chromeos::ProcessProxyRegistry::Get()->OnTerminalResize( terminal_id, width, height); - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {content::BrowserThread::UI}, base::BindOnce( &TerminalPrivateOnTerminalResizeFunction::RespondOnUIThread, this,
diff --git a/chrome/browser/extensions/api/webrtc_logging_private/webrtc_logging_private_api.cc b/chrome/browser/extensions/api/webrtc_logging_private/webrtc_logging_private_api.cc index 8a6d956d..f62882df 100644 --- a/chrome/browser/extensions/api/webrtc_logging_private/webrtc_logging_private_api.cc +++ b/chrome/browser/extensions/api/webrtc_logging_private/webrtc_logging_private_api.cc
@@ -288,7 +288,7 @@ // Post a task since this is an asynchronous extension function. // TODO(devlin): This is unneccessary; this should just be a // ExtensionFunction. Fix this. - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {BrowserThread::UI}, base::BindOnce( &WebrtcLoggingPrivateSetUploadOnRenderCloseFunction::SendResponse,
diff --git a/chrome/browser/flag-metadata.json b/chrome/browser/flag-metadata.json index ef3680d..58715bb 100644 --- a/chrome/browser/flag-metadata.json +++ b/chrome/browser/flag-metadata.json
@@ -550,8 +550,8 @@ }, { "name": "cryptauth-v2-enrollment", - "owners": [ "jlklein", "khorimoto", "nohle" ], - "expiry_milestone": 76 + "owners": [ "khorimoto", "nohle" ], + "expiry_milestone": 82 }, { "name": "d3d11-video-decoder", @@ -880,8 +880,8 @@ }, { "name": "enable-autofill-account-wallet-storage", - "owners": [ "feuunk", "butter-team@google.com" ], - "expiry_milestone": 76 + "owners": [ "treib", "jsaul@google.com", "butter-team@google.com" ], + "expiry_milestone": 81 }, { "name": "enable-autofill-credit-card-ablation-experiment",
diff --git a/chrome/browser/payments/android/journey_logger_android.cc b/chrome/browser/payments/android/journey_logger_android.cc index 319725e..4a0336c 100644 --- a/chrome/browser/payments/android/journey_logger_android.cc +++ b/chrome/browser/payments/android/journey_logger_android.cc
@@ -151,6 +151,12 @@ ConvertJavaStringToUTF8(env, jvalue), jcompleted); } +void JourneyLoggerAndroid::SetTriggerTime( + JNIEnv* env, + const base::android::JavaParamRef<jobject>& jcaller) { + journey_logger_.SetTriggerTime(); +} + static jlong JNI_JourneyLogger_InitJourneyLoggerAndroid( JNIEnv* env, const JavaParamRef<jobject>& jcaller,
diff --git a/chrome/browser/payments/android/journey_logger_android.h b/chrome/browser/payments/android/journey_logger_android.h index 4219bb3..bffb292 100644 --- a/chrome/browser/payments/android/journey_logger_android.h +++ b/chrome/browser/payments/android/journey_logger_android.h
@@ -78,6 +78,8 @@ const base::android::JavaParamRef<jstring>& jcurrency, const base::android::JavaParamRef<jstring>& jvalue, jboolean jcompleted); + void SetTriggerTime(JNIEnv* env, + const base::android::JavaParamRef<jobject>& jcaller); private: JourneyLogger journey_logger_;
diff --git a/chrome/browser/renderer_host/pepper/device_id_fetcher.cc b/chrome/browser/renderer_host/pepper/device_id_fetcher.cc index bb5a147e..712e0a74 100644 --- a/chrome/browser/renderer_host/pepper/device_id_fetcher.cc +++ b/chrome/browser/renderer_host/pepper/device_id_fetcher.cc
@@ -76,9 +76,8 @@ in_progress_ = true; callback_ = callback; - base::PostTaskWithTraits( - FROM_HERE, {BrowserThread::UI}, - base::BindOnce(&DeviceIDFetcher::CheckPrefsOnUIThread, this)); + base::PostTask(FROM_HERE, {BrowserThread::UI}, + base::BindOnce(&DeviceIDFetcher::CheckPrefsOnUIThread, this)); return true; } @@ -125,10 +124,11 @@ #if defined(OS_CHROMEOS) // Try the legacy path first for ChromeOS. We pass the new salt in as well // in case the legacy id doesn't exist. - base::PostTaskWithTraits(FROM_HERE, - {base::MayBlock(), base::TaskPriority::BEST_EFFORT}, - base::BindOnce(&DeviceIDFetcher::LegacyComputeAsync, - this, profile->GetPath(), salt)); + base::PostTask( + FROM_HERE, + {base::ThreadPool(), base::MayBlock(), base::TaskPriority::BEST_EFFORT}, + base::BindOnce(&DeviceIDFetcher::LegacyComputeAsync, this, + profile->GetPath(), salt)); #else // Get the machine ID and call ComputeOnUIThread with salt + machine_id. GetMachineIDAsync( @@ -191,20 +191,18 @@ } // If we didn't find an ID, get the machine ID and call the new code path to // generate an ID. - base::PostTaskWithTraits( - FROM_HERE, {BrowserThread::UI}, - base::BindOnce( - &GetMachineIDAsync, - base::Bind(&DeviceIDFetcher::ComputeOnUIThread, this, salt))); + base::PostTask(FROM_HERE, {BrowserThread::UI}, + base::BindOnce(&GetMachineIDAsync, + base::Bind(&DeviceIDFetcher::ComputeOnUIThread, + this, salt))); } void DeviceIDFetcher::RunCallbackOnIOThread(const std::string& id, int32_t result) { if (!BrowserThread::CurrentlyOn(BrowserThread::IO)) { - base::PostTaskWithTraits( - FROM_HERE, {BrowserThread::IO}, - base::BindOnce(&DeviceIDFetcher::RunCallbackOnIOThread, this, id, - result)); + base::PostTask(FROM_HERE, {BrowserThread::IO}, + base::BindOnce(&DeviceIDFetcher::RunCallbackOnIOThread, this, + id, result)); return; } in_progress_ = false;
diff --git a/chrome/browser/renderer_host/pepper/monitor_finder_mac.mm b/chrome/browser/renderer_host/pepper/monitor_finder_mac.mm index 087cba2..41f0611 100644 --- a/chrome/browser/renderer_host/pepper/monitor_finder_mac.mm +++ b/chrome/browser/renderer_host/pepper/monitor_finder_mac.mm
@@ -30,9 +30,8 @@ request_sent_ = true; } - base::PostTaskWithTraits( - FROM_HERE, {content::BrowserThread::UI}, - base::BindOnce(&MonitorFinder::FetchMonitorFromWidget, this)); + base::PostTask(FROM_HERE, {content::BrowserThread::UI}, + base::BindOnce(&MonitorFinder::FetchMonitorFromWidget, this)); return display_id_; }
diff --git a/chrome/browser/renderer_host/pepper/pepper_broker_message_filter.cc b/chrome/browser/renderer_host/pepper/pepper_broker_message_filter.cc index 83cedb4..37245c48 100644 --- a/chrome/browser/renderer_host/pepper/pepper_broker_message_filter.cc +++ b/chrome/browser/renderer_host/pepper/pepper_broker_message_filter.cc
@@ -37,7 +37,7 @@ scoped_refptr<base::TaskRunner> PepperBrokerMessageFilter::OverrideTaskRunnerForMessage( const IPC::Message& message) { - return base::CreateSingleThreadTaskRunnerWithTraits({BrowserThread::UI}); + return base::CreateSingleThreadTaskRunner({BrowserThread::UI}); } int32_t PepperBrokerMessageFilter::OnResourceMessageReceived(
diff --git a/chrome/browser/renderer_host/pepper/pepper_flash_browser_host.cc b/chrome/browser/renderer_host/pepper/pepper_flash_browser_host.cc index 9d28e92..c6c2ac11 100644 --- a/chrome/browser/renderer_host/pepper/pepper_flash_browser_host.cc +++ b/chrome/browser/renderer_host/pepper/pepper_flash_browser_host.cc
@@ -135,7 +135,7 @@ plugin_url, cookie_settings_); } else { - base::PostTaskWithTraitsAndReplyWithResult( + base::PostTaskAndReplyWithResult( FROM_HERE, {BrowserThread::UI}, base::Bind(&GetCookieSettings, render_process_id_), base::Bind(&PepperFlashBrowserHost::GetLocalDataRestrictions, @@ -192,9 +192,9 @@ // The existing connector is bound to the UI thread, the current thread is // IO thread. So bind the ConnectorRequest of IO thread to the connector // in UI thread. - base::PostTaskWithTraits(FROM_HERE, {BrowserThread::UI}, - base::BindOnce(&PepperBindConnectorRequest, - std::move(connector_request))); + base::PostTask(FROM_HERE, {BrowserThread::UI}, + base::BindOnce(&PepperBindConnectorRequest, + std::move(connector_request))); device::mojom::WakeLockProviderPtr wake_lock_provider; connector->BindInterface(device::mojom::kServiceName,
diff --git a/chrome/browser/renderer_host/pepper/pepper_flash_clipboard_message_filter.cc b/chrome/browser/renderer_host/pepper/pepper_flash_clipboard_message_filter.cc index da44713..7469e74 100644 --- a/chrome/browser/renderer_host/pepper/pepper_flash_clipboard_message_filter.cc +++ b/chrome/browser/renderer_host/pepper/pepper_flash_clipboard_message_filter.cc
@@ -106,16 +106,16 @@ // restrictions of various platform APIs. In general, the clipboard is not // thread-safe, so all clipboard calls should be serviced from the UI thread. if (msg.type() == PpapiHostMsg_FlashClipboard_WriteData::ID) - return base::CreateSingleThreadTaskRunnerWithTraits({BrowserThread::UI}); + return base::CreateSingleThreadTaskRunner({BrowserThread::UI}); // Windows needs clipboard reads to be serviced from the IO thread because // these are sync IPCs which can result in deadlocks with plugins if serviced // from the UI thread. Note that Windows clipboard calls ARE thread-safe so it // is ok for reads and writes to be serviced from different threads. #if !defined(OS_WIN) - return base::CreateSingleThreadTaskRunnerWithTraits({BrowserThread::UI}); + return base::CreateSingleThreadTaskRunner({BrowserThread::UI}); #else - return base::CreateSingleThreadTaskRunnerWithTraits({BrowserThread::IO}); + return base::CreateSingleThreadTaskRunner({BrowserThread::IO}); #endif }
diff --git a/chrome/browser/renderer_host/pepper/pepper_flash_drm_host.cc b/chrome/browser/renderer_host/pepper/pepper_flash_drm_host.cc index 0a727e8c..2e51425 100644 --- a/chrome/browser/renderer_host/pepper/pepper_flash_drm_host.cc +++ b/chrome/browser/renderer_host/pepper/pepper_flash_drm_host.cc
@@ -61,7 +61,7 @@ // do this because we don't know how often our client is going // to call and we can't cache the |monitor_| value. if (InterlockedCompareExchange(&request_sent_, 1, 0) == 0) { - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {content::BrowserThread::UI}, base::BindOnce(&MonitorFinder::FetchMonitorFromWidget, this)); }
diff --git a/chrome/browser/renderer_host/pepper/pepper_isolated_file_system_message_filter.cc b/chrome/browser/renderer_host/pepper/pepper_isolated_file_system_message_filter.cc index 0d083bb..00db4e2 100644 --- a/chrome/browser/renderer_host/pepper/pepper_isolated_file_system_message_filter.cc +++ b/chrome/browser/renderer_host/pepper/pepper_isolated_file_system_message_filter.cc
@@ -81,8 +81,7 @@ const IPC::Message& msg) { // In order to reach ExtensionSystem, we need to get ProfileManager first. // ProfileManager lives in UI thread, so we need to do this in UI thread. - return base::CreateSingleThreadTaskRunnerWithTraits( - {content::BrowserThread::UI}); + return base::CreateSingleThreadTaskRunner({content::BrowserThread::UI}); } int32_t PepperIsolatedFileSystemMessageFilter::OnResourceMessageReceived(
diff --git a/chrome/browser/resources/settings/autofill_page/BUILD.gn b/chrome/browser/resources/settings/autofill_page/BUILD.gn index 5758c5b..1afa9c4 100644 --- a/chrome/browser/resources/settings/autofill_page/BUILD.gn +++ b/chrome/browser/resources/settings/autofill_page/BUILD.gn
@@ -117,6 +117,7 @@ ":password_list_item", ":password_manager_proxy", "..:global_scroll_target_behavior", + "../people_page:sync_browser_proxy", "//third_party/polymer/v1_0/components-chromium/iron-a11y-announcer:iron-a11y-announcer-extracted", "//third_party/polymer/v1_0/components-chromium/iron-a11y-keys-behavior:iron-a11y-keys-behavior-extracted", "//ui/webui/resources/cr_elements/cr_action_menu:cr_action_menu", @@ -125,6 +126,7 @@ "//ui/webui/resources/js:i18n_behavior", "//ui/webui/resources/js:list_property_update_behavior", "//ui/webui/resources/js:util", + "//ui/webui/resources/js:web_ui_listener_behavior", "//ui/webui/resources/js/cr/ui:focus_without_ink", ] externs_list = [ "$externs_path/passwords_private.js" ]
diff --git a/chrome/browser/resources/settings/autofill_page/passwords_section.html b/chrome/browser/resources/settings/autofill_page/passwords_section.html index d80e1ba..3c21d97e 100644 --- a/chrome/browser/resources/settings/autofill_page/passwords_section.html +++ b/chrome/browser/resources/settings/autofill_page/passwords_section.html
@@ -77,7 +77,8 @@ label="$i18n{passwordsAutosigninLabel}" sub-label="$i18n{passwordsAutosigninDescription}"> </settings-toggle-button> - <div id="manageLink" class="settings-box first two-line"> + <div id="manageLink" class="settings-box first two-line" + hidden$="[[hidePasswordsLink_]]"> <!-- This span lays out the url correctly, relative to the label. --> <span>$i18nRaw{managePasswordsLabel}</span> </div>
diff --git a/chrome/browser/resources/settings/autofill_page/passwords_section.js b/chrome/browser/resources/settings/autofill_page/passwords_section.js index 0a5eb38..c3b30c0 100644 --- a/chrome/browser/resources/settings/autofill_page/passwords_section.js +++ b/chrome/browser/resources/settings/autofill_page/passwords_section.js
@@ -36,6 +36,7 @@ behaviors: [ I18nBehavior, + WebUIListenerBehavior, ListPropertyUpdateBehavior, Polymer.IronA11yKeysBehavior, settings.GlobalScrollTargetBehavior, @@ -94,6 +95,12 @@ }, /** @private */ + hidePasswordsLink_: { + type: Boolean, + computed: 'computeHidePasswordsLink_(syncPrefs_, syncStatus_)', + }, + + /** @private */ showExportPasswords_: { type: Boolean, computed: 'hasPasswords_(savedPasswords.splices)', @@ -111,6 +118,12 @@ /** @private */ showPasswordEditDialog_: Boolean, + /** @private {settings.SyncPrefs} */ + syncPrefs_: Object, + + /** @private {settings.SyncStatus} */ + syncStatus_: Object, + /** Filter on the saved passwords and exceptions. */ filter: { type: String, @@ -229,6 +242,16 @@ this.notifySplices('savedPasswords', []); + const syncBrowserProxy = settings.SyncBrowserProxyImpl.getInstance(); + + const syncStatusChanged = syncStatus => this.syncStatus_ = syncStatus; + syncBrowserProxy.getSyncStatus().then(syncStatusChanged); + this.addWebUIListener('sync-status-changed', syncStatusChanged); + + const syncPrefsChanged = syncPrefs => this.syncPrefs_ = syncPrefs; + this.addWebUIListener('sync-prefs-changed', syncPrefsChanged); + syncBrowserProxy.sendSyncPrefsChanged(); + Polymer.RenderStatus.afterNextRender(this, function() { Polymer.IronA11yAnnouncer.requestAvailability(); }); @@ -306,6 +329,15 @@ }, /** + * @return {boolean} + * @private + */ + computeHidePasswordsLink_: function() { + return !!this.syncStatus_ && !!this.syncStatus_.signedIn && + !!this.syncPrefs_ && !!this.syncPrefs_.encryptAllData; + }, + + /** * @param {string} filter * @return {!Array<!PasswordManagerProxy.UiEntryWithPassword>} * @private
diff --git a/chrome/browser/resources/settings/people_page/sync_browser_proxy.js b/chrome/browser/resources/settings/people_page/sync_browser_proxy.js index 1b17c57..dfaa6b3 100644 --- a/chrome/browser/resources/settings/people_page/sync_browser_proxy.js +++ b/chrome/browser/resources/settings/people_page/sync_browser_proxy.js
@@ -211,6 +211,13 @@ * Opens the Google Activity Controls url in a new tab. */ openActivityControlsUrl() {} + + /** + * Function to dispatch event sync-prefs-changed even without a change. + * This is used to decide whether we should show the link to password + * manager in passwords section on page load. + */ + sendSyncPrefsChanged() {} } /** @@ -298,6 +305,11 @@ chrome.metricsPrivate.recordUserAction( 'Signin_AccountSettings_GoogleActivityControlsClicked'); } + + /** @override */ + sendSyncPrefsChanged() { + chrome.send('SyncPrefsDispatch'); + } } cr.addSingletonGetter(SyncBrowserProxyImpl);
diff --git a/chrome/browser/signin/identity_services_provider_android.cc b/chrome/browser/signin/identity_services_provider_android.cc index e80e11f..be416f66 100644 --- a/chrome/browser/signin/identity_services_provider_android.cc +++ b/chrome/browser/signin/identity_services_provider_android.cc
@@ -13,6 +13,14 @@ using base::android::ScopedJavaLocalRef; static ScopedJavaLocalRef<jobject> +JNI_IdentityServicesProvider_GetIdentityManager( + JNIEnv* env, + const JavaParamRef<jobject>& j_profile_android) { + Profile* profile = ProfileAndroid::FromProfileAndroid(j_profile_android); + return IdentityManagerFactory::GetForProfile(profile)->GetJavaObject(); +} + +static ScopedJavaLocalRef<jobject> JNI_IdentityServicesProvider_GetAccountTrackerService( JNIEnv* env, const JavaParamRef<jobject>& j_profile_android) {
diff --git a/chrome/browser/ui/BUILD.gn b/chrome/browser/ui/BUILD.gn index ecc801d..efe5670 100644 --- a/chrome/browser/ui/BUILD.gn +++ b/chrome/browser/ui/BUILD.gn
@@ -1009,6 +1009,9 @@ "page_info/page_info_infobar_delegate.h", "page_info/permission_menu_model.cc", "page_info/permission_menu_model.h", + "passwords/credential_manager_dialog_controller.h", + "passwords/credential_manager_dialog_controller_impl.cc", + "passwords/credential_manager_dialog_controller_impl.h", "passwords/google_password_manager_navigation_throttle.cc", "passwords/google_password_manager_navigation_throttle.h", "passwords/manage_passwords_bubble_model.cc", @@ -1016,9 +1019,7 @@ "passwords/manage_passwords_icon_view.h", "passwords/manage_passwords_ui_controller.cc", "passwords/manage_passwords_ui_controller.h", - "passwords/password_dialog_controller.h", - "passwords/password_dialog_controller_impl.cc", - "passwords/password_dialog_controller_impl.h", + "passwords/password_base_dialog_controller.h", "passwords/password_dialog_prompts.h", "passwords/passwords_client_ui_delegate.cc", "passwords/passwords_client_ui_delegate.h", @@ -3979,10 +3980,10 @@ "exclusive_access/fullscreen_controller_test.h", "global_error/global_error_waiter.cc", "global_error/global_error_waiter.h", + "passwords/credential_manager_dialog_controller_mock.cc", + "passwords/credential_manager_dialog_controller_mock.h", "passwords/manage_passwords_ui_controller_mock.cc", "passwords/manage_passwords_ui_controller_mock.h", - "passwords/password_dialog_controller_mock.cc", - "passwords/password_dialog_controller_mock.h", "passwords/passwords_model_delegate_mock.cc", "passwords/passwords_model_delegate_mock.h", "tabs/tab_ukm_test_helper.cc",
diff --git a/chrome/browser/ui/android/passwords/manual_filling_view_android.cc b/chrome/browser/ui/android/passwords/manual_filling_view_android.cc index 63bcb79..f144c1e 100644 --- a/chrome/browser/ui/android/passwords/manual_filling_view_android.cc +++ b/chrome/browser/ui/android/passwords/manual_filling_view_android.cc
@@ -152,7 +152,8 @@ ScopedJavaLocalRef<jobject> j_tab_data = Java_ManualFillingComponentBridge_createAccessorySheetData( env, static_cast<int>(tab_data.get_sheet_type()), - ConvertUTF16ToJavaString(env, tab_data.title())); + ConvertUTF16ToJavaString(env, tab_data.title()), + ConvertUTF16ToJavaString(env, tab_data.warning())); for (const UserInfo& user_info : tab_data.user_info_list()) { ScopedJavaLocalRef<jobject> j_user_info =
diff --git a/chrome/browser/ui/android/widget/BUILD.gn b/chrome/browser/ui/android/widget/BUILD.gn index c521dcb..9bed5918 100644 --- a/chrome/browser/ui/android/widget/BUILD.gn +++ b/chrome/browser/ui/android/widget/BUILD.gn
@@ -6,7 +6,19 @@ android_library("java") { java_files = [ + "java/src/org/chromium/chrome//browser/ui/widget/CompositeTouchDelegate.java", "java/src/org/chromium/chrome//browser/ui/widget/FadingShadow.java", "java/src/org/chromium/chrome//browser/ui/widget/FadingShadowView.java", ] } + +junit_binary("ui_widget_junit_tests") { + java_files = [ "junit/src/org/chromium/chrome//browser/ui/widget/CompositeTouchDelegateTest.java" ] + deps = [ + ":java", + "//base:base_java", + "//base:base_java_test_support", + "//base:base_junit_test_support", + "//base/test:test_support_java", + ] +}
diff --git a/chrome/browser/ui/android/widget/DEPS b/chrome/browser/ui/android/widget/DEPS index 61b58f2..cb8c60a 100644 --- a/chrome/browser/ui/android/widget/DEPS +++ b/chrome/browser/ui/android/widget/DEPS
@@ -1,3 +1,5 @@ noparent = True -include_rules = [ ] +include_rules = [ + "+base", +]
diff --git a/chrome/browser/ui/android/widget/java/src/org/chromium/chrome/browser/ui/widget/CompositeTouchDelegate.java b/chrome/browser/ui/android/widget/java/src/org/chromium/chrome/browser/ui/widget/CompositeTouchDelegate.java new file mode 100644 index 0000000..f4b1112 --- /dev/null +++ b/chrome/browser/ui/android/widget/java/src/org/chromium/chrome/browser/ui/widget/CompositeTouchDelegate.java
@@ -0,0 +1,68 @@ +// Copyright 2019 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +package org.chromium.chrome.browser.ui.widget; + +import android.graphics.Rect; +import android.view.MotionEvent; +import android.view.TouchDelegate; +import android.view.View; + +import java.util.ArrayList; +import java.util.List; + +/** + * Allows multiple touch delegates for one parent view. + * When to use this class: + * You need add touch delegates to two or more views that share the same parent. + * To use this class: + * 1. Add this as an instance variable to an ancestor view. + * 2. Set the CompositeTouchDelegate to the ancestor view's TouchDelegate slot (setTouchDelegate). + * 2. Pass the CompositeTouchDelegate instance into the descendant views. + * 3. Register the descendant's TouchDelegate with the supplied CompositeTouchDelegate using + * {@link #addDelegateForDescendantView}. + * + * Note that it is expected that the registered touch delegates will each handle a different region + * of the ancestor view. Only the first matching TouchDelegate that can handle a touch event will be + * sent the event. + */ +public class CompositeTouchDelegate extends TouchDelegate { + private final List<TouchDelegate> mDelegates = new ArrayList<>(); + + /** + * @param view Used to get the context. + */ + public CompositeTouchDelegate(View view) { + super(new Rect(), view); + } + + /** + * Add a delegate to the composite. + * @param delegate Delegate to be added, this will receive touch events. + */ + public void addDelegateForDescendantView(TouchDelegate delegate) { + mDelegates.add(delegate); + } + + /** + * Remove the delegate from the composite. + * @param delegate Delegate to be removed. + */ + public void removeDelegateForDescendantView(TouchDelegate delegate) { + mDelegates.remove(delegate); + } + + @Override + public boolean onTouchEvent(MotionEvent event) { + float x = event.getX(); + float y = event.getY(); + for (TouchDelegate delegate : mDelegates) { + event.setLocation(x, y); + boolean wasTouchEventHandled = delegate.onTouchEvent(event); + if (wasTouchEventHandled) return true; + } + + return false; + } +}
diff --git a/chrome/browser/ui/android/widget/junit/src/org/chromium/chrome/browser/ui/widget/CompositeTouchDelegateTest.java b/chrome/browser/ui/android/widget/junit/src/org/chromium/chrome/browser/ui/widget/CompositeTouchDelegateTest.java new file mode 100644 index 0000000..29637ec --- /dev/null +++ b/chrome/browser/ui/android/widget/junit/src/org/chromium/chrome/browser/ui/widget/CompositeTouchDelegateTest.java
@@ -0,0 +1,74 @@ +// Copyright 2019 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +package org.chromium.chrome.browser.ui.widget; + +import android.view.MotionEvent; +import android.view.TouchDelegate; +import android.view.View; + +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.mockito.MockitoAnnotations; +import org.robolectric.annotation.Config; + +import org.chromium.base.test.BaseRobolectricTestRunner; + +/** + * Tests for CompositeTouchDelegate. + */ +@RunWith(BaseRobolectricTestRunner.class) +@Config(manifest = Config.NONE) +public final class CompositeTouchDelegateTest { + CompositeTouchDelegate mCompositeTouchDelegate; + + @Mock + View mMockAncestorView; + + @Mock + TouchDelegate mMockTouchDelegate; + + @Mock + TouchDelegate mMockOtherTouchDelegate; + + @Mock + MotionEvent mMockMotionEvent; + + @Before + public void setUp() { + MockitoAnnotations.initMocks(this); + mCompositeTouchDelegate = new CompositeTouchDelegate(mMockAncestorView); + mCompositeTouchDelegate.addDelegateForDescendantView(mMockTouchDelegate); + mCompositeTouchDelegate.addDelegateForDescendantView(mMockOtherTouchDelegate); + } + + @Test + public void addDelegateForDescendantView_onTouchEventCallsDelegates() { + mCompositeTouchDelegate.onTouchEvent(mMockMotionEvent); + Mockito.verify(mMockTouchDelegate).onTouchEvent(mMockMotionEvent); + Mockito.verify(mMockOtherTouchDelegate).onTouchEvent(mMockMotionEvent); + } + + @Test + public void addDelegateForDescendantView_onTouchEventIsHandledByFirst() { + // Signal that the event is handled. + Mockito.when(mMockTouchDelegate.onTouchEvent(mMockMotionEvent)).thenReturn(true); + Assert.assertTrue(mCompositeTouchDelegate.onTouchEvent(mMockMotionEvent)); + Mockito.verify(mMockTouchDelegate).onTouchEvent(mMockMotionEvent); + // Event was handled already, so the event won't make it here. + Mockito.verify(mMockOtherTouchDelegate, Mockito.never()).onTouchEvent(mMockMotionEvent); + } + + @Test + public void removeDelegateForDescendantView_onTouchEventCallsDelegates() { + mCompositeTouchDelegate.removeDelegateForDescendantView(mMockOtherTouchDelegate); + mCompositeTouchDelegate.onTouchEvent(mMockMotionEvent); + Mockito.verify(mMockTouchDelegate).onTouchEvent(mMockMotionEvent); + Mockito.verify(mMockOtherTouchDelegate, Mockito.never()).onTouchEvent(mMockMotionEvent); + } +}
diff --git a/chrome/browser/ui/ash/test_login_screen.cc b/chrome/browser/ui/ash/test_login_screen.cc index f366a81..ced91e94 100644 --- a/chrome/browser/ui/ash/test_login_screen.cc +++ b/chrome/browser/ui/ash/test_login_screen.cc
@@ -58,3 +58,8 @@ TestLoginScreen::GetScopedGuestButtonBlocker() { return std::make_unique<ScopedGuestButtonBlockerTestImpl>(); } + +void TestLoginScreen::RequestSecurityTokenPin( + ash::SecurityTokenPinRequest request) {} + +void TestLoginScreen::ClearSecurityTokenPinRequest() {}
diff --git a/chrome/browser/ui/ash/test_login_screen.h b/chrome/browser/ui/ash/test_login_screen.h index e5fcc1a..d94cbbfa 100644 --- a/chrome/browser/ui/ash/test_login_screen.h +++ b/chrome/browser/ui/ash/test_login_screen.h
@@ -49,6 +49,8 @@ void SetAllowLoginAsGuest(bool allow_guest) override; std::unique_ptr<ash::ScopedGuestButtonBlocker> GetScopedGuestButtonBlocker() override; + void RequestSecurityTokenPin(ash::SecurityTokenPinRequest request) override; + void ClearSecurityTokenPinRequest() override; private: TestLoginScreenModel test_screen_model_;
diff --git a/chrome/browser/ui/global_media_controls/media_dialog_controller.cc b/chrome/browser/ui/global_media_controls/media_dialog_controller.cc index a60816f..762d71c 100644 --- a/chrome/browser/ui/global_media_controls/media_dialog_controller.cc +++ b/chrome/browser/ui/global_media_controls/media_dialog_controller.cc
@@ -29,16 +29,16 @@ // Connect to the controller manager so we can create media controllers for // media sessions. - connector_->BindInterface(media_session::mojom::kServiceName, - mojo::MakeRequest(&controller_manager_ptr_)); + connector_->Connect(media_session::mojom::kServiceName, + controller_manager_remote_.BindNewPipeAndPassReceiver()); // Connect to receive audio focus events. - connector_->BindInterface(media_session::mojom::kServiceName, - mojo::MakeRequest(&audio_focus_ptr_)); - audio_focus_ptr_->AddObserver( + connector_->Connect(media_session::mojom::kServiceName, + audio_focus_remote_.BindNewPipeAndPassReceiver()); + audio_focus_remote_->AddObserver( audio_focus_observer_receiver_.BindNewPipeAndPassRemote()); - audio_focus_ptr_->GetFocusRequests( + audio_focus_remote_->GetFocusRequests( base::BindOnce(&MediaDialogController::OnReceivedAudioFocusRequests, weak_ptr_factory_.GetWeakPtr())); } @@ -53,13 +53,13 @@ if (it != sessions_.end() && !it->second.frozen()) return; - media_session::mojom::MediaControllerPtr controller; + mojo::Remote<media_session::mojom::MediaController> controller; - // |controller_manager_ptr_| may be null in tests where connector is + // |controller_manager_remote_| may be null in tests where connector is // unavailable. - if (controller_manager_ptr_) { - controller_manager_ptr_->CreateMediaControllerForSession( - mojo::MakeRequest(&controller), *session->request_id); + if (controller_manager_remote_) { + controller_manager_remote_->CreateMediaControllerForSession( + controller.BindNewPipeAndPassReceiver(), *session->request_id); } if (it != sessions_.end()) {
diff --git a/chrome/browser/ui/global_media_controls/media_dialog_controller.h b/chrome/browser/ui/global_media_controls/media_dialog_controller.h index 22ed04e0b..a5c13b4 100644 --- a/chrome/browser/ui/global_media_controls/media_dialog_controller.h +++ b/chrome/browser/ui/global_media_controls/media_dialog_controller.h
@@ -11,6 +11,7 @@ #include "base/memory/weak_ptr.h" #include "components/media_message_center/media_notification_controller.h" #include "mojo/public/cpp/bindings/receiver.h" +#include "mojo/public/cpp/bindings/remote.h" #include "services/media_session/public/mojom/audio_focus.mojom.h" #include "services/media_session/public/mojom/media_controller.mojom.h" @@ -64,8 +65,9 @@ std::map<const std::string, media_message_center::MediaNotificationItem> sessions_; - media_session::mojom::AudioFocusManagerPtr audio_focus_ptr_; - media_session::mojom::MediaControllerManagerPtr controller_manager_ptr_; + mojo::Remote<media_session::mojom::AudioFocusManager> audio_focus_remote_; + mojo::Remote<media_session::mojom::MediaControllerManager> + controller_manager_remote_; // Used to receive updates to the active media controller. mojo::Receiver<media_session::mojom::AudioFocusObserver>
diff --git a/chrome/browser/ui/passwords/password_dialog_controller.h b/chrome/browser/ui/passwords/credential_manager_dialog_controller.h similarity index 81% rename from chrome/browser/ui/passwords/password_dialog_controller.h rename to chrome/browser/ui/passwords/credential_manager_dialog_controller.h index fea1e0a..a3a0cf6 100644 --- a/chrome/browser/ui/passwords/password_dialog_controller.h +++ b/chrome/browser/ui/passwords/credential_manager_dialog_controller.h
@@ -2,14 +2,15 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#ifndef CHROME_BROWSER_UI_PASSWORDS_PASSWORD_DIALOG_CONTROLLER_H_ -#define CHROME_BROWSER_UI_PASSWORDS_PASSWORD_DIALOG_CONTROLLER_H_ +#ifndef CHROME_BROWSER_UI_PASSWORDS_CREDENTIAL_MANAGER_DIALOG_CONTROLLER_H_ +#define CHROME_BROWSER_UI_PASSWORDS_CREDENTIAL_MANAGER_DIALOG_CONTROLLER_H_ #include <memory> #include <utility> #include <vector> #include "base/strings/string16.h" +#include "chrome/browser/ui/passwords/password_base_dialog_controller.h" #include "components/password_manager/core/common/credential_manager_types.h" #include "ui/gfx/range/range.h" @@ -19,7 +20,7 @@ // An interface used by the password dialog (the account chooser) for setting // and retrieving the state. -class PasswordDialogController { +class CredentialManagerDialogController : public PasswordBaseDialogController { public: using FormsVector = std::vector<std::unique_ptr<autofill::PasswordForm>>; @@ -59,8 +60,7 @@ virtual void OnCloseDialog() = 0; protected: - virtual ~PasswordDialogController() = default; + ~CredentialManagerDialogController() override = default; }; - -#endif // CHROME_BROWSER_UI_PASSWORDS_PASSWORD_DIALOG_CONTROLLER_H_ +#endif // CHROME_BROWSER_UI_PASSWORDS_CREDENTIAL_MANAGER_DIALOG_CONTROLLER_H_
diff --git a/chrome/browser/ui/passwords/password_dialog_controller_impl.cc b/chrome/browser/ui/passwords/credential_manager_dialog_controller_impl.cc similarity index 76% rename from chrome/browser/ui/passwords/password_dialog_controller_impl.cc rename to chrome/browser/ui/passwords/credential_manager_dialog_controller_impl.cc index a197b10..d07f5db 100644 --- a/chrome/browser/ui/passwords/password_dialog_controller_impl.cc +++ b/chrome/browser/ui/passwords/credential_manager_dialog_controller_impl.cc
@@ -2,7 +2,7 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "chrome/browser/ui/passwords/password_dialog_controller_impl.h" +#include "chrome/browser/ui/passwords/credential_manager_dialog_controller_impl.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/sync/profile_sync_service_factory.h" @@ -19,20 +19,20 @@ #include "components/sync/driver/sync_service.h" #include "ui/base/l10n/l10n_util.h" -PasswordDialogControllerImpl::PasswordDialogControllerImpl( - Profile* profle, +CredentialManagerDialogControllerImpl::CredentialManagerDialogControllerImpl( + Profile* profile, PasswordsModelDelegate* delegate) - : profile_(profle), + : profile_(profile), delegate_(delegate), account_chooser_dialog_(nullptr), - autosignin_dialog_(nullptr) { -} + autosignin_dialog_(nullptr) {} -PasswordDialogControllerImpl::~PasswordDialogControllerImpl() { +CredentialManagerDialogControllerImpl:: + ~CredentialManagerDialogControllerImpl() { ResetDialog(); } -void PasswordDialogControllerImpl::ShowAccountChooser( +void CredentialManagerDialogControllerImpl::ShowAccountChooser( AccountChooserPrompt* dialog, std::vector<std::unique_ptr<autofill::PasswordForm>> locals) { DCHECK(!account_chooser_dialog_); @@ -43,7 +43,7 @@ account_chooser_dialog_->ShowAccountChooser(); } -void PasswordDialogControllerImpl::ShowAutosigninPrompt( +void CredentialManagerDialogControllerImpl::ShowAutosigninPrompt( AutoSigninFirstRunPrompt* dialog) { DCHECK(!account_chooser_dialog_); DCHECK(!autosignin_dialog_); @@ -52,39 +52,46 @@ autosignin_dialog_->ShowAutoSigninPrompt(); } -const PasswordDialogController::FormsVector& -PasswordDialogControllerImpl::GetLocalForms() const { +bool CredentialManagerDialogControllerImpl::IsShowingAccountChooser() const { + return !!account_chooser_dialog_; +} + +const CredentialManagerDialogController::FormsVector& +CredentialManagerDialogControllerImpl::GetLocalForms() const { return local_credentials_; } -base::string16 PasswordDialogControllerImpl::GetAccoutChooserTitle() const { +base::string16 CredentialManagerDialogControllerImpl::GetAccoutChooserTitle() + const { return l10n_util::GetStringUTF16(IDS_PASSWORD_MANAGER_ACCOUNT_CHOOSER_TITLE); } -bool PasswordDialogControllerImpl::ShouldShowSignInButton() const { +bool CredentialManagerDialogControllerImpl::ShouldShowSignInButton() const { return local_credentials_.size() == 1; } -base::string16 PasswordDialogControllerImpl::GetAutoSigninPromoTitle() const { +base::string16 CredentialManagerDialogControllerImpl::GetAutoSigninPromoTitle() + const { int message_id = IsSyncingAutosignSetting(profile_) ? IDS_AUTO_SIGNIN_FIRST_RUN_TITLE_MANY_DEVICES : IDS_AUTO_SIGNIN_FIRST_RUN_TITLE_LOCAL_DEVICE; return l10n_util::GetStringUTF16(message_id); } -base::string16 PasswordDialogControllerImpl::GetAutoSigninText() const { +base::string16 CredentialManagerDialogControllerImpl::GetAutoSigninText() + const { return l10n_util::GetStringFUTF16( IDS_AUTO_SIGNIN_FIRST_RUN_TEXT, l10n_util::GetStringUTF16(IDS_PASSWORD_MANAGER_TITLE_BRAND)); } -bool PasswordDialogControllerImpl::ShouldShowFooter() const { +bool CredentialManagerDialogControllerImpl::ShouldShowFooter() const { const syncer::SyncService* sync_service = ProfileSyncServiceFactory::GetForProfile(profile_); return password_bubble_experiment::IsSmartLockUser(sync_service); } -void PasswordDialogControllerImpl::OnChooseCredentials( +void CredentialManagerDialogControllerImpl::OnChooseCredentials( const autofill::PasswordForm& password_form, password_manager::CredentialType credential_type) { if (local_credentials_.size() == 1) { @@ -98,7 +105,7 @@ delegate_->ChooseCredential(password_form, credential_type); } -void PasswordDialogControllerImpl::OnSignInClicked() { +void CredentialManagerDialogControllerImpl::OnSignInClicked() { DCHECK_EQ(1u, local_credentials_.size()); password_manager::metrics_util::LogAccountChooserUserActionOneAccount( password_manager::metrics_util::ACCOUNT_CHOOSER_SIGN_IN); @@ -108,7 +115,7 @@ password_manager::CredentialType::CREDENTIAL_TYPE_PASSWORD); } -void PasswordDialogControllerImpl::OnAutoSigninOK() { +void CredentialManagerDialogControllerImpl::OnAutoSigninOK() { password_bubble_experiment::RecordAutoSignInPromptFirstRunExperienceWasShown( profile_->GetPrefs()); password_manager::metrics_util::LogAutoSigninPromoUserAction( @@ -117,7 +124,7 @@ OnCloseDialog(); } -void PasswordDialogControllerImpl::OnAutoSigninTurnOff() { +void CredentialManagerDialogControllerImpl::OnAutoSigninTurnOff() { profile_->GetPrefs()->SetBoolean( password_manager::prefs::kCredentialsEnableAutosignin, false); password_bubble_experiment::RecordAutoSignInPromptFirstRunExperienceWasShown( @@ -128,7 +135,7 @@ OnCloseDialog(); } -void PasswordDialogControllerImpl::OnCloseDialog() { +void CredentialManagerDialogControllerImpl::OnCloseDialog() { if (account_chooser_dialog_) { if (local_credentials_.size() == 1) { password_manager::metrics_util::LogAccountChooserUserActionOneAccount( @@ -147,7 +154,7 @@ delegate_->OnDialogHidden(); } -void PasswordDialogControllerImpl::ResetDialog() { +void CredentialManagerDialogControllerImpl::ResetDialog() { if (account_chooser_dialog_) { account_chooser_dialog_->ControllerGone(); account_chooser_dialog_ = nullptr;
diff --git a/chrome/browser/ui/passwords/password_dialog_controller_impl.h b/chrome/browser/ui/passwords/credential_manager_dialog_controller_impl.h similarity index 68% rename from chrome/browser/ui/passwords/password_dialog_controller_impl.h rename to chrome/browser/ui/passwords/credential_manager_dialog_controller_impl.h index c511fcd..acf3c76 100644 --- a/chrome/browser/ui/passwords/password_dialog_controller_impl.h +++ b/chrome/browser/ui/passwords/credential_manager_dialog_controller_impl.h
@@ -2,14 +2,14 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#ifndef CHROME_BROWSER_UI_PASSWORDS_PASSWORD_DIALOG_CONTROLLER_IMPL_H_ -#define CHROME_BROWSER_UI_PASSWORDS_PASSWORD_DIALOG_CONTROLLER_IMPL_H_ +#ifndef CHROME_BROWSER_UI_PASSWORDS_CREDENTIAL_MANAGER_DIALOG_CONTROLLER_IMPL_H_ +#define CHROME_BROWSER_UI_PASSWORDS_CREDENTIAL_MANAGER_DIALOG_CONTROLLER_IMPL_H_ #include <memory> #include <vector> #include "base/macros.h" -#include "chrome/browser/ui/passwords/password_dialog_controller.h" +#include "chrome/browser/ui/passwords/credential_manager_dialog_controller.h" class AccountChooserPrompt; class AutoSigninFirstRunPrompt; @@ -18,11 +18,12 @@ // A UI controller responsible for the account chooser dialog and autosignin // first run promo. -class PasswordDialogControllerImpl : public PasswordDialogController { +class CredentialManagerDialogControllerImpl + : public CredentialManagerDialogController { public: - PasswordDialogControllerImpl(Profile* profle, - PasswordsModelDelegate* delegate); - ~PasswordDialogControllerImpl() override; + CredentialManagerDialogControllerImpl(Profile* profile, + PasswordsModelDelegate* delegate); + ~CredentialManagerDialogControllerImpl() override; // Pop up the account chooser dialog. void ShowAccountChooser(AccountChooserPrompt* dialog, FormsVector locals); @@ -30,11 +31,10 @@ // Pop up the autosignin first run dialog. void ShowAutosigninPrompt(AutoSigninFirstRunPrompt* dialog); - bool IsShowingAccountChooser() const { return !!account_chooser_dialog_; } - - // PasswordDialogController: + // CredentialManagerDialogController: const FormsVector& GetLocalForms() const override; base::string16 GetAccoutChooserTitle() const override; + bool IsShowingAccountChooser() const override; bool ShouldShowSignInButton() const override; base::string16 GetAutoSigninPromoTitle() const override; base::string16 GetAutoSigninText() const override; @@ -57,7 +57,7 @@ AutoSigninFirstRunPrompt* autosignin_dialog_; std::vector<std::unique_ptr<autofill::PasswordForm>> local_credentials_; - DISALLOW_COPY_AND_ASSIGN(PasswordDialogControllerImpl); + DISALLOW_COPY_AND_ASSIGN(CredentialManagerDialogControllerImpl); }; -#endif // CHROME_BROWSER_UI_PASSWORDS_PASSWORD_DIALOG_CONTROLLER_IMPL_H_ +#endif // CHROME_BROWSER_UI_PASSWORDS_CREDENTIAL_MANAGER_DIALOG_CONTROLLER_IMPL_H_
diff --git a/chrome/browser/ui/passwords/password_dialog_controller_impl_unittest.cc b/chrome/browser/ui/passwords/credential_manager_dialog_controller_impl_unittest.cc similarity index 80% rename from chrome/browser/ui/passwords/password_dialog_controller_impl_unittest.cc rename to chrome/browser/ui/passwords/credential_manager_dialog_controller_impl_unittest.cc index c036de6..4b146c342 100644 --- a/chrome/browser/ui/passwords/password_dialog_controller_impl_unittest.cc +++ b/chrome/browser/ui/passwords/credential_manager_dialog_controller_impl_unittest.cc
@@ -2,7 +2,7 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "chrome/browser/ui/passwords/password_dialog_controller_impl.h" +#include "chrome/browser/ui/passwords/credential_manager_dialog_controller_impl.h" #include <memory> #include <utility> @@ -52,17 +52,16 @@ return form; } -class PasswordDialogControllerTest : public testing::Test { +class CredentialManagerDialogControllerTest : public testing::Test { public: - PasswordDialogControllerTest() - : controller_(&profile_, &ui_controller_mock_) { - } + CredentialManagerDialogControllerTest() + : controller_(&profile_, &ui_controller_mock_) {} PasswordsModelDelegateMock& ui_controller_mock() { return ui_controller_mock_; } - PasswordDialogControllerImpl& controller() { return controller_; } + CredentialManagerDialogControllerImpl& controller() { return controller_; } PrefService* prefs() { return profile_.GetPrefs(); } @@ -70,10 +69,10 @@ content::TestBrowserThreadBundle thread_bundle_; TestingProfile profile_; StrictMock<PasswordsModelDelegateMock> ui_controller_mock_; - PasswordDialogControllerImpl controller_; + CredentialManagerDialogControllerImpl controller_; }; -TEST_F(PasswordDialogControllerTest, ShowAccountChooser) { +TEST_F(CredentialManagerDialogControllerTest, ShowAccountChooser) { base::HistogramTester histogram_tester; StrictMock<MockPasswordPrompt> prompt; autofill::PasswordForm local_form = GetLocalForm(); @@ -86,26 +85,27 @@ EXPECT_CALL(prompt, ShowAccountChooser()); controller().ShowAccountChooser(&prompt, std::move(locals)); - EXPECT_THAT(controller().GetLocalForms(), ElementsAre(Pointee(local_form), - Pointee(local_form2))); + EXPECT_THAT(controller().GetLocalForms(), + ElementsAre(Pointee(local_form), Pointee(local_form2))); EXPECT_FALSE(controller().ShouldShowSignInButton()); // Close the dialog. EXPECT_CALL(prompt, ControllerGone()); - EXPECT_CALL(ui_controller_mock(), ChooseCredential( - local_form, - password_manager::CredentialType::CREDENTIAL_TYPE_PASSWORD)); + EXPECT_CALL(ui_controller_mock(), + ChooseCredential( + local_form, + password_manager::CredentialType::CREDENTIAL_TYPE_PASSWORD)); controller().OnChooseCredentials( *local_form_ptr, password_manager::CredentialType::CREDENTIAL_TYPE_PASSWORD); histogram_tester.ExpectUniqueSample( "PasswordManager.AccountChooserDialogMultipleAccounts", - password_manager::metrics_util::ACCOUNT_CHOOSER_CREDENTIAL_CHOSEN, 1); + password_manager::metrics_util::ACCOUNT_CHOOSER_CREDENTIAL_CHOSEN, 1); histogram_tester.ExpectTotalCount( "PasswordManager.AccountChooserDialogOneAccount", 0); } -TEST_F(PasswordDialogControllerTest, ShowAccountChooserAndSignIn) { +TEST_F(CredentialManagerDialogControllerTest, ShowAccountChooserAndSignIn) { base::HistogramTester histogram_tester; StrictMock<MockPasswordPrompt> prompt; autofill::PasswordForm local_form = GetLocalForm(); @@ -119,18 +119,19 @@ // Close the dialog. EXPECT_CALL(prompt, ControllerGone()); - EXPECT_CALL(ui_controller_mock(), ChooseCredential( - local_form, - password_manager::CredentialType::CREDENTIAL_TYPE_PASSWORD)); + EXPECT_CALL(ui_controller_mock(), + ChooseCredential( + local_form, + password_manager::CredentialType::CREDENTIAL_TYPE_PASSWORD)); controller().OnSignInClicked(); histogram_tester.ExpectUniqueSample( "PasswordManager.AccountChooserDialogOneAccount", - password_manager::metrics_util::ACCOUNT_CHOOSER_SIGN_IN, 1); + password_manager::metrics_util::ACCOUNT_CHOOSER_SIGN_IN, 1); histogram_tester.ExpectTotalCount( "PasswordManager.AccountChooserDialogMultipleAccounts", 0); } -TEST_F(PasswordDialogControllerTest, AccountChooserClosed) { +TEST_F(CredentialManagerDialogControllerTest, AccountChooserClosed) { base::HistogramTester histogram_tester; StrictMock<MockPasswordPrompt> prompt; std::vector<std::unique_ptr<autofill::PasswordForm>> locals; @@ -142,12 +143,12 @@ controller().OnCloseDialog(); histogram_tester.ExpectUniqueSample( "PasswordManager.AccountChooserDialogOneAccount", - password_manager::metrics_util::ACCOUNT_CHOOSER_DISMISSED, 1); + password_manager::metrics_util::ACCOUNT_CHOOSER_DISMISSED, 1); histogram_tester.ExpectTotalCount( "PasswordManager.AccountChooserDialogMultipleAccounts", 0); } -TEST_F(PasswordDialogControllerTest, AutoSigninPromo) { +TEST_F(CredentialManagerDialogControllerTest, AutoSigninPromo) { base::HistogramTester histogram_tester; StrictMock<MockPasswordPrompt> prompt; EXPECT_CALL(prompt, ShowAutoSigninPrompt()); @@ -162,10 +163,10 @@ prefs())); histogram_tester.ExpectUniqueSample( "PasswordManager.AutoSigninFirstRunDialog", - password_manager::metrics_util::AUTO_SIGNIN_NO_ACTION, 1); + password_manager::metrics_util::AUTO_SIGNIN_NO_ACTION, 1); } -TEST_F(PasswordDialogControllerTest, AutoSigninPromoOkGotIt) { +TEST_F(CredentialManagerDialogControllerTest, AutoSigninPromoOkGotIt) { base::HistogramTester histogram_tester; StrictMock<MockPasswordPrompt> prompt; EXPECT_CALL(prompt, ShowAutoSigninPrompt()); @@ -185,10 +186,10 @@ password_manager::prefs::kCredentialsEnableAutosignin)); histogram_tester.ExpectUniqueSample( "PasswordManager.AutoSigninFirstRunDialog", - password_manager::metrics_util::AUTO_SIGNIN_OK_GOT_IT, 1); + password_manager::metrics_util::AUTO_SIGNIN_OK_GOT_IT, 1); } -TEST_F(PasswordDialogControllerTest, AutoSigninPromoTurnOff) { +TEST_F(CredentialManagerDialogControllerTest, AutoSigninPromoTurnOff) { base::HistogramTester histogram_tester; StrictMock<MockPasswordPrompt> prompt; EXPECT_CALL(prompt, ShowAutoSigninPrompt()); @@ -208,7 +209,7 @@ password_manager::prefs::kCredentialsEnableAutosignin)); histogram_tester.ExpectUniqueSample( "PasswordManager.AutoSigninFirstRunDialog", - password_manager::metrics_util::AUTO_SIGNIN_TURN_OFF, 1); + password_manager::metrics_util::AUTO_SIGNIN_TURN_OFF, 1); } } // namespace
diff --git a/chrome/browser/ui/passwords/credential_manager_dialog_controller_mock.cc b/chrome/browser/ui/passwords/credential_manager_dialog_controller_mock.cc new file mode 100644 index 0000000..b22c2013 --- /dev/null +++ b/chrome/browser/ui/passwords/credential_manager_dialog_controller_mock.cc
@@ -0,0 +1,13 @@ +// Copyright 2016 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "chrome/browser/ui/passwords/credential_manager_dialog_controller_mock.h" + +#include "components/autofill/core/common/password_form.h" + +CredentialManagerDialogControllerMock::CredentialManagerDialogControllerMock() = + default; + +CredentialManagerDialogControllerMock:: + ~CredentialManagerDialogControllerMock() = default;
diff --git a/chrome/browser/ui/passwords/credential_manager_dialog_controller_mock.h b/chrome/browser/ui/passwords/credential_manager_dialog_controller_mock.h new file mode 100644 index 0000000..7069f72 --- /dev/null +++ b/chrome/browser/ui/passwords/credential_manager_dialog_controller_mock.h
@@ -0,0 +1,37 @@ +// Copyright 2016 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef CHROME_BROWSER_UI_PASSWORDS_CREDENTIAL_MANAGER_DIALOG_CONTROLLER_MOCK_H_ +#define CHROME_BROWSER_UI_PASSWORDS_CREDENTIAL_MANAGER_DIALOG_CONTROLLER_MOCK_H_ + +#include "base/macros.h" +#include "chrome/browser/ui/passwords/credential_manager_dialog_controller.h" +#include "testing/gmock/include/gmock/gmock.h" + +class CredentialManagerDialogControllerMock + : public CredentialManagerDialogController { + public: + CredentialManagerDialogControllerMock(); + ~CredentialManagerDialogControllerMock() override; + + MOCK_CONST_METHOD0(GetLocalForms, const FormsVector&()); + MOCK_CONST_METHOD0(GetAccoutChooserTitle, base::string16()); + MOCK_CONST_METHOD0(ShouldShowSignInButton, bool()); + MOCK_CONST_METHOD0(GetAutoSigninPromoTitle, base::string16()); + MOCK_CONST_METHOD0(GetAutoSigninText, base::string16()); + MOCK_CONST_METHOD0(ShouldShowFooter, bool()); + MOCK_METHOD0(OnSmartLockLinkClicked, void()); + MOCK_METHOD2(OnChooseCredentials, + void(const autofill::PasswordForm& password_form, + password_manager::CredentialType credential_type)); + MOCK_METHOD0(OnSignInClicked, void()); + MOCK_METHOD0(OnAutoSigninOK, void()); + MOCK_METHOD0(OnAutoSigninTurnOff, void()); + MOCK_METHOD0(OnCloseDialog, void()); + + private: + DISALLOW_COPY_AND_ASSIGN(CredentialManagerDialogControllerMock); +}; + +#endif // CHROME_BROWSER_UI_PASSWORDS_CREDENTIAL_MANAGER_DIALOG_CONTROLLER_MOCK_H_
diff --git a/chrome/browser/ui/passwords/manage_passwords_ui_controller.cc b/chrome/browser/ui/passwords/manage_passwords_ui_controller.cc index dd2c162..bef7813 100644 --- a/chrome/browser/ui/passwords/manage_passwords_ui_controller.cc +++ b/chrome/browser/ui/passwords/manage_passwords_ui_controller.cc
@@ -25,9 +25,9 @@ #include "chrome/browser/ui/chrome_pages.h" #include "chrome/browser/ui/location_bar/location_bar.h" #include "chrome/browser/ui/page_action/page_action_icon_container.h" +#include "chrome/browser/ui/passwords/credential_manager_dialog_controller_impl.h" #include "chrome/browser/ui/passwords/manage_passwords_icon_view.h" #include "chrome/browser/ui/passwords/manage_passwords_view_utils.h" -#include "chrome/browser/ui/passwords/password_dialog_controller_impl.h" #include "chrome/browser/ui/passwords/password_dialog_prompts.h" #include "chrome/browser/ui/tab_dialogs.h" #include "chrome/common/url_constants.h" @@ -179,17 +179,16 @@ // the state because PSL matches aren't saved for current page. This logic is // implemented here because Android uses ManagePasswordsState as a data source // for account chooser. - PasswordDialogController::FormsVector locals; + CredentialManagerDialogController::FormsVector locals; if (!local_credentials[0]->is_public_suffix_match) locals = CopyFormVector(local_credentials); passwords_data_.OnRequestCredentials(std::move(locals), origin); passwords_data_.set_credentials_callback(callback); - dialog_controller_.reset(new PasswordDialogControllerImpl( - Profile::FromBrowserContext(web_contents()->GetBrowserContext()), - this)); - dialog_controller_->ShowAccountChooser( - CreateAccountChooser(dialog_controller_.get()), - std::move(local_credentials)); + auto* raw_controller = new CredentialManagerDialogControllerImpl( + Profile::FromBrowserContext(web_contents()->GetBrowserContext()), this); + dialog_controller_.reset(raw_controller); + raw_controller->ShowAccountChooser(CreateAccountChooser(raw_controller), + std::move(local_credentials)); UpdateBubbleAndIconVisibility(); return true; } @@ -208,11 +207,10 @@ // Both the account chooser and the previous prompt shouldn't be closed. if (dialog_controller_) return; - dialog_controller_.reset(new PasswordDialogControllerImpl( - Profile::FromBrowserContext(web_contents()->GetBrowserContext()), - this)); - dialog_controller_->ShowAutosigninPrompt( - CreateAutoSigninPrompt(dialog_controller_.get())); + auto* raw_controller = new CredentialManagerDialogControllerImpl( + Profile::FromBrowserContext(web_contents()->GetBrowserContext()), this); + dialog_controller_.reset(raw_controller); + raw_controller->ShowAutosigninPrompt(CreateAutoSigninPrompt(raw_controller)); } void ManagePasswordsUIController::OnAutomaticPasswordSave( @@ -514,12 +512,12 @@ } AccountChooserPrompt* ManagePasswordsUIController::CreateAccountChooser( - PasswordDialogController* controller) { + CredentialManagerDialogController* controller) { return CreateAccountChooserPromptView(controller, web_contents()); } AutoSigninFirstRunPrompt* ManagePasswordsUIController::CreateAutoSigninPrompt( - PasswordDialogController* controller) { + CredentialManagerDialogController* controller) { return CreateAutoSigninPromptView(controller, web_contents()); }
diff --git a/chrome/browser/ui/passwords/manage_passwords_ui_controller.h b/chrome/browser/ui/passwords/manage_passwords_ui_controller.h index 58cebb6..62edb86c 100644 --- a/chrome/browser/ui/passwords/manage_passwords_ui_controller.h +++ b/chrome/browser/ui/passwords/manage_passwords_ui_controller.h
@@ -37,8 +37,8 @@ struct AccountInfo; class AutoSigninFirstRunPrompt; class ManagePasswordsIconView; -class PasswordDialogController; -class PasswordDialogControllerImpl; +class CredentialManagerDialogController; +class PasswordBaseDialogController; // Per-tab class to control the Omnibox password icon and bubble. class ManagePasswordsUIController @@ -159,11 +159,11 @@ // Called to create the account chooser dialog. Mocked in tests. virtual AccountChooserPrompt* CreateAccountChooser( - PasswordDialogController* controller); + CredentialManagerDialogController* controller); // Called to create the account chooser dialog. Mocked in tests. virtual AutoSigninFirstRunPrompt* CreateAutoSigninPrompt( - PasswordDialogController* controller); + CredentialManagerDialogController* controller); // Check if |web_contents()| is attached to some Browser. Mocked in tests. virtual bool HasBrowserWindow() const; @@ -234,7 +234,7 @@ ManagePasswordsState passwords_data_; // The controller for the blocking dialogs. - std::unique_ptr<PasswordDialogControllerImpl> dialog_controller_; + std::unique_ptr<PasswordBaseDialogController> dialog_controller_; BubbleStatus bubble_status_;
diff --git a/chrome/browser/ui/passwords/manage_passwords_ui_controller_unittest.cc b/chrome/browser/ui/passwords/manage_passwords_ui_controller_unittest.cc index 0fefdeb4..97c1461 100644 --- a/chrome/browser/ui/passwords/manage_passwords_ui_controller_unittest.cc +++ b/chrome/browser/ui/passwords/manage_passwords_ui_controller_unittest.cc
@@ -15,10 +15,10 @@ #include "base/strings/utf_string_conversions.h" #include "base/test/metrics/histogram_tester.h" #include "build/build_config.h" +#include "chrome/browser/ui/passwords/credential_manager_dialog_controller.h" #include "chrome/browser/ui/passwords/manage_passwords_bubble_model.h" #include "chrome/browser/ui/passwords/manage_passwords_icon_view.h" #include "chrome/browser/ui/passwords/manage_passwords_ui_controller_mock.h" -#include "chrome/browser/ui/passwords/password_dialog_controller.h" #include "chrome/browser/ui/passwords/password_dialog_prompts.h" #include "chrome/browser/ui/passwords/passwords_model_delegate.h" #include "chrome/test/base/chrome_render_view_host_test_harness.h" @@ -102,9 +102,9 @@ } MOCK_METHOD1(CreateAccountChooser, - AccountChooserPrompt*(PasswordDialogController*)); + AccountChooserPrompt*(CredentialManagerDialogController*)); MOCK_METHOD1(CreateAutoSigninPrompt, - AutoSigninFirstRunPrompt*(PasswordDialogController*)); + AutoSigninFirstRunPrompt*(CredentialManagerDialogController*)); MOCK_CONST_METHOD0(HasBrowserWindow, bool()); MOCK_METHOD0(OnUpdateBubbleAndIconVisibility, void()); using ManagePasswordsUIController::DidFinishNavigation; @@ -669,7 +669,7 @@ std::vector<std::unique_ptr<autofill::PasswordForm>> local_credentials; local_credentials.emplace_back(new autofill::PasswordForm(test_local_form())); GURL origin("http://example.com"); - PasswordDialogController* dialog_controller = nullptr; + CredentialManagerDialogController* dialog_controller = nullptr; EXPECT_CALL(*controller(), CreateAccountChooser(_)) .WillOnce( DoAll(SaveArg<0>(&dialog_controller), Return(&dialog_prompt()))); @@ -703,7 +703,7 @@ local_credentials.emplace_back( new autofill::PasswordForm(test_federated_form())); GURL origin("http://example.com"); - PasswordDialogController* dialog_controller = nullptr; + CredentialManagerDialogController* dialog_controller = nullptr; EXPECT_CALL(*controller(), CreateAccountChooser(_)) .WillOnce( DoAll(SaveArg<0>(&dialog_controller), Return(&dialog_prompt()))); @@ -736,7 +736,7 @@ std::vector<std::unique_ptr<autofill::PasswordForm>> local_credentials; local_credentials.emplace_back(new autofill::PasswordForm(test_local_form())); GURL origin("http://example.com"); - PasswordDialogController* dialog_controller = nullptr; + CredentialManagerDialogController* dialog_controller = nullptr; EXPECT_CALL(*controller(), CreateAccountChooser(_)) .WillOnce( DoAll(SaveArg<0>(&dialog_controller), Return(&dialog_prompt()))); @@ -778,7 +778,7 @@ std::vector<std::unique_ptr<autofill::PasswordForm>> local_credentials; local_credentials.emplace_back(new autofill::PasswordForm(test_local_form())); GURL origin("http://example.com"); - PasswordDialogController* dialog_controller = nullptr; + CredentialManagerDialogController* dialog_controller = nullptr; EXPECT_CALL(*controller(), CreateAccountChooser(_)) .WillOnce( DoAll(SaveArg<0>(&dialog_controller), Return(&dialog_prompt())));
diff --git a/chrome/browser/ui/passwords/password_base_dialog_controller.h b/chrome/browser/ui/passwords/password_base_dialog_controller.h new file mode 100644 index 0000000..e898fb9 --- /dev/null +++ b/chrome/browser/ui/passwords/password_base_dialog_controller.h
@@ -0,0 +1,22 @@ +// Copyright 2019 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef CHROME_BROWSER_UI_PASSWORDS_PASSWORD_BASE_DIALOG_CONTROLLER_H_ +#define CHROME_BROWSER_UI_PASSWORDS_PASSWORD_BASE_DIALOG_CONTROLLER_H_ + +// A UI controller responsible for the credential manager and credentials +// leaked dialogs. +class PasswordBaseDialogController { + public: + PasswordBaseDialogController() = default; + virtual ~PasswordBaseDialogController() = default; + + // Returns true if account chooser dialog created by derived credential + // manager controller is active. + virtual bool IsShowingAccountChooser() const = 0; + + DISALLOW_COPY_AND_ASSIGN(PasswordBaseDialogController); +}; + +#endif // CHROME_BROWSER_UI_PASSWORDS_PASSWORD_BASE_DIALOG_CONTROLLER_H_
diff --git a/chrome/browser/ui/passwords/password_dialog_controller_mock.cc b/chrome/browser/ui/passwords/password_dialog_controller_mock.cc deleted file mode 100644 index 9f34a91..0000000 --- a/chrome/browser/ui/passwords/password_dialog_controller_mock.cc +++ /dev/null
@@ -1,11 +0,0 @@ -// Copyright 2016 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chrome/browser/ui/passwords/password_dialog_controller_mock.h" - -#include "components/autofill/core/common/password_form.h" - -PasswordDialogControllerMock::PasswordDialogControllerMock() {} - -PasswordDialogControllerMock::~PasswordDialogControllerMock() {}
diff --git a/chrome/browser/ui/passwords/password_dialog_controller_mock.h b/chrome/browser/ui/passwords/password_dialog_controller_mock.h deleted file mode 100644 index 90032c8..0000000 --- a/chrome/browser/ui/passwords/password_dialog_controller_mock.h +++ /dev/null
@@ -1,36 +0,0 @@ -// Copyright 2016 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROME_BROWSER_UI_PASSWORDS_PASSWORD_DIALOG_CONTROLLER_MOCK_H_ -#define CHROME_BROWSER_UI_PASSWORDS_PASSWORD_DIALOG_CONTROLLER_MOCK_H_ - -#include "base/macros.h" -#include "chrome/browser/ui/passwords/password_dialog_controller.h" -#include "testing/gmock/include/gmock/gmock.h" - -class PasswordDialogControllerMock : public PasswordDialogController { - public: - PasswordDialogControllerMock(); - ~PasswordDialogControllerMock() override; - - MOCK_CONST_METHOD0(GetLocalForms, const FormsVector&()); - MOCK_CONST_METHOD0(GetAccoutChooserTitle, base::string16()); - MOCK_CONST_METHOD0(ShouldShowSignInButton, bool()); - MOCK_CONST_METHOD0(GetAutoSigninPromoTitle, base::string16()); - MOCK_CONST_METHOD0(GetAutoSigninText, base::string16()); - MOCK_CONST_METHOD0(ShouldShowFooter, bool()); - MOCK_METHOD0(OnSmartLockLinkClicked, void()); - MOCK_METHOD2(OnChooseCredentials, void( - const autofill::PasswordForm& password_form, - password_manager::CredentialType credential_type)); - MOCK_METHOD0(OnSignInClicked, void()); - MOCK_METHOD0(OnAutoSigninOK, void()); - MOCK_METHOD0(OnAutoSigninTurnOff, void()); - MOCK_METHOD0(OnCloseDialog, void()); - - private: - DISALLOW_COPY_AND_ASSIGN(PasswordDialogControllerMock); -}; - -#endif // CHROME_BROWSER_UI_PASSWORDS_PASSWORD_DIALOG_CONTROLLER_MOCK_H_
diff --git a/chrome/browser/ui/passwords/password_dialog_prompts.h b/chrome/browser/ui/passwords/password_dialog_prompts.h index ef3e5cd..3f5d384b 100644 --- a/chrome/browser/ui/passwords/password_dialog_prompts.h +++ b/chrome/browser/ui/passwords/password_dialog_prompts.h
@@ -11,7 +11,7 @@ class WebContents; } -class PasswordDialogController; +class CredentialManagerDialogController; // The default inset from BubbleFrameView. const int kTitleTopInset = 12; @@ -50,10 +50,12 @@ // Factory function for AccountChooserPrompt on desktop platforms. AccountChooserPrompt* CreateAccountChooserPromptView( - PasswordDialogController* controller, content::WebContents* web_contents); + CredentialManagerDialogController* controller, + content::WebContents* web_contents); // Factory function for AutoSigninFirstRunPrompt on desktop platforms. AutoSigninFirstRunPrompt* CreateAutoSigninPromptView( - PasswordDialogController* controller, content::WebContents* web_contents); + CredentialManagerDialogController* controller, + content::WebContents* web_contents); #endif // CHROME_BROWSER_UI_PASSWORDS_PASSWORD_DIALOG_PROMPTS_H_
diff --git a/chrome/browser/ui/views/frame/browser_view.cc b/chrome/browser/ui/views/frame/browser_view.cc index 30c034a..fa1f2c6f 100644 --- a/chrome/browser/ui/views/frame/browser_view.cc +++ b/chrome/browser/ui/views/frame/browser_view.cc
@@ -1421,7 +1421,7 @@ send_tab_to_self::SendTabToSelfBubbleViewImpl* bubble = new send_tab_to_self::SendTabToSelfBubbleViewImpl( - GetLocationBarView(), gfx::Point(), web_contents, controller); + GetLocationBarView(), web_contents, controller); views::BubbleDialogDelegateView::CreateBubble(bubble); bubble->Show(send_tab_to_self::SendTabToSelfBubbleViewImpl::USER_GESTURE);
diff --git a/chrome/browser/ui/views/location_bar/zoom_bubble_view.cc b/chrome/browser/ui/views/location_bar/zoom_bubble_view.cc index a0edced6..9663484e 100644 --- a/chrome/browser/ui/views/location_bar/zoom_bubble_view.cc +++ b/chrome/browser/ui/views/location_bar/zoom_bubble_view.cc
@@ -186,7 +186,6 @@ // static void ZoomBubbleView::ShowBubble(content::WebContents* web_contents, - const gfx::Point& anchor_point, DisplayReason reason) { Browser* browser = chrome::FindBrowserWithWebContents(web_contents); // |web_contents| could have been unloaded if a tab gets closed and a mouse @@ -206,8 +205,8 @@ ImmersiveModeController* immersive_mode_controller = GetImmersiveModeControllerForBrowser(browser); - zoom_bubble_ = new ZoomBubbleView(anchor_view, anchor_point, web_contents, - reason, immersive_mode_controller); + zoom_bubble_ = new ZoomBubbleView(anchor_view, web_contents, reason, + immersive_mode_controller); const extensions::ExtensionZoomRequestClient* client = GetExtensionZoomRequestClient(web_contents); @@ -286,11 +285,10 @@ ZoomBubbleView::ZoomBubbleView( views::View* anchor_view, - const gfx::Point& anchor_point, content::WebContents* web_contents, DisplayReason reason, ImmersiveModeController* immersive_mode_controller) - : LocationBarBubbleDelegateView(anchor_view, anchor_point, web_contents), + : LocationBarBubbleDelegateView(anchor_view, gfx::Point(), web_contents), auto_close_duration_(kBubbleCloseDelayDefault), auto_close_(reason == AUTOMATIC), immersive_mode_controller_(immersive_mode_controller),
diff --git a/chrome/browser/ui/views/location_bar/zoom_bubble_view.h b/chrome/browser/ui/views/location_bar/zoom_bubble_view.h index 4cf9035..f88f3d6 100644 --- a/chrome/browser/ui/views/location_bar/zoom_bubble_view.h +++ b/chrome/browser/ui/views/location_bar/zoom_bubble_view.h
@@ -36,7 +36,6 @@ // Shows the bubble and automatically closes it after a short time period if // |reason| is AUTOMATIC. static void ShowBubble(content::WebContents* web_contents, - const gfx::Point& anchor_point, DisplayReason reason); // If the bubble is being shown for the given |web_contents|, refreshes it. @@ -82,12 +81,11 @@ std::unique_ptr<const extensions::IconImage> icon_image; }; - // Constructs ZoomBubbleView. Anchors the bubble to |anchor_view| when it is - // not nullptr or alternatively, to |anchor_point|. The bubble will auto-close - // when |reason| is AUTOMATIC. If |immersive_mode_controller_| is present, the - // bubble will auto-close when the top-of-window views are revealed. + // Constructs ZoomBubbleView. Anchors the bubble to |anchor_view|, which must + // not be nullptr. The bubble will auto-close when |reason| is AUTOMATIC. If + // |immersive_mode_controller_| is present, the bubble will auto-close when + // the top-of-window views are revealed. ZoomBubbleView(views::View* anchor_view, - const gfx::Point& anchor_point, content::WebContents* web_contents, DisplayReason reason, ImmersiveModeController* immersive_mode_controller);
diff --git a/chrome/browser/ui/views/location_bar/zoom_bubble_view_browsertest.cc b/chrome/browser/ui/views/location_bar/zoom_bubble_view_browsertest.cc index 605be55e..6bd47c4 100644 --- a/chrome/browser/ui/views/location_bar/zoom_bubble_view_browsertest.cc +++ b/chrome/browser/ui/views/location_bar/zoom_bubble_view_browsertest.cc
@@ -35,8 +35,7 @@ void ShowInActiveTab(Browser* browser) { content::WebContents* web_contents = browser->tab_strip_model()->GetActiveWebContents(); - ZoomBubbleView::ShowBubble(web_contents, gfx::Point(), - ZoomBubbleView::USER_GESTURE); + ZoomBubbleView::ShowBubble(web_contents, ZoomBubbleView::USER_GESTURE); EXPECT_TRUE(ZoomBubbleView::GetZoomBubble()); } @@ -53,8 +52,7 @@ content::WebContents* web_contents = browser_view->GetActiveWebContents(); // The zoom bubble should be anchored when not in fullscreen. - ZoomBubbleView::ShowBubble(web_contents, gfx::Point(), - ZoomBubbleView::AUTOMATIC); + ZoomBubbleView::ShowBubble(web_contents, ZoomBubbleView::AUTOMATIC); ASSERT_TRUE(ZoomBubbleView::GetZoomBubble()); const ZoomBubbleView* zoom_bubble = ZoomBubbleView::GetZoomBubble(); EXPECT_TRUE(zoom_bubble->GetAnchorView()); @@ -76,8 +74,7 @@ // The bubble should not be anchored when it is shown in non-immersive // fullscreen. - ZoomBubbleView::ShowBubble(web_contents, gfx::Point(), - ZoomBubbleView::AUTOMATIC); + ZoomBubbleView::ShowBubble(web_contents, ZoomBubbleView::AUTOMATIC); ASSERT_TRUE(ZoomBubbleView::GetZoomBubble()); zoom_bubble = ZoomBubbleView::GetZoomBubble(); EXPECT_FALSE(zoom_bubble->GetAnchorView()); @@ -115,8 +112,7 @@ // The zoom bubble should not be anchored when it is shown in immersive // fullscreen and the top-of-window views are not revealed. - ZoomBubbleView::ShowBubble(web_contents, gfx::Point(), - ZoomBubbleView::AUTOMATIC); + ZoomBubbleView::ShowBubble(web_contents, ZoomBubbleView::AUTOMATIC); ASSERT_TRUE(ZoomBubbleView::GetZoomBubble()); const ZoomBubbleView* zoom_bubble = ZoomBubbleView::GetZoomBubble(); EXPECT_FALSE(zoom_bubble->GetAnchorView()); @@ -130,8 +126,7 @@ // The zoom bubble should be anchored when it is shown in immersive fullscreen // and the top-of-window views are revealed. - ZoomBubbleView::ShowBubble(web_contents, gfx::Point(), - ZoomBubbleView::AUTOMATIC); + ZoomBubbleView::ShowBubble(web_contents, ZoomBubbleView::AUTOMATIC); zoom_bubble = ZoomBubbleView::GetZoomBubble(); ASSERT_TRUE(zoom_bubble); EXPECT_TRUE(zoom_bubble->GetAnchorView()); @@ -160,13 +155,11 @@ content::WebContents* web_contents = browser()->tab_strip_model()->GetActiveWebContents(); - ZoomBubbleView::ShowBubble(web_contents, gfx::Point(), - ZoomBubbleView::AUTOMATIC); + ZoomBubbleView::ShowBubble(web_contents, ZoomBubbleView::AUTOMATIC); // Close the current tab and try opening the zoom bubble with stale // |web_contents|. chrome::CloseTab(browser()); - ZoomBubbleView::ShowBubble(web_contents, gfx::Point(), - ZoomBubbleView::AUTOMATIC); + ZoomBubbleView::ShowBubble(web_contents, ZoomBubbleView::AUTOMATIC); } // Ensure a tab switch closes the bubble. @@ -342,8 +335,7 @@ IN_PROC_BROWSER_TEST_F(ZoomBubbleBrowserTest, FocusPreventsClose) { content::WebContents* web_contents = browser()->tab_strip_model()->GetActiveWebContents(); - ZoomBubbleView::ShowBubble(web_contents, gfx::Point(), - ZoomBubbleView::AUTOMATIC); + ZoomBubbleView::ShowBubble(web_contents, ZoomBubbleView::AUTOMATIC); ZoomBubbleView* bubble = ZoomBubbleView::GetZoomBubble(); ASSERT_TRUE(bubble); // |auto_close_timer_| is running so that the bubble is closed at the end.
diff --git a/chrome/browser/ui/views/native_file_system/native_file_system_permission_view_browsertest.cc b/chrome/browser/ui/views/native_file_system/native_file_system_permission_view_browsertest.cc index 1ba691a2..d7ff53e 100644 --- a/chrome/browser/ui/views/native_file_system/native_file_system_permission_view_browsertest.cc +++ b/chrome/browser/ui/views/native_file_system/native_file_system_permission_view_browsertest.cc
@@ -30,10 +30,7 @@ NOTREACHED() << "Unimplemented test: " << name; } widget_ = NativeFileSystemPermissionView::ShowDialog( - url::Origin::Create(GURL("https://" - "totallynotgooglechromelabbutverylongurlthatdo" - "esnotfitononeline.github.io//")), - path, is_directory, + kTestOrigin, path, is_directory, base::BindLambdaForTesting([&](PermissionAction result) { callback_called_ = true; callback_result_ = result;
diff --git a/chrome/browser/ui/views/native_file_system/native_file_system_usage_bubble_view.cc b/chrome/browser/ui/views/native_file_system/native_file_system_usage_bubble_view.cc index 8396cd2..9eef3c6c 100644 --- a/chrome/browser/ui/views/native_file_system/native_file_system_usage_bubble_view.cc +++ b/chrome/browser/ui/views/native_file_system/native_file_system_usage_bubble_view.cc
@@ -261,8 +261,8 @@ } usage.readable_directories = readable_directories; - bubble_ = new NativeFileSystemUsageBubbleView( - anchor_view, gfx::Point(), web_contents, origin, std::move(usage)); + bubble_ = new NativeFileSystemUsageBubbleView(anchor_view, web_contents, + origin, std::move(usage)); bubble_->SetHighlightedButton(anchor_view->GetPageActionIconView( PageActionIconType::kNativeFileSystemAccess)); @@ -285,11 +285,10 @@ NativeFileSystemUsageBubbleView::NativeFileSystemUsageBubbleView( views::View* anchor_view, - const gfx::Point& anchor_point, content::WebContents* web_contents, const url::Origin& origin, Usage usage) - : LocationBarBubbleDelegateView(anchor_view, anchor_point, web_contents), + : LocationBarBubbleDelegateView(anchor_view, gfx::Point(), web_contents), origin_(origin), usage_(std::move(usage)), writable_paths_model_(usage_.writable_files, usage_.writable_directories),
diff --git a/chrome/browser/ui/views/native_file_system/native_file_system_usage_bubble_view.h b/chrome/browser/ui/views/native_file_system/native_file_system_usage_bubble_view.h index 941fc9ae..41d2ff2 100644 --- a/chrome/browser/ui/views/native_file_system/native_file_system_usage_bubble_view.h +++ b/chrome/browser/ui/views/native_file_system/native_file_system_usage_bubble_view.h
@@ -56,7 +56,6 @@ }; NativeFileSystemUsageBubbleView(views::View* anchor_view, - const gfx::Point& anchor_point, content::WebContents* web_contents, const url::Origin& origin, Usage usage);
diff --git a/chrome/browser/ui/views/page_action/zoom_view.cc b/chrome/browser/ui/views/page_action/zoom_view.cc index 1bbfd0f..0e61188a 100644 --- a/chrome/browser/ui/views/page_action/zoom_view.cc +++ b/chrome/browser/ui/views/page_action/zoom_view.cc
@@ -80,8 +80,7 @@ SetVisible(true); if (can_show_bubble) { - ZoomBubbleView::ShowBubble(web_contents, gfx::Point(), - ZoomBubbleView::AUTOMATIC); + ZoomBubbleView::ShowBubble(web_contents, ZoomBubbleView::AUTOMATIC); } else { ZoomBubbleView::RefreshBubbleIfShowing(web_contents); } @@ -95,8 +94,7 @@ } void ZoomView::OnExecuting(PageActionIconView::ExecuteSource source) { - ZoomBubbleView::ShowBubble(GetWebContents(), gfx::Point(), - ZoomBubbleView::USER_GESTURE); + ZoomBubbleView::ShowBubble(GetWebContents(), ZoomBubbleView::USER_GESTURE); } views::BubbleDialogDelegateView* ZoomView::GetBubble() const {
diff --git a/chrome/browser/ui/views/passwords/account_chooser_dialog_view.cc b/chrome/browser/ui/views/passwords/account_chooser_dialog_view.cc index c6c885c..b79a64c 100644 --- a/chrome/browser/ui/views/passwords/account_chooser_dialog_view.cc +++ b/chrome/browser/ui/views/passwords/account_chooser_dialog_view.cc
@@ -10,8 +10,8 @@ #include "build/build_config.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/ui/browser_dialogs.h" +#include "chrome/browser/ui/passwords/credential_manager_dialog_controller.h" #include "chrome/browser/ui/passwords/manage_passwords_view_utils.h" -#include "chrome/browser/ui/passwords/password_dialog_controller.h" #include "chrome/browser/ui/views/chrome_layout_provider.h" #include "chrome/browser/ui/views/chrome_typography.h" #include "chrome/browser/ui/views/passwords/credentials_item_view.h" @@ -41,7 +41,7 @@ // Creates a list view of credentials in |forms|. views::ScrollView* CreateCredentialsView( - const PasswordDialogController::FormsVector& forms, + const CredentialManagerDialogController::FormsVector& forms, views::ButtonListener* button_listener, network::mojom::URLLoaderFactory* loader_factory) { auto list_view = std::make_unique<views::View>(); @@ -74,7 +74,7 @@ } // namespace AccountChooserDialogView::AccountChooserDialogView( - PasswordDialogController* controller, + CredentialManagerDialogController* controller, content::WebContents* web_contents) : controller_(controller), web_contents_(web_contents), @@ -179,6 +179,7 @@ } AccountChooserPrompt* CreateAccountChooserPromptView( - PasswordDialogController* controller, content::WebContents* web_contents) { + CredentialManagerDialogController* controller, + content::WebContents* web_contents) { return new AccountChooserDialogView(controller, web_contents); }
diff --git a/chrome/browser/ui/views/passwords/account_chooser_dialog_view.h b/chrome/browser/ui/views/passwords/account_chooser_dialog_view.h index 88e790b..53c22a30 100644 --- a/chrome/browser/ui/views/passwords/account_chooser_dialog_view.h +++ b/chrome/browser/ui/views/passwords/account_chooser_dialog_view.h
@@ -14,13 +14,13 @@ class WebContents; } -class PasswordDialogController; +class CredentialManagerDialogController; class AccountChooserDialogView : public views::BubbleDialogDelegateView, public views::ButtonListener, public AccountChooserPrompt { public: - AccountChooserDialogView(PasswordDialogController* controller, + AccountChooserDialogView(CredentialManagerDialogController* controller, content::WebContents* web_contents); ~AccountChooserDialogView() override; @@ -48,7 +48,7 @@ void InitWindow(); // A weak pointer to the controller. - PasswordDialogController* controller_; + CredentialManagerDialogController* controller_; content::WebContents* web_contents_; // The "Sign in" button is shown for one credential only. The variable is // cached because the framework can call GetDialogButtons() after the
diff --git a/chrome/browser/ui/views/passwords/auto_signin_first_run_dialog_view.cc b/chrome/browser/ui/views/passwords/auto_signin_first_run_dialog_view.cc index 01e9f88..67298f2 100644 --- a/chrome/browser/ui/views/passwords/auto_signin_first_run_dialog_view.cc +++ b/chrome/browser/ui/views/passwords/auto_signin_first_run_dialog_view.cc
@@ -6,7 +6,7 @@ #include "build/build_config.h" #include "chrome/browser/ui/browser_dialogs.h" -#include "chrome/browser/ui/passwords/password_dialog_controller.h" +#include "chrome/browser/ui/passwords/credential_manager_dialog_controller.h" #include "chrome/browser/ui/views/chrome_layout_provider.h" #include "chrome/browser/ui/views/chrome_typography.h" #include "chrome/grit/generated_resources.h" @@ -19,7 +19,7 @@ #include "ui/views/widget/widget.h" AutoSigninFirstRunDialogView::AutoSigninFirstRunDialogView( - PasswordDialogController* controller, + CredentialManagerDialogController* controller, content::WebContents* web_contents) : controller_(controller), web_contents_(web_contents) { chrome::RecordDialogCreation(chrome::DialogIdentifier::AUTO_SIGNIN_FIRST_RUN); @@ -106,6 +106,7 @@ } AutoSigninFirstRunPrompt* CreateAutoSigninPromptView( - PasswordDialogController* controller, content::WebContents* web_contents) { + CredentialManagerDialogController* controller, + content::WebContents* web_contents) { return new AutoSigninFirstRunDialogView(controller, web_contents); }
diff --git a/chrome/browser/ui/views/passwords/auto_signin_first_run_dialog_view.h b/chrome/browser/ui/views/passwords/auto_signin_first_run_dialog_view.h index 4979f3a..ce81195 100644 --- a/chrome/browser/ui/views/passwords/auto_signin_first_run_dialog_view.h +++ b/chrome/browser/ui/views/passwords/auto_signin_first_run_dialog_view.h
@@ -12,7 +12,7 @@ class AutoSigninFirstRunDialogView : public views::DialogDelegateView, public AutoSigninFirstRunPrompt { public: - AutoSigninFirstRunDialogView(PasswordDialogController* controller, + AutoSigninFirstRunDialogView(CredentialManagerDialogController* controller, content::WebContents* web_contents); ~AutoSigninFirstRunDialogView() override; @@ -36,7 +36,7 @@ void InitWindow(); // A weak pointer to the controller. - PasswordDialogController* controller_; + CredentialManagerDialogController* controller_; content::WebContents* const web_contents_; DISALLOW_COPY_AND_ASSIGN(AutoSigninFirstRunDialogView);
diff --git a/chrome/browser/ui/views/passwords/password_dialog_view_browsertest.cc b/chrome/browser/ui/views/passwords/password_dialog_view_browsertest.cc index 3894268..4821ffe 100644 --- a/chrome/browser/ui/views/passwords/password_dialog_view_browsertest.cc +++ b/chrome/browser/ui/views/passwords/password_dialog_view_browsertest.cc
@@ -46,9 +46,9 @@ void OnDialogHidden() override; AccountChooserPrompt* CreateAccountChooser( - PasswordDialogController* controller) override; + CredentialManagerDialogController* controller) override; AutoSigninFirstRunPrompt* CreateAutoSigninPrompt( - PasswordDialogController* controller) override; + CredentialManagerDialogController* controller) override; AccountChooserDialogView* current_account_chooser() const { return static_cast<AccountChooserDialogView*>(current_account_chooser_); @@ -87,7 +87,7 @@ } AccountChooserPrompt* TestManagePasswordsUIController::CreateAccountChooser( - PasswordDialogController* controller) { + CredentialManagerDialogController* controller) { current_account_chooser_ = ManagePasswordsUIController::CreateAccountChooser(controller); return current_account_chooser_; @@ -95,7 +95,7 @@ AutoSigninFirstRunPrompt* TestManagePasswordsUIController::CreateAutoSigninPrompt( - PasswordDialogController* controller) { + CredentialManagerDialogController* controller) { current_autosignin_prompt_ = ManagePasswordsUIController::CreateAutoSigninPrompt(controller); return current_autosignin_prompt_;
diff --git a/chrome/browser/ui/views/payments/payment_request_completion_status_metrics_browsertest.cc b/chrome/browser/ui/views/payments/payment_request_completion_status_metrics_browsertest.cc index a68847552..5f75ed4 100644 --- a/chrome/browser/ui/views/payments/payment_request_completion_status_metrics_browsertest.cc +++ b/chrome/browser/ui/views/payments/payment_request_completion_status_metrics_browsertest.cc
@@ -66,6 +66,12 @@ // Complete the Payment Request. PayWithCreditCardAndWait(base::ASCIIToUTF16("123")); + histogram_tester.ExpectTotalCount("PaymentRequest.TimeToCheckout.Completed", + 1); + histogram_tester.ExpectTotalCount( + "PaymentRequest.TimeToCheckout.Completed.Shown", 1); + histogram_tester.ExpectTotalCount( + "PaymentRequest.TimeToCheckout.Completed.Shown.BasicCard", 1); histogram_tester.ExpectUniqueSample( "PaymentRequest.TransactionAmount.Completed", kRegularTransaction, 1); @@ -121,6 +127,8 @@ histogram_tester.ExpectUniqueSample( "PaymentRequest.CheckoutFunnel.Aborted", JourneyLogger::ABORT_REASON_MERCHANT_NAVIGATION, 1); + histogram_tester.ExpectTotalCount( + "PaymentRequest.TimeToCheckout.OtherAborted", 1); // Make sure PaymentRequest.TransactionAmount.Completed is not logged // since the request got aborted. @@ -295,6 +303,11 @@ "PaymentRequest.CheckoutFunnel.Aborted", JourneyLogger::ABORT_REASON_USER_NAVIGATION, 1); + histogram_tester.ExpectTotalCount("PaymentRequest.TimeToCheckout.UserAborted", + 1); + histogram_tester.ExpectTotalCount( + "PaymentRequest.TimeToCheckout.UserAborted.Shown", 1); + // Make sure PaymentRequest.TransactionAmount.Completed is not logged // since the request got aborted. histogram_tester.ExpectTotalCount(
diff --git a/chrome/browser/ui/views/payments/payment_request_payment_app_browsertest.cc b/chrome/browser/ui/views/payments/payment_request_payment_app_browsertest.cc index 82a86cd..960bd94b6 100644 --- a/chrome/browser/ui/views/payments/payment_request_payment_app_browsertest.cc +++ b/chrome/browser/ui/views/payments/payment_request_payment_app_browsertest.cc
@@ -3,6 +3,7 @@ // found in the LICENSE file. #include "base/macros.h" +#include "base/test/metrics/histogram_tester.h" #include "base/test/scoped_feature_list.h" #include "chrome/browser/content_settings/host_content_settings_map_factory.h" #include "chrome/browser/permissions/permission_request_manager.h" @@ -469,6 +470,7 @@ } IN_PROC_BROWSER_TEST_F(PaymentRequestPaymentAppTest, SkipUIEnabledWithBobPay) { + base::HistogramTester histogram_tester; base::test::ScopedFeatureList features; features.InitWithFeatures( { @@ -496,6 +498,13 @@ WaitForObservedEvent(); ExpectBodyContains({"bobpay.com"}); + + histogram_tester.ExpectTotalCount("PaymentRequest.TimeToCheckout.Completed", + 1); + histogram_tester.ExpectTotalCount( + "PaymentRequest.TimeToCheckout.Completed.SkippedShow", 1); + histogram_tester.ExpectTotalCount( + "PaymentRequest.TimeToCheckout.Completed.SkippedShow.Other", 1); } }
diff --git a/chrome/browser/ui/views/relaunch_notification/relaunch_recommended_bubble_view.cc b/chrome/browser/ui/views/relaunch_notification/relaunch_recommended_bubble_view.cc index 5a065fb..9a5f3227 100644 --- a/chrome/browser/ui/views/relaunch_notification/relaunch_recommended_bubble_view.cc +++ b/chrome/browser/ui/views/relaunch_notification/relaunch_recommended_bubble_view.cc
@@ -51,7 +51,7 @@ ->toolbar_button_provider() ->GetAppMenuButton(); auto* bubble_view = new RelaunchRecommendedBubbleView( - anchor_button, gfx::Point(), detection_time, std::move(on_accept)); + anchor_button, detection_time, std::move(on_accept)); bubble_view->SetArrow(views::BubbleBorder::TOP_RIGHT); #if defined(OS_MACOSX) @@ -169,10 +169,9 @@ // title needs to be updated (e.g., from "2 days" to "3 days"). RelaunchRecommendedBubbleView::RelaunchRecommendedBubbleView( views::Button* anchor_button, - const gfx::Point& anchor_point, base::Time detection_time, base::RepeatingClosure on_accept) - : LocationBarBubbleDelegateView(anchor_button, anchor_point, nullptr), + : LocationBarBubbleDelegateView(anchor_button, gfx::Point(), nullptr), on_accept_(std::move(on_accept)), body_label_(nullptr), relaunch_recommended_timer_(
diff --git a/chrome/browser/ui/views/relaunch_notification/relaunch_recommended_bubble_view.h b/chrome/browser/ui/views/relaunch_notification/relaunch_recommended_bubble_view.h index 2eebc31..267ad08 100644 --- a/chrome/browser/ui/views/relaunch_notification/relaunch_recommended_bubble_view.h +++ b/chrome/browser/ui/views/relaunch_notification/relaunch_recommended_bubble_view.h
@@ -52,7 +52,6 @@ private: RelaunchRecommendedBubbleView(views::Button* anchor_button, - const gfx::Point& anchor_point, base::Time detection_time, base::RepeatingClosure on_accept);
diff --git a/chrome/browser/ui/views/send_tab_to_self/send_tab_to_self_bubble_view_impl.cc b/chrome/browser/ui/views/send_tab_to_self/send_tab_to_self_bubble_view_impl.cc index 65fd453..542d961 100644 --- a/chrome/browser/ui/views/send_tab_to_self/send_tab_to_self_bubble_view_impl.cc +++ b/chrome/browser/ui/views/send_tab_to_self/send_tab_to_self_bubble_view_impl.cc
@@ -38,10 +38,9 @@ SendTabToSelfBubbleViewImpl::SendTabToSelfBubbleViewImpl( views::View* anchor_view, - const gfx::Point& anchor_point, content::WebContents* web_contents, SendTabToSelfBubbleController* controller) - : LocationBarBubbleDelegateView(anchor_view, anchor_point, web_contents), + : LocationBarBubbleDelegateView(anchor_view, gfx::Point(), web_contents), web_contents_(web_contents), controller_(controller) { DCHECK(controller);
diff --git a/chrome/browser/ui/views/send_tab_to_self/send_tab_to_self_bubble_view_impl.h b/chrome/browser/ui/views/send_tab_to_self/send_tab_to_self_bubble_view_impl.h index bf680b6..1e3560b9 100644 --- a/chrome/browser/ui/views/send_tab_to_self/send_tab_to_self_bubble_view_impl.h +++ b/chrome/browser/ui/views/send_tab_to_self/send_tab_to_self_bubble_view_impl.h
@@ -39,7 +39,6 @@ public: // Bubble will be anchored to |anchor_view|. SendTabToSelfBubbleViewImpl(views::View* anchor_view, - const gfx::Point& anchor_point, content::WebContents* web_contents, SendTabToSelfBubbleController* controller);
diff --git a/chrome/browser/ui/views/send_tab_to_self/send_tab_to_self_bubble_view_impl_unittest.cc b/chrome/browser/ui/views/send_tab_to_self/send_tab_to_self_bubble_view_impl_unittest.cc index c23dda72..f724600 100644 --- a/chrome/browser/ui/views/send_tab_to_self/send_tab_to_self_bubble_view_impl_unittest.cc +++ b/chrome/browser/ui/views/send_tab_to_self/send_tab_to_self_bubble_view_impl_unittest.cc
@@ -33,11 +33,9 @@ class SendTabToSelfBubbleViewImplMock : public SendTabToSelfBubbleViewImpl { public: SendTabToSelfBubbleViewImplMock(views::View* anchor_view, - const gfx::Point& anchor_point, content::WebContents* web_contents, SendTabToSelfBubbleController* controller) : SendTabToSelfBubbleViewImpl(anchor_view, - anchor_point, web_contents, controller) {} ~SendTabToSelfBubbleViewImplMock() override = default; @@ -65,8 +63,7 @@ profile_.reset(new TestingProfile); controller_ = std::make_unique<SendTabToSelfBubbleControllerMock>(); bubble_ = std::make_unique<SendTabToSelfBubbleViewImplMock>( - anchor_widget_->GetContentsView(), gfx::Point(), nullptr, - controller_.get()); + anchor_widget_->GetContentsView(), nullptr, controller_.get()); } void TearDown() override {
diff --git a/chrome/browser/ui/views/tab_sharing/tab_sharing_ui_views.cc b/chrome/browser/ui/views/tab_sharing/tab_sharing_ui_views.cc index 1a85602..73a59fb7 100644 --- a/chrome/browser/ui/views/tab_sharing/tab_sharing_ui_views.cc +++ b/chrome/browser/ui/views/tab_sharing/tab_sharing_ui_views.cc
@@ -30,6 +30,7 @@ namespace { +#if !defined(OS_MACOSX) const int kContentsBorderThickness = 10; const float kContentsBorderOpacity = 0.24; const SkColor kContentsBorderColor = gfx::kGoogleBlue500; @@ -68,8 +69,11 @@ browser_view->set_contents_border_widget(widget); } +#endif void SetContentsBorderVisible(content::WebContents* contents, bool visible) { + if (!contents) + return; Browser* browser = chrome::FindBrowserWithWebContents(contents); if (!browser) return; @@ -108,7 +112,10 @@ media_id.web_contents_id.main_render_frame_id)); shared_tab_name_ = GetTabName(shared_tab_); profile_ = ProfileManager::GetLastUsedProfileAllowedByPolicy(); +#if !defined(OS_MACOSX) + // TODO(https://crbug.com/991896) fix contents border on Mac. InitContentsBorderWidget(shared_tab_); +#endif } TabSharingUIViews::~TabSharingUIViews() {
diff --git a/chrome/browser/ui/webui/devtools_ui.cc b/chrome/browser/ui/webui/devtools_ui.cc index 972657d..471f7b1 100644 --- a/chrome/browser/ui/webui/devtools_ui.cc +++ b/chrome/browser/ui/webui/devtools_ui.cc
@@ -369,8 +369,12 @@ const std::string& path, const GotDataCallback& callback) { base::FilePath inspector_debug_dir; - if (!base::PathService::Get(chrome::DIR_INSPECTOR_DEBUG, - &inspector_debug_dir)) { + base::CommandLine* command_line = base::CommandLine::ForCurrentProcess(); + if (command_line->HasSwitch(switches::kCustomDevtoolsFrontend)) { + inspector_debug_dir = + command_line->GetSwitchValuePath(switches::kCustomDevtoolsFrontend); + } else if (!base::PathService::Get(chrome::DIR_INSPECTOR_DEBUG, + &inspector_debug_dir)) { callback.Run(CreateNotFoundResponse()); return; }
diff --git a/chrome/browser/ui/webui/settings/people_handler.cc b/chrome/browser/ui/webui/settings/people_handler.cc index 6780ce8..66d6ca6 100644 --- a/chrome/browser/ui/webui/settings/people_handler.cc +++ b/chrome/browser/ui/webui/settings/people_handler.cc
@@ -303,6 +303,10 @@ "SyncSetupGetSyncStatus", base::BindRepeating(&PeopleHandler::HandleGetSyncStatus, base::Unretained(this))); + web_ui()->RegisterMessageCallback( + "SyncPrefsDispatch", + base::BindRepeating(&PeopleHandler::HandleSyncPrefsDispatch, + base::Unretained(this))); #if defined(OS_CHROMEOS) web_ui()->RegisterMessageCallback( "AttemptUserExit", @@ -850,6 +854,11 @@ ResolveJavascriptCallback(*callback_id, *GetSyncStatusDictionary()); } +void PeopleHandler::HandleSyncPrefsDispatch(const base::ListValue* args) { + AllowJavascript(); + PushSyncPrefs(); +} + void PeopleHandler::CloseSyncSetup() { // Stop a timer to handle timeout in waiting for checking network connection. engine_start_timer_.reset();
diff --git a/chrome/browser/ui/webui/settings/people_handler.h b/chrome/browser/ui/webui/settings/people_handler.h index 83cd891..51e9195 100644 --- a/chrome/browser/ui/webui/settings/people_handler.h +++ b/chrome/browser/ui/webui/settings/people_handler.h
@@ -176,6 +176,7 @@ void HandleSetEncryption(const base::ListValue* args); void HandleShowSetupUI(const base::ListValue* args); void HandleAttemptUserExit(const base::ListValue* args); + void HandleSyncPrefsDispatch(const base::ListValue* args); #if defined(OS_CHROMEOS) void HandleRequestPinLoginState(const base::ListValue* args); #endif
diff --git a/chrome/test/BUILD.gn b/chrome/test/BUILD.gn index 04a5a129..f60e308 100644 --- a/chrome/test/BUILD.gn +++ b/chrome/test/BUILD.gn
@@ -3731,8 +3731,8 @@ "../browser/ui/omnibox/chrome_omnibox_navigation_observer_unittest.cc", "../browser/ui/omnibox/clipboard_utils_unittest.cc", "../browser/ui/page_info/permission_menu_model_unittest.cc", + "../browser/ui/passwords/credential_manager_dialog_controller_impl_unittest.cc", "../browser/ui/passwords/manage_passwords_bubble_model_unittest.cc", - "../browser/ui/passwords/password_dialog_controller_impl_unittest.cc", "../browser/ui/recently_audible_helper_unittest.cc", "../browser/ui/search/ntp_user_data_logger_unittest.cc", "../browser/ui/search/search_ipc_router_policy_unittest.cc",
diff --git a/chrome/test/android/javatests/src/org/chromium/chrome/test/util/browser/signin/SigninTestUtil.java b/chrome/test/android/javatests/src/org/chromium/chrome/test/util/browser/signin/SigninTestUtil.java index b7a2052..a7622d74 100644 --- a/chrome/test/android/javatests/src/org/chromium/chrome/test/util/browser/signin/SigninTestUtil.java +++ b/chrome/test/android/javatests/src/org/chromium/chrome/test/util/browser/signin/SigninTestUtil.java
@@ -120,7 +120,7 @@ AccountIdProvider.setInstanceForTest(new AccountIdProvider() { @Override public String getAccountId(String accountName) { - return "gaia-id-" + accountName; + return "gaia-id-" + accountName.replace("@", "_at_"); } @Override
diff --git a/chrome/test/chromedriver/js/get_element_location.js b/chrome/test/chromedriver/js/get_element_location.js index 7c114c23..7e85c06d 100644 --- a/chrome/test/chromedriver/js/get_element_location.js +++ b/chrome/test/chromedriver/js/get_element_location.js
@@ -2,25 +2,45 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -function getInViewPoint(rect) { - var left = Math.max(0, rect.left); - var right = Math.min(window.innerWidth, rect.right); - var top = Math.max(0, rect.top); - var bottom = Math.min(window.innerHeight, rect.bottom); - - var x = 0.5 * (left + right); - var y = 0.5 * (top + bottom); - - return [x, y, rect.left, rect.top]; +function getParentRect(element) { + var parent = element.parentElement; + var parentRect = parent.getClientRects()[0]; + return parentRect; } -function inView(element) { +function getInViewPoint(element) { var rectangles = element.getClientRects(); if (rectangles.length === 0) { return false; } - var elementPoint = getInViewPoint(rectangles[0]); + var rect = rectangles[0]; + var left = Math.max(0, rect.left); + var right = Math.min(window.innerWidth, rect.right); + var top = Math.max(0, rect.top); + var bottom = Math.min(window.innerHeight, rect.bottom); + + // Find the view boundry of the element by checking itself and all of its + // ancestor's boundry. + while (element.parentElement != null && + element.parentElement != document.body && + element.parentElement.getClientRects().length > 0) { + var parentRect = getParentRect(element); + left = Math.max(left, parentRect.left); + right = Math.min(right, parentRect.right); + top = Math.max(top, parentRect.top); + bottom = Math.min(bottom, parentRect.bottom); + element = element.parentElement; + } + + var x = 0.5 * (left + right); + var y = 0.5 * (top + bottom); + + return [x, y, left, top]; +} + +function inView(element) { + var elementPoint = getInViewPoint(element); if (elementPoint[0] <= 0 || elementPoint[1] <= 0 || elementPoint[0] >= window.innerWidth || elementPoint[1] >= window.innerHeight || @@ -50,8 +70,8 @@ e.code = 60; throw e; } - var rect = clientRects[0]; - var elementPoint = getInViewPoint(rect); + + var elementPoint = getInViewPoint(element); if (center) { return { 'x': elementPoint[0],
diff --git a/chrome/test/data/webui/settings/cr_settings_browsertest.js b/chrome/test/data/webui/settings/cr_settings_browsertest.js index 073ee56..c6991f9f 100644 --- a/chrome/test/data/webui/settings/cr_settings_browsertest.js +++ b/chrome/test/data/webui/settings/cr_settings_browsertest.js
@@ -365,6 +365,7 @@ '../test_browser_proxy.js', 'passwords_and_autofill_fake_data.js', 'passwords_section_test.js', + 'sync_test_util.js', 'test_password_manager_proxy.js', '../test_util.js', ]), @@ -745,6 +746,7 @@ /** @override */ extraLibraries: CrSettingsBrowserTest.prototype.extraLibraries.concat([ '../test_browser_proxy.js', + 'sync_test_util.js', 'test_sync_browser_proxy.js', 'test_util.js', 'people_page_sync_controls_test.js',
diff --git a/chrome/test/data/webui/settings/passwords_section_test.js b/chrome/test/data/webui/settings/passwords_section_test.js index eb289d7..e22d606c 100644 --- a/chrome/test/data/webui/settings/passwords_section_test.js +++ b/chrome/test/data/webui/settings/passwords_section_test.js
@@ -844,5 +844,36 @@ {status: chrome.passwordsPrivate.ExportProgressStatus.SUCCEEDED}); return wait; }); + + test('hideLinkToPasswordManagerWhenEncrypted', function() { + const passwordsSection = + elementFactory.createPasswordsSection(passwordManager, [], []); + const prefs = sync_test_util.getSyncAllPrefs(); + prefs.encryptAllData = true; + cr.webUIListenerCallback('sync-prefs-changed', prefs); + sync_test_util.simulateSyncStatus({signedIn: true}); + Polymer.dom.flush(); + assertTrue(passwordsSection.$.manageLink.hidden); + }); + + test('showLinkToPasswordManagerWhenNotEncrypted', function() { + const passwordsSection = + elementFactory.createPasswordsSection(passwordManager, [], []); + const prefs = sync_test_util.getSyncAllPrefs(); + prefs.encryptAllData = false; + cr.webUIListenerCallback('sync-prefs-changed', prefs); + Polymer.dom.flush(); + assertFalse(passwordsSection.$.manageLink.hidden); + }); + + test('showLinkToPasswordManagerWhenNotSignedIn', function() { + const passwordsSection = + elementFactory.createPasswordsSection(passwordManager, [], []); + const prefs = sync_test_util.getSyncAllPrefs(); + sync_test_util.simulateSyncStatus({signedIn: false}); + cr.webUIListenerCallback('sync-prefs-changed', prefs); + Polymer.dom.flush(); + assertFalse(passwordsSection.$.manageLink.hidden); + }); }); });
diff --git a/chrome/test/data/webui/settings/people_page_sync_controls_test.js b/chrome/test/data/webui/settings/people_page_sync_controls_test.js index e7f5059..8c19c37 100644 --- a/chrome/test/data/webui/settings/people_page_sync_controls_test.js +++ b/chrome/test/data/webui/settings/people_page_sync_controls_test.js
@@ -7,44 +7,6 @@ let syncControls = null; let browserProxy = null; - /** - * Returns sync prefs with everything synced. - * @return {!settings.SyncPrefs} - */ - function getSyncAllPrefs() { - return { - appsEnforced: false, - appsRegistered: true, - appsSynced: true, - autofillEnforced: false, - autofillRegistered: true, - autofillSynced: true, - bookmarksEnforced: false, - bookmarksRegistered: true, - bookmarksSynced: true, - extensionsEnforced: false, - extensionsRegistered: true, - extensionsSynced: true, - passwordsEnforced: false, - passwordsRegistered: true, - passwordsSynced: true, - paymentsIntegrationEnabled: true, - preferencesEnforced: false, - preferencesRegistered: true, - preferencesSynced: true, - syncAllDataTypes: true, - tabsEnforced: false, - tabsRegistered: true, - tabsSynced: true, - themesEnforced: false, - themesRegistered: true, - themesSynced: true, - typedUrlsEnforced: false, - typedUrlsRegistered: true, - typedUrlsSynced: true, - }; - } - setup(function() { browserProxy = new TestSyncBrowserProxy(); settings.SyncBrowserProxyImpl.instance_ = browserProxy; @@ -54,7 +16,8 @@ document.body.appendChild(syncControls); // Start with Sync All. - cr.webUIListenerCallback('sync-prefs-changed', getSyncAllPrefs()); + cr.webUIListenerCallback( + 'sync-prefs-changed', sync_test_util.getSyncAllPrefs()); Polymer.dom.flush(); }); @@ -79,7 +42,7 @@ syncAllDataTypesControl.click(); function verifyPrefs(prefs) { - const expected = getSyncAllPrefs(); + const expected = sync_test_util.getSyncAllPrefs(); expected.syncAllDataTypes = false; assertEquals(JSON.stringify(expected), JSON.stringify(prefs)); @@ -97,7 +60,7 @@ datatypeControls[2].click(); return browserProxy.whenCalled('setSyncDatatypes') .then(function(prefs) { - const expected = getSyncAllPrefs(); + const expected = sync_test_util.getSyncAllPrefs(); expected.syncAllDataTypes = false; expected.extensionsSynced = false; assertEquals(JSON.stringify(expected), JSON.stringify(prefs));
diff --git a/chrome/test/data/webui/settings/people_page_sync_page_test.js b/chrome/test/data/webui/settings/people_page_sync_page_test.js index cd0cd4d..1d05826 100644 --- a/chrome/test/data/webui/settings/people_page_sync_page_test.js +++ b/chrome/test/data/webui/settings/people_page_sync_page_test.js
@@ -9,51 +9,6 @@ let encryptWithGoogle = null; let encryptWithPassphrase = null; - /** - * Returns sync prefs with everything synced and no passphrase required. - * @return {!settings.SyncPrefs} - */ - function getSyncAllPrefs() { - return { - appsEnforced: false, - appsRegistered: true, - appsSynced: true, - autofillEnforced: false, - autofillRegistered: true, - autofillSynced: true, - bookmarksEnforced: false, - bookmarksRegistered: true, - bookmarksSynced: true, - encryptAllData: false, - encryptAllDataAllowed: true, - enterPassphraseBody: 'Enter custom passphrase.', - extensionsEnforced: false, - extensionsRegistered: true, - extensionsSynced: true, - fullEncryptionBody: '', - passphrase: '', - passphraseRequired: false, - passwordsEnforced: false, - passwordsRegistered: true, - passwordsSynced: true, - paymentsIntegrationEnabled: true, - preferencesEnforced: false, - preferencesRegistered: true, - preferencesSynced: true, - setNewPassphrase: false, - syncAllDataTypes: true, - tabsEnforced: false, - tabsRegistered: true, - tabsSynced: true, - themesEnforced: false, - themesRegistered: true, - themesSynced: true, - typedUrlsEnforced: false, - typedUrlsRegistered: true, - typedUrlsSynced: true, - }; - } - setup(function() { browserProxy = new TestSyncBrowserProxy(); settings.SyncBrowserProxyImpl.instance_ = browserProxy; @@ -72,7 +27,8 @@ // Start with Sync All with no encryption selected. Also, ensure that // this is not a supervised user, so that Sync Passphrase is enabled. - cr.webUIListenerCallback('sync-prefs-changed', getSyncAllPrefs()); + cr.webUIListenerCallback( + 'sync-prefs-changed', sync_test_util.getSyncAllPrefs()); syncPage.set('syncStatus', {supervisedUser: false}); Polymer.dom.flush(); @@ -258,7 +214,8 @@ assertTrue(!!saveNewPassphrase); // Test that a sync prefs update does not reset the selection. - cr.webUIListenerCallback('sync-prefs-changed', getSyncAllPrefs()); + cr.webUIListenerCallback( + 'sync-prefs-changed', sync_test_util.getSyncAllPrefs()); Polymer.dom.flush(); assertTrue(encryptWithPassphrase.checked); }); @@ -347,7 +304,7 @@ saveNewPassphrase.click(); function verifyPrefs(prefs) { - const expected = getSyncAllPrefs(); + const expected = sync_test_util.getSyncAllPrefs(); expected.setNewPassphrase = true; expected.passphrase = 'foo'; expected.encryptAllData = true; @@ -374,7 +331,7 @@ }); test('RadioBoxesHiddenWhenEncrypted', function() { - const prefs = getSyncAllPrefs(); + const prefs = sync_test_util.getSyncAllPrefs(); prefs.encryptAllData = true; prefs.passphraseRequired = true; prefs.fullEncryptionBody = 'Sync already encrypted.'; @@ -389,7 +346,7 @@ test( 'ExistingPassphraseSubmitButtonDisabledWhenExistingPassphraseEmpty', function() { - const prefs = getSyncAllPrefs(); + const prefs = sync_test_util.getSyncAllPrefs(); prefs.encryptAllData = true; prefs.passphraseRequired = true; cr.webUIListenerCallback('sync-prefs-changed', prefs); @@ -410,7 +367,7 @@ }); test('EnterExistingWrongPassphrase', function() { - const prefs = getSyncAllPrefs(); + const prefs = sync_test_util.getSyncAllPrefs(); prefs.encryptAllData = true; prefs.passphraseRequired = true; cr.webUIListenerCallback('sync-prefs-changed', prefs); @@ -428,7 +385,7 @@ submitExistingPassphrase.click(); return browserProxy.whenCalled('setSyncEncryption').then(function(prefs) { - const expected = getSyncAllPrefs(); + const expected = sync_test_util.getSyncAllPrefs(); expected.setNewPassphrase = false; expected.passphrase = 'wrong'; expected.encryptAllData = true; @@ -442,7 +399,7 @@ }); test('EnterExistingCorrectPassphrase', function() { - const prefs = getSyncAllPrefs(); + const prefs = sync_test_util.getSyncAllPrefs(); prefs.encryptAllData = true; prefs.passphraseRequired = true; cr.webUIListenerCallback('sync-prefs-changed', prefs); @@ -460,14 +417,14 @@ submitExistingPassphrase.click(); return browserProxy.whenCalled('setSyncEncryption').then(function(prefs) { - const expected = getSyncAllPrefs(); + const expected = sync_test_util.getSyncAllPrefs(); expected.setNewPassphrase = false; expected.passphrase = 'right'; expected.encryptAllData = true; expected.passphraseRequired = true; assertEquals(JSON.stringify(expected), JSON.stringify(prefs)); - const newPrefs = getSyncAllPrefs(); + const newPrefs = sync_test_util.getSyncAllPrefs(); newPrefs.encryptAllData = true; cr.webUIListenerCallback('sync-prefs-changed', newPrefs); @@ -502,7 +459,7 @@ // 1) Normal user (full data encryption allowed) // EXPECTED: encryptionOptions enabled - const prefs1 = getSyncAllPrefs(); + const prefs1 = sync_test_util.getSyncAllPrefs(); prefs1.encryptAllDataAllowed = true; cr.webUIListenerCallback('sync-prefs-changed', prefs1); syncPage.syncStatus = {supervisedUser: false}; @@ -514,7 +471,7 @@ // encryptAllDataAllowed is usually false only for supervised // users, but it's better to be check this case. // EXPECTED: encryptionOptions disabled - const prefs2 = getSyncAllPrefs(); + const prefs2 = sync_test_util.getSyncAllPrefs(); prefs2.encryptAllDataAllowed = false; cr.webUIListenerCallback('sync-prefs-changed', prefs2); syncPage.syncStatus = {supervisedUser: false}; @@ -524,7 +481,7 @@ // 3) Supervised user (full data encryption not allowed) // EXPECTED: encryptionOptions disabled - const prefs3 = getSyncAllPrefs(); + const prefs3 = sync_test_util.getSyncAllPrefs(); prefs3.encryptAllDataAllowed = false; cr.webUIListenerCallback('sync-prefs-changed', prefs3); syncPage.syncStatus = {supervisedUser: true}; @@ -535,7 +492,7 @@ // 4) Supervised user (full data encryption allowed) // This never happens in practice, but just to be safe. // EXPECTED: encryptionOptions disabled - const prefs4 = getSyncAllPrefs(); + const prefs4 = sync_test_util.getSyncAllPrefs(); prefs4.encryptAllDataAllowed = true; cr.webUIListenerCallback('sync-prefs-changed', prefs4); syncPage.syncStatus = {supervisedUser: true}; @@ -549,7 +506,7 @@ test('SyncDashboardHiddenFromSupervisedUsers', function() { const dashboardLink = syncPage.$$('#syncDashboardLink'); - const prefs = getSyncAllPrefs(); + const prefs = sync_test_util.getSyncAllPrefs(); cr.webUIListenerCallback('sync-prefs-changed', prefs); // Normal user
diff --git a/chrome/test/data/webui/settings/sync_test_util.js b/chrome/test/data/webui/settings/sync_test_util.js index a86f77d..4524bd0f 100644 --- a/chrome/test/data/webui/settings/sync_test_util.js +++ b/chrome/test/data/webui/settings/sync_test_util.js
@@ -3,6 +3,51 @@ // found in the LICENSE file. cr.define('sync_test_util', function() { + /** + * Returns sync prefs with everything synced and no passphrase required. + * @return {!settings.SyncPrefs} + */ + function getSyncAllPrefs() { + return { + appsEnforced: false, + appsRegistered: true, + appsSynced: true, + autofillEnforced: false, + autofillRegistered: true, + autofillSynced: true, + bookmarksEnforced: false, + bookmarksRegistered: true, + bookmarksSynced: true, + encryptAllData: false, + encryptAllDataAllowed: true, + enterPassphraseBody: 'Enter custom passphrase.', + extensionsEnforced: false, + extensionsRegistered: true, + extensionsSynced: true, + fullEncryptionBody: '', + passphrase: '', + passphraseRequired: false, + passwordsEnforced: false, + passwordsRegistered: true, + passwordsSynced: true, + paymentsIntegrationEnabled: true, + preferencesEnforced: false, + preferencesRegistered: true, + preferencesSynced: true, + setNewPassphrase: false, + syncAllDataTypes: true, + tabsEnforced: false, + tabsRegistered: true, + tabsSynced: true, + themesEnforced: false, + themesRegistered: true, + themesSynced: true, + typedUrlsEnforced: false, + typedUrlsRegistered: true, + typedUrlsSynced: true, + }; + } + /** @param {!settings.SyncStatus} */ function simulateSyncStatus(status) { cr.webUIListenerCallback('sync-status-changed', status); @@ -16,7 +61,8 @@ } return { + getSyncAllPrefs: getSyncAllPrefs, simulateSyncStatus: simulateSyncStatus, simulateStoredAccounts: simulateStoredAccounts, }; -}); \ No newline at end of file +});
diff --git a/chrome/test/data/webui/settings/test_sync_browser_proxy.js b/chrome/test/data/webui/settings/test_sync_browser_proxy.js index efcfd55..3900d7d 100644 --- a/chrome/test/data/webui/settings/test_sync_browser_proxy.js +++ b/chrome/test/data/webui/settings/test_sync_browser_proxy.js
@@ -16,6 +16,7 @@ 'setSyncEncryption', 'signOut', 'pauseSync', + 'sendSyncPrefsChanged', 'startSignIn', 'startSyncingWithEmail', ]); @@ -95,4 +96,9 @@ this.methodCalled('setSyncEncryption', syncPrefs); return Promise.resolve(this.encryptionResponse); } + + /** @override */ + sendSyncPrefsChanged() { + this.methodCalled('sendSyncPrefsChanged'); + } }
diff --git a/chromeos/components/account_manager/account_manager.cc b/chromeos/components/account_manager/account_manager.cc index 0561dff..e88f949 100644 --- a/chromeos/components/account_manager/account_manager.cc +++ b/chromeos/components/account_manager/account_manager.cc
@@ -181,8 +181,9 @@ base::OnceClosure initialization_callback) { Initialize( home_dir, url_loader_factory, std::move(delay_network_call_runner), - base::CreateSequencedTaskRunnerWithTraits( - {base::TaskShutdownBehavior::BLOCK_SHUTDOWN, base::MayBlock()}), + base::CreateSequencedTaskRunner( + {base::ThreadPool(), base::TaskShutdownBehavior::BLOCK_SHUTDOWN, + base::MayBlock()}), std::move(initialization_callback)); }
diff --git a/chromeos/components/drivefs/fake_drivefs.cc b/chromeos/components/drivefs/fake_drivefs.cc index e94cd0e..a6f97f4 100644 --- a/chromeos/components/drivefs/fake_drivefs.cc +++ b/chromeos/components/drivefs/fake_drivefs.cc
@@ -106,8 +106,10 @@ } else { // Default implementation: just search for a file name. callback_ = std::move(callback); - base::PostTaskWithTraitsAndReplyWithResult( - FROM_HERE, {base::MayBlock(), base::TaskPriority::BEST_EFFORT}, + base::PostTaskAndReplyWithResult( + FROM_HERE, + {base::ThreadPool(), base::MayBlock(), + base::TaskPriority::BEST_EFFORT}, base::BindOnce(&SearchQuery::SearchFiles, drive_fs_->mount_path()), base::BindOnce(&SearchQuery::GetMetadata, weak_ptr_factory_.GetWeakPtr()));
diff --git a/chromeos/components/drivefs/fake_drivefs_launcher_client.cc b/chromeos/components/drivefs/fake_drivefs_launcher_client.cc index 86fa062..4cefa0f 100644 --- a/chromeos/components/drivefs/fake_drivefs_launcher_client.cc +++ b/chromeos/components/drivefs/fake_drivefs_launcher_client.cc
@@ -56,8 +56,9 @@ const base::FilePath& socket_path) : chroot_path_(chroot_path), socket_path_(chroot_path_.Append(socket_path)) { - base::PostTaskWithTraits( - FROM_HERE, {base::MayBlock(), base::TaskPriority::BEST_EFFORT}, + base::PostTask( + FROM_HERE, + {base::ThreadPool(), base::MayBlock(), base::TaskPriority::BEST_EFFORT}, base::BindOnce(&ConnectAsync, mojo::MakeRequest(&launcher_), socket_path_.value()));
diff --git a/chromeos/components/nearby/count_down_latch_impl_unittest.cc b/chromeos/components/nearby/count_down_latch_impl_unittest.cc index 8d4a952..0bd168c 100644 --- a/chromeos/components/nearby/count_down_latch_impl_unittest.cc +++ b/chromeos/components/nearby/count_down_latch_impl_unittest.cc
@@ -39,8 +39,8 @@ base::UnguessableToken PostAwaitTask( const base::Optional<base::TimeDelta>& timeout_millis) { base::UnguessableToken unique_task_id = base::UnguessableToken::Create(); - base::PostTaskWithTraits( - FROM_HERE, {base::MayBlock()}, + base::PostTask( + FROM_HERE, {base::ThreadPool(), base::MayBlock()}, base::BindOnce(&CountDownLatchImplTest::AwaitTask, base::Unretained(this), timeout_millis, unique_task_id)); return unique_task_id;
diff --git a/chromeos/components/nearby/lock_impl_unittest.cc b/chromeos/components/nearby/lock_impl_unittest.cc index 7564cf7..c600484c 100644 --- a/chromeos/components/nearby/lock_impl_unittest.cc +++ b/chromeos/components/nearby/lock_impl_unittest.cc
@@ -26,8 +26,8 @@ protected: LockImplTest() : lock_(std::make_unique<LockImpl>()), - different_thread_task_runner_( - base::CreateSingleThreadTaskRunnerWithTraits(base::MayBlock())) {} + different_thread_task_runner_(base::CreateSingleThreadTaskRunner( + {base::ThreadPool(), base::MayBlock()})) {} // testing::Test void SetUp() override {
diff --git a/chromeos/components/nearby/multi_thread_executor_impl.cc b/chromeos/components/nearby/multi_thread_executor_impl.cc index 6a21b7f..d6a0a91 100644 --- a/chromeos/components/nearby/multi_thread_executor_impl.cc +++ b/chromeos/components/nearby/multi_thread_executor_impl.cc
@@ -10,7 +10,7 @@ MultiThreadExecutorImpl::MultiThreadExecutorImpl() : SubmittableExecutorBase( - base::CreateTaskRunnerWithTraits(base::MayBlock())) {} + base::CreateTaskRunner({base::ThreadPool(), base::MayBlock()})) {} MultiThreadExecutorImpl::~MultiThreadExecutorImpl() = default;
diff --git a/chromeos/components/nearby/scheduled_executor_impl.h b/chromeos/components/nearby/scheduled_executor_impl.h index 91c5a239..b968906 100644 --- a/chromeos/components/nearby/scheduled_executor_impl.h +++ b/chromeos/components/nearby/scheduled_executor_impl.h
@@ -30,7 +30,8 @@ public: ScheduledExecutorImpl( scoped_refptr<base::SequencedTaskRunner> timer_task_runner = - base::CreateSequencedTaskRunnerWithTraits(base::MayBlock())); + base::CreateSequencedTaskRunner({base::ThreadPool(), + base::MayBlock()})); ~ScheduledExecutorImpl() override; private:
diff --git a/chromeos/components/nearby/settable_future_impl_unittest.cc b/chromeos/components/nearby/settable_future_impl_unittest.cc index a501740..3bab8c7a 100644 --- a/chromeos/components/nearby/settable_future_impl_unittest.cc +++ b/chromeos/components/nearby/settable_future_impl_unittest.cc
@@ -49,10 +49,9 @@ base::UnguessableToken PostGetAsyncResult() { base::UnguessableToken id = base::UnguessableToken::Create(); - base::PostTaskWithTraits( - FROM_HERE, {base::MayBlock()}, - base::BindOnce(&SettableFutureImplTest::GetAsyncResult, - base::Unretained(this), id)); + base::PostTask(FROM_HERE, {base::ThreadPool(), base::MayBlock()}, + base::BindOnce(&SettableFutureImplTest::GetAsyncResult, + base::Unretained(this), id)); return id; }
diff --git a/chromeos/components/nearby/single_thread_executor_impl.cc b/chromeos/components/nearby/single_thread_executor_impl.cc index 466847a..c27e675 100644 --- a/chromeos/components/nearby/single_thread_executor_impl.cc +++ b/chromeos/components/nearby/single_thread_executor_impl.cc
@@ -9,8 +9,8 @@ namespace nearby { SingleThreadExecutorImpl::SingleThreadExecutorImpl() - : SubmittableExecutorBase( - base::CreateSequencedTaskRunnerWithTraits(base::MayBlock())) {} + : SubmittableExecutorBase(base::CreateSequencedTaskRunner( + {base::ThreadPool(), base::MayBlock()})) {} SingleThreadExecutorImpl::~SingleThreadExecutorImpl() = default;
diff --git a/chromeos/cryptohome/cryptohome_parameters.cc b/chromeos/cryptohome/cryptohome_parameters.cc index f6f4672..99fb6670 100644 --- a/chromeos/cryptohome/cryptohome_parameters.cc +++ b/chromeos/cryptohome/cryptohome_parameters.cc
@@ -41,6 +41,29 @@ return account_id.GetUserEmail(); } +AccountId LookupUserByCryptohomeId(const std::string& cryptohome_id) { + const std::vector<AccountId> known_account_ids = + user_manager::known_user::GetKnownAccountIds(); + + // A LOT of tests start with --login_user <user>, and not registering this + // user before. So we might have "known_user" entry without gaia_id. + for (const AccountId& known_id : known_account_ids) { + if (known_id.HasAccountIdKey() && + known_id.GetAccountIdKey() == cryptohome_id) { + return known_id; + } + } + + for (const AccountId& known_id : known_account_ids) { + if (known_id.GetUserEmail() == cryptohome_id) { + return known_id; + } + } + + return user_manager::known_user::GetAccountId( + cryptohome_id, std::string() /* id */, AccountType::UNKNOWN); +} + } // anonymous namespace Identification::Identification() = default; @@ -63,25 +86,7 @@ } AccountId Identification::GetAccountId() const { - const std::vector<AccountId> known_account_ids = - user_manager::known_user::GetKnownAccountIds(); - - // A LOT of tests start with --login_user <user>, and not registing this user - // before. So we might have "known_user" entry without gaia_id. - for (const AccountId& known_id : known_account_ids) { - if (known_id.HasAccountIdKey() && known_id.GetAccountIdKey() == id_) { - return known_id; - } - } - - for (const AccountId& known_id : known_account_ids) { - if (known_id.GetUserEmail() == id_) { - return known_id; - } - } - - return user_manager::known_user::GetAccountId(id_, std::string() /* id */, - AccountType::UNKNOWN); + return LookupUserByCryptohomeId(id_); } AccountIdentifier CreateAccountIdentifierFromAccountId(const AccountId& id) { @@ -97,6 +102,11 @@ return out; } +AccountId GetAccountIdFromAccountIdentifier( + const AccountIdentifier& account_identifier) { + return LookupUserByCryptohomeId(account_identifier.account_id()); +} + KeyDefinition::AuthorizationData::Secret::Secret() : encrypt(false), sign(false), wrapped(false) {
diff --git a/chromeos/cryptohome/cryptohome_parameters.h b/chromeos/cryptohome/cryptohome_parameters.h index 04dbf38..34bb24a 100644 --- a/chromeos/cryptohome/cryptohome_parameters.h +++ b/chromeos/cryptohome/cryptohome_parameters.h
@@ -62,6 +62,11 @@ AccountIdentifier CreateAccountIdentifierFromIdentification( const Identification& id); +// Look up known user for the given AccountIdentifier and return its AccountId. +COMPONENT_EXPORT(CHROMEOS_CRYPTOHOME) +AccountId GetAccountIdFromAccountIdentifier( + const AccountIdentifier& account_identifier); + // Definition of the key (e.g. password) for the cryptohome. // It contains authorization data along with extra parameters like permissions // associated with this key.
diff --git a/chromeos/dbus/debug_daemon_client.cc b/chromeos/dbus/debug_daemon_client.cc index a3c8cc4..618575a2 100644 --- a/chromeos/dbus/debug_daemon_client.cc +++ b/chromeos/dbus/debug_daemon_client.cc
@@ -52,8 +52,8 @@ class PipeReaderWrapper : public base::SupportsWeakPtr<PipeReaderWrapper> { public: explicit PipeReaderWrapper(DebugDaemonClient::GetLogsCallback callback) - : pipe_reader_(base::CreateTaskRunnerWithTraits( - {base::MayBlock(), + : pipe_reader_(base::CreateTaskRunner( + {base::ThreadPool(), base::MayBlock(), base::TaskShutdownBehavior::CONTINUE_ON_SHUTDOWN})), callback_(std::move(callback)) {}
diff --git a/chromeos/dbus/fake_cros_disks_client.cc b/chromeos/dbus/fake_cros_disks_client.cc index 91607f9..6cc8d82 100644 --- a/chromeos/dbus/fake_cros_disks_client.cc +++ b/chromeos/dbus/fake_cros_disks_client.cc
@@ -117,9 +117,10 @@ } mounted_paths_.insert(mounted_path); - base::PostTaskWithTraitsAndReplyWithResult( + base::PostTaskAndReplyWithResult( FROM_HERE, - {base::MayBlock(), base::TaskShutdownBehavior::CONTINUE_ON_SHUTDOWN}, + {base::ThreadPool(), base::MayBlock(), + base::TaskShutdownBehavior::CONTINUE_ON_SHUTDOWN}, base::BindOnce(&PerformFakeMount, source_path, mounted_path, type), base::BindOnce(&FakeCrosDisksClient::DidMount, weak_ptr_factory_.GetWeakPtr(), source_path, type, @@ -153,9 +154,9 @@ // Remove the dummy mounted directory if it exists. if (mounted_paths_.erase(base::FilePath::FromUTF8Unsafe(device_path))) { - base::PostTaskWithTraitsAndReply( + base::PostTaskAndReply( FROM_HERE, - {base::MayBlock(), base::TaskPriority::BEST_EFFORT, + {base::ThreadPool(), base::MayBlock(), base::TaskPriority::BEST_EFFORT, base::TaskShutdownBehavior::CONTINUE_ON_SHUTDOWN}, base::BindOnce(base::IgnoreResult(&base::DeleteFile), base::FilePath::FromUTF8Unsafe(device_path),
diff --git a/chromeos/dbus/fake_oobe_configuration_client.cc b/chromeos/dbus/fake_oobe_configuration_client.cc index fe43bad1..641c01e 100644 --- a/chromeos/dbus/fake_oobe_configuration_client.cc +++ b/chromeos/dbus/fake_oobe_configuration_client.cc
@@ -53,8 +53,9 @@ base::CommandLine::ForCurrentProcess()->GetSwitchValuePath( chromeos::switches::kFakeOobeConfiguration); - base::PostTaskWithTraitsAndReplyWithResult( - FROM_HERE, {base::TaskPriority::BEST_EFFORT, base::MayBlock()}, + base::PostTaskAndReplyWithResult( + FROM_HERE, + {base::ThreadPool(), base::TaskPriority::BEST_EFFORT, base::MayBlock()}, base::BindOnce(&LoadConfigurationFile, path), base::BindOnce(&OnConfigurationLoaded, std::move(callback))); }
diff --git a/chromeos/dbus/lorgnette_manager_client.cc b/chromeos/dbus/lorgnette_manager_client.cc index 25e7a93..4260372 100644 --- a/chromeos/dbus/lorgnette_manager_client.cc +++ b/chromeos/dbus/lorgnette_manager_client.cc
@@ -101,9 +101,9 @@ base::ScopedFD Start() { DCHECK(!pipe_reader_.get()); DCHECK(!data_.has_value()); - pipe_reader_ = std::make_unique<chromeos::PipeReader>( - base::CreateTaskRunnerWithTraits( - {base::MayBlock(), + pipe_reader_ = + std::make_unique<chromeos::PipeReader>(base::CreateTaskRunner( + {base::ThreadPool(), base::MayBlock(), base::TaskShutdownBehavior::CONTINUE_ON_SHUTDOWN})); return pipe_reader_->StartIO(base::BindOnce(
diff --git a/chromeos/dbus/permission_broker/fake_permission_broker_client.cc b/chromeos/dbus/permission_broker/fake_permission_broker_client.cc index 9b86e06..3f31564 100644 --- a/chromeos/dbus/permission_broker/fake_permission_broker_client.cc +++ b/chromeos/dbus/permission_broker/fake_permission_broker_client.cc
@@ -75,12 +75,12 @@ void FakePermissionBrokerClient::OpenPath(const std::string& path, OpenPathCallback callback, ErrorCallback error_callback) { - base::PostTaskWithTraits( - FROM_HERE, - {base::MayBlock(), base::TaskShutdownBehavior::CONTINUE_ON_SHUTDOWN}, - base::BindOnce(&chromeos::OpenPath, path, std::move(callback), - std::move(error_callback), - base::ThreadTaskRunnerHandle::Get())); + base::PostTask(FROM_HERE, + {base::ThreadPool(), base::MayBlock(), + base::TaskShutdownBehavior::CONTINUE_ON_SHUTDOWN}, + base::BindOnce(&chromeos::OpenPath, path, std::move(callback), + std::move(error_callback), + base::ThreadTaskRunnerHandle::Get())); } void FakePermissionBrokerClient::RequestTcpPortAccess(
diff --git a/chromeos/dbus/session_manager/fake_session_manager_client.cc b/chromeos/dbus/session_manager/fake_session_manager_client.cc index f1ea6c5..fa064ab 100644 --- a/chromeos/dbus/session_manager/fake_session_manager_client.cc +++ b/chromeos/dbus/session_manager/fake_session_manager_client.cc
@@ -426,9 +426,10 @@ GetStubPolicyFilePath(descriptor, nullptr /* key_path */); DCHECK(!policy_path.empty()); - base::PostTaskWithTraitsAndReplyWithResult( + base::PostTaskAndReplyWithResult( FROM_HERE, - {base::MayBlock(), base::TaskShutdownBehavior::CONTINUE_ON_SHUTDOWN}, + {base::ThreadPool(), base::MayBlock(), + base::TaskShutdownBehavior::CONTINUE_ON_SHUTDOWN}, base::BindOnce(&GetFileContent, policy_path), base::BindOnce(std::move(callback), RetrievePolicyResponseType::SUCCESS)); @@ -510,9 +511,10 @@ if (response.has_new_public_key()) files_to_store[key_path] = response.new_public_key(); - base::PostTaskWithTraitsAndReply( + base::PostTaskAndReply( FROM_HERE, - {base::MayBlock(), base::TaskShutdownBehavior::CONTINUE_ON_SHUTDOWN}, + {base::ThreadPool(), base::MayBlock(), + base::TaskShutdownBehavior::CONTINUE_ON_SHUTDOWN}, base::BindOnce(StoreFiles, std::move(files_to_store)), base::BindOnce(std::move(callback), true /* success */)); } else { @@ -526,9 +528,9 @@ GetStubPolicyFilePath(descriptor, &key_path); DCHECK(!key_path.empty()); - base::PostTaskWithTraitsAndReply( + base::PostTaskAndReply( FROM_HERE, - {base::MayBlock(), + {base::ThreadPool(), base::MayBlock(), base::TaskShutdownBehavior::CONTINUE_ON_SHUTDOWN}, base::BindOnce(StoreFiles, std::map<base::FilePath, std::string>{ @@ -543,7 +545,7 @@ } // Run the callback if it hasn't been passed to - // PostTaskWithTraitsAndReply(), in which case it will be run after the + // PostTaskAndReply(), in which case it will be run after the // owner key file was stored to disk. if (callback) { PostReply(FROM_HERE, std::move(callback), true /* success */); @@ -573,9 +575,10 @@ CHECK(base::PathService::Get(dbus_paths::FILE_OWNER_KEY, &owner_key_path)); const base::FilePath state_keys_path = owner_key_path.DirName().AppendASCII(kStubStateKeysFileName); - base::PostTaskWithTraitsAndReplyWithResult( + base::PostTaskAndReplyWithResult( FROM_HERE, - {base::MayBlock(), base::TaskShutdownBehavior::CONTINUE_ON_SHUTDOWN}, + {base::ThreadPool(), base::MayBlock(), + base::TaskShutdownBehavior::CONTINUE_ON_SHUTDOWN}, base::BindOnce(&ReadCreateStateKeysStub, state_keys_path), std::move(callback)); } else {
diff --git a/chromeos/network/client_cert_resolver.cc b/chromeos/network/client_cert_resolver.cc index e142d9c..9a39df2c 100644 --- a/chromeos/network/client_cert_resolver.cc +++ b/chromeos/network/client_cert_resolver.cc
@@ -659,9 +659,10 @@ VLOG(2) << "Start task for resolving client cert patterns."; resolve_task_running_ = true; - base::PostTaskWithTraitsAndReplyWithResult( + base::PostTaskAndReplyWithResult( FROM_HERE, - {base::MayBlock(), base::TaskShutdownBehavior::CONTINUE_ON_SHUTDOWN}, + {base::ThreadPool(), base::MayBlock(), + base::TaskShutdownBehavior::CONTINUE_ON_SHUTDOWN}, base::BindOnce(&FindCertificateMatches, NetworkCertLoader::CloneNetworkCertList( NetworkCertLoader::Get()->client_certs()),
diff --git a/chromeos/printing/ppd_cache.cc b/chromeos/printing/ppd_cache.cc index f1b6a996..99c7b85 100644 --- a/chromeos/printing/ppd_cache.cc +++ b/chromeos/printing/ppd_cache.cc
@@ -176,14 +176,14 @@ // static scoped_refptr<PpdCache> PpdCache::Create(const base::FilePath& cache_base_dir) { - return scoped_refptr<PpdCache>( - new PpdCacheImpl(cache_base_dir, - base::CreateSequencedTaskRunnerWithTraits( - {base::TaskPriority::USER_VISIBLE, base::MayBlock(), - base::TaskShutdownBehavior::SKIP_ON_SHUTDOWN}), - base::CreateSequencedTaskRunnerWithTraits( - {base::TaskPriority::BEST_EFFORT, base::MayBlock(), - base::TaskShutdownBehavior::BLOCK_SHUTDOWN}))); + return scoped_refptr<PpdCache>(new PpdCacheImpl( + cache_base_dir, + base::CreateSequencedTaskRunner( + {base::ThreadPool(), base::TaskPriority::USER_VISIBLE, + base::MayBlock(), base::TaskShutdownBehavior::SKIP_ON_SHUTDOWN}), + base::CreateSequencedTaskRunner( + {base::ThreadPool(), base::TaskPriority::BEST_EFFORT, + base::MayBlock(), base::TaskShutdownBehavior::BLOCK_SHUTDOWN}))); } scoped_refptr<PpdCache> PpdCache::CreateForTesting(
diff --git a/chromeos/printing/ppd_provider.cc b/chromeos/printing/ppd_provider.cc index 9107effb..91040ad 100644 --- a/chromeos/printing/ppd_provider.cc +++ b/chromeos/printing/ppd_provider.cc
@@ -414,9 +414,9 @@ : browser_locale_(browser_locale), loader_factory_(loader_factory), ppd_cache_(ppd_cache), - disk_task_runner_(base::CreateSequencedTaskRunnerWithTraits( - {base::TaskPriority::USER_VISIBLE, base::MayBlock(), - base::TaskShutdownBehavior::SKIP_ON_SHUTDOWN})), + disk_task_runner_(base::CreateSequencedTaskRunner( + {base::ThreadPool(), base::TaskPriority::USER_VISIBLE, + base::MayBlock(), base::TaskShutdownBehavior::SKIP_ON_SHUTDOWN})), version_(current_version), options_(options), weak_factory_(this) {}
diff --git a/chromeos/services/assistant/chromium_http_connection.cc b/chromeos/services/assistant/chromium_http_connection.cc index 5ceb30e8..e5de556 100644 --- a/chromeos/services/assistant/chromium_http_connection.cc +++ b/chromeos/services/assistant/chromium_http_connection.cc
@@ -55,7 +55,7 @@ std::unique_ptr<SharedURLLoaderFactoryInfo> url_loader_factory_info, Delegate* delegate) : delegate_(delegate), - task_runner_(base::CreateSequencedTaskRunnerWithTraits({})), + task_runner_(base::CreateSequencedTaskRunner({})), url_loader_factory_info_(std::move(url_loader_factory_info)) { DCHECK(delegate_); DCHECK(url_loader_factory_info_);
diff --git a/chromeos/settings/timezone_settings.cc b/chromeos/settings/timezone_settings.cc index c5ec163..1710229 100644 --- a/chromeos/settings/timezone_settings.cc +++ b/chromeos/settings/timezone_settings.cc
@@ -393,10 +393,11 @@ VLOG(1) << "Setting timezone to " << id; // It's safe to change the timezone config files in the background as the // following operations don't depend on the completion of the config change. - base::PostTaskWithTraits(FROM_HERE, - {base::MayBlock(), base::TaskPriority::BEST_EFFORT, - base::TaskShutdownBehavior::CONTINUE_ON_SHUTDOWN}, - base::BindOnce(&SetTimezoneIDFromString, id)); + base::PostTask( + FROM_HERE, + {base::ThreadPool(), base::MayBlock(), base::TaskPriority::BEST_EFFORT, + base::TaskShutdownBehavior::CONTINUE_ON_SHUTDOWN}, + base::BindOnce(&SetTimezoneIDFromString, id)); icu::TimeZone::setDefault(*known_timezone); for (auto& observer : observers_) observer.TimezoneChanged(*known_timezone);
diff --git a/chromeos/system/statistics_provider.cc b/chromeos/system/statistics_provider.cc index 65bb425..3875ee8 100644 --- a/chromeos/system/statistics_provider.cc +++ b/chromeos/system/statistics_provider.cc
@@ -486,9 +486,9 @@ // TaskPriority::USER_BLOCKING because this is on the critical path of // rendering the NTP on startup. https://crbug.com/831835 - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, - {base::MayBlock(), base::TaskPriority::USER_BLOCKING, + {base::ThreadPool(), base::MayBlock(), base::TaskPriority::USER_BLOCKING, base::TaskShutdownBehavior::SKIP_ON_SHUTDOWN}, base::BindOnce(&StatisticsProviderImpl::LoadMachineStatistics, base::Unretained(this), load_oem_manifest));
diff --git a/components/BUILD.gn b/components/BUILD.gn index 15da5b3..111f08d 100644 --- a/components/BUILD.gn +++ b/components/BUILD.gn
@@ -298,6 +298,7 @@ "//components/policy/android:policy_java", "//components/signin/core/browser", "//components/signin/core/browser/android:java", + "//components/signin/public/identity_manager/android:java", "//components/spellcheck/browser/android:java", "//components/variations/android:variations_java", "//content/public/android:content_java",
diff --git a/components/autofill/core/browser/BUILD.gn b/components/autofill/core/browser/BUILD.gn index 1139bda..3ec082a 100644 --- a/components/autofill/core/browser/BUILD.gn +++ b/components/autofill/core/browser/BUILD.gn
@@ -33,6 +33,8 @@ "autofill-inl.h", "autofill_address_util.cc", "autofill_address_util.h", + "autofill_browser_util.cc", + "autofill_browser_util.h", "autofill_client.cc", "autofill_client.h", "autofill_data_util.cc",
diff --git a/components/autofill/core/browser/autofill_browser_util.cc b/components/autofill/core/browser/autofill_browser_util.cc new file mode 100644 index 0000000..db8b6be --- /dev/null +++ b/components/autofill/core/browser/autofill_browser_util.cc
@@ -0,0 +1,24 @@ +// Copyright 2019 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "components/autofill/core/browser/autofill_browser_util.h" + +#include "components/autofill/core/browser/autofill_client.h" + +namespace autofill { + +bool IsFormOrClientNonSecure(AutofillClient* client, const FormData& form) { + return !client->IsContextSecure() || + (form.action.is_valid() && form.action.SchemeIs("http")); +} + +bool ShouldAllowCreditCardFallbacks(AutofillClient* client, + const FormData& form) { + // Skip the form check if there wasn't a form yet: + if (form.unique_renderer_id == FormData::kNotSetFormRendererId) + return client->IsContextSecure(); + return !IsFormOrClientNonSecure(client, form); +} + +} // namespace autofill
diff --git a/components/autofill/core/browser/autofill_browser_util.h b/components/autofill/core/browser/autofill_browser_util.h new file mode 100644 index 0000000..f684ef3e --- /dev/null +++ b/components/autofill/core/browser/autofill_browser_util.h
@@ -0,0 +1,26 @@ +// Copyright 2019 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef COMPONENTS_AUTOFILL_CORE_BROWSER_AUTOFILL_BROWSER_UTIL_H_ +#define COMPONENTS_AUTOFILL_CORE_BROWSER_AUTOFILL_BROWSER_UTIL_H_ + +#include <stddef.h> + +#include "components/autofill/core/common/form_data.h" + +namespace autofill { + +class AutofillClient; + +// Checks whether a given form is considered insecure (by origin or action). +bool IsFormOrClientNonSecure(AutofillClient* client, const FormData& form); + +// Returns true if context provided by the client and the given form are +// considered "secure enough" to manually fill credit card data. +bool ShouldAllowCreditCardFallbacks(AutofillClient* client, + const FormData& form); + +} // namespace autofill + +#endif // COMPONENTS_AUTOFILL_CORE_BROWSER_AUTOFILL_BROWSER_UTIL_H_
diff --git a/components/autofill/core/browser/autofill_external_delegate.h b/components/autofill/core/browser/autofill_external_delegate.h index 2783c46..aa6b69d 100644 --- a/components/autofill/core/browser/autofill_external_delegate.h +++ b/components/autofill/core/browser/autofill_external_delegate.h
@@ -100,6 +100,8 @@ // who has a controller relation to the current autofill popup. int32_t GetWebContentsPopupControllerAxId() const; + const FormData& query_form() const { return query_form_; } + protected: base::WeakPtr<AutofillExternalDelegate> GetWeakPtr();
diff --git a/components/autofill/core/browser/autofill_manager.cc b/components/autofill/core/browser/autofill_manager.cc index 57fe5e7..030d6f9 100644 --- a/components/autofill/core/browser/autofill_manager.cc +++ b/components/autofill/core/browser/autofill_manager.cc
@@ -37,6 +37,7 @@ #include "base/threading/thread_restrictions.h" #include "build/build_config.h" #include "components/autofill/core/browser/autocomplete_history_manager.h" +#include "components/autofill/core/browser/autofill_browser_util.h" #include "components/autofill/core/browser/autofill_client.h" #include "components/autofill/core/browser/autofill_data_util.h" #include "components/autofill/core/browser/autofill_external_delegate.h" @@ -663,8 +664,7 @@ } bool AutofillManager::IsFormNonSecure(const FormData& form) const { - return !client_->IsContextSecure() || - (form.action.is_valid() && form.action.SchemeIs("http")); + return IsFormOrClientNonSecure(client_, form); } void AutofillManager::OnQueryFormFieldAutofillImpl( @@ -1241,6 +1241,10 @@ channel != version_info::Channel::BETA; } +const FormData& AutofillManager::last_query_form() const { + return external_delegate_->query_form(); +} + bool AutofillManager::ShouldUploadForm(const FormStructure& form) { return IsAutofillEnabled() && !driver()->IsIncognito() && form.ShouldBeUploaded();
diff --git a/components/autofill/core/browser/autofill_manager.h b/components/autofill/core/browser/autofill_manager.h index 56bccac..3496e3c 100644 --- a/components/autofill/core/browser/autofill_manager.h +++ b/components/autofill/core/browser/autofill_manager.h
@@ -239,6 +239,9 @@ // neither on the STABLE nor BETA release channel. static bool IsRichQueryEnabled(version_info::Channel channel); + // Returns the last form the autofill manager considered in this frame. + virtual const FormData& last_query_form() const; + protected: // Test code should prefer to use this constructor. AutofillManager(
diff --git a/components/autofill/core/browser/ui/accessory_sheet_data.cc b/components/autofill/core/browser/ui/accessory_sheet_data.cc index 3f9740d..a9b7596 100644 --- a/components/autofill/core/browser/ui/accessory_sheet_data.cc +++ b/components/autofill/core/browser/ui/accessory_sheet_data.cc
@@ -127,7 +127,13 @@ AccessorySheetData::AccessorySheetData(AccessoryTabType sheet_type, base::string16 title) - : sheet_type_(sheet_type), title_(std::move(title)) {} + : AccessorySheetData(sheet_type, std::move(title), base::string16()) {} +AccessorySheetData::AccessorySheetData(AccessoryTabType sheet_type, + base::string16 title, + base::string16 warning) + : sheet_type_(sheet_type), + title_(std::move(title)), + warning_(std::move(warning)) {} AccessorySheetData::AccessorySheetData(const AccessorySheetData& data) = default; @@ -144,13 +150,13 @@ bool AccessorySheetData::operator==(const AccessorySheetData& data) const { return sheet_type_ == data.sheet_type_ && title_ == data.title_ && - user_info_list_ == data.user_info_list_ && + warning_ == data.warning_ && user_info_list_ == data.user_info_list_ && footer_commands_ == data.footer_commands_; } std::ostream& operator<<(std::ostream& os, const AccessorySheetData& data) { os << data.get_sheet_type() << " with title: \"" << data.title() - << "\", user info list: ["; + << "\", warning: \"" << data.warning() << "\", and user info list: ["; for (const UserInfo& user_info : data.user_info_list()) { os << user_info << ", "; } @@ -167,6 +173,18 @@ AccessorySheetData::Builder::~Builder() = default; +AccessorySheetData::Builder&& AccessorySheetData::Builder::SetWarning( + base::string16 warning) && { + // Calls SetWarning(base::string16 warning)()& since |this| is an lvalue. + return std::move(SetWarning(std::move(warning))); +} + +AccessorySheetData::Builder& AccessorySheetData::Builder::SetWarning( + base::string16 warning) & { + accessory_sheet_data_.set_warning(std::move(warning)); + return *this; +} + AccessorySheetData::Builder&& AccessorySheetData::Builder::AddUserInfo( std::string origin) && { // Calls AddUserInfo()& since |this| is an lvalue.
diff --git a/components/autofill/core/browser/ui/accessory_sheet_data.h b/components/autofill/core/browser/ui/accessory_sheet_data.h index 1c1fa830..351e1c0 100644 --- a/components/autofill/core/browser/ui/accessory_sheet_data.h +++ b/components/autofill/core/browser/ui/accessory_sheet_data.h
@@ -119,6 +119,9 @@ class Builder; AccessorySheetData(AccessoryTabType sheet_type, base::string16 title); + AccessorySheetData(AccessoryTabType sheet_type, + base::string16 title, + base::string16 warning); AccessorySheetData(const AccessorySheetData& data); AccessorySheetData(AccessorySheetData&& data); @@ -130,6 +133,9 @@ const base::string16& title() const { return title_; } AccessoryTabType get_sheet_type() const { return sheet_type_; } + const base::string16& warning() const { return warning_; } + void set_warning(base::string16 warning) { warning_ = std::move(warning); } + void add_user_info(UserInfo user_info) { user_info_list_.emplace_back(std::move(user_info)); } @@ -153,6 +159,7 @@ private: AccessoryTabType sheet_type_; base::string16 title_; + base::string16 warning_; std::vector<UserInfo> user_info_list_; std::vector<FooterCommand> footer_commands_; }; @@ -177,6 +184,10 @@ Builder(AccessoryTabType type, base::string16 title); ~Builder(); + // Adds a warning string to the accessory sheet. + Builder&& SetWarning(base::string16 warning) &&; + Builder& SetWarning(base::string16 warning) &; + // Adds a new UserInfo object to |accessory_sheet_data_|. Builder&& AddUserInfo(std::string origin = std::string()) &&; Builder& AddUserInfo(std::string origin = std::string()) &;
diff --git a/components/media_message_center/media_notification_item.cc b/components/media_message_center/media_notification_item.cc index cb9a103..2ab8705 100644 --- a/components/media_message_center/media_notification_item.cc +++ b/components/media_message_center/media_notification_item.cc
@@ -54,7 +54,7 @@ MediaNotificationController* notification_controller, const std::string& request_id, const std::string& source_name, - media_session::mojom::MediaControllerPtr controller, + mojo::Remote<media_session::mojom::MediaController> controller, media_session::mojom::MediaSessionInfoPtr session_info) : controller_(notification_controller), request_id_(request_id), @@ -141,7 +141,7 @@ } void MediaNotificationItem::FlushForTesting() { - media_controller_ptr_.FlushForTesting(); + media_controller_remote_.FlushForTesting(); } bool MediaNotificationItem::ShouldShowNotification() const { @@ -193,27 +193,27 @@ if (frozen_) return; - media_session::PerformMediaSessionAction(action, media_controller_ptr_); + media_session::PerformMediaSessionAction(action, media_controller_remote_); } void MediaNotificationItem::SetController( - media_session::mojom::MediaControllerPtr controller, + mojo::Remote<media_session::mojom::MediaController> controller, media_session::mojom::MediaSessionInfoPtr session_info) { observer_receiver_.reset(); artwork_observer_receiver_.reset(); is_bound_ = true; - media_controller_ptr_ = std::move(controller); + media_controller_remote_ = std::move(controller); session_info_ = std::move(session_info); - if (media_controller_ptr_.is_bound()) { + if (media_controller_remote_.is_bound()) { // Bind an observer to the associated media controller. - media_controller_ptr_->AddObserver( + media_controller_remote_->AddObserver( observer_receiver_.BindNewPipeAndPassRemote()); // TODO(https://crbug.com/931397): Use dip to calculate the size. // Bind an observer to be notified when the artwork changes. - media_controller_ptr_->ObserveImages( + media_controller_remote_->ObserveImages( media_session::mojom::MediaSessionImageType::kArtwork, kMediaSessionNotificationArtworkMinSize, kMediaSessionNotificationArtworkDesiredSize,
diff --git a/components/media_message_center/media_notification_item.h b/components/media_message_center/media_notification_item.h index 08a3465..63f91cb 100644 --- a/components/media_message_center/media_notification_item.h +++ b/components/media_message_center/media_notification_item.h
@@ -12,8 +12,8 @@ #include "base/macros.h" #include "base/memory/weak_ptr.h" #include "base/optional.h" -#include "mojo/public/cpp/bindings/binding.h" #include "mojo/public/cpp/bindings/receiver.h" +#include "mojo/public/cpp/bindings/remote.h" #include "services/media_session/public/mojom/media_controller.mojom.h" #include "services/media_session/public/mojom/media_session.mojom.h" #include "ui/gfx/image/image_skia.h" @@ -45,11 +45,12 @@ kMaxValue = kArc, }; - MediaNotificationItem(MediaNotificationController* notification_controller, - const std::string& request_id, - const std::string& source_name, - media_session::mojom::MediaControllerPtr controller, - media_session::mojom::MediaSessionInfoPtr session_info); + MediaNotificationItem( + MediaNotificationController* notification_controller, + const std::string& request_id, + const std::string& source_name, + mojo::Remote<media_session::mojom::MediaController> controller, + media_session::mojom::MediaSessionInfoPtr session_info); ~MediaNotificationItem() override; // media_session::mojom::MediaControllerObserver: @@ -83,12 +84,13 @@ void FlushForTesting(); void SetMediaControllerForTesting( - media_session::mojom::MediaControllerPtr controller) { - media_controller_ptr_ = std::move(controller); + mojo::Remote<media_session::mojom::MediaController> controller) { + media_controller_remote_ = std::move(controller); } - void SetController(media_session::mojom::MediaControllerPtr controller, - media_session::mojom::MediaSessionInfoPtr session_info); + void SetController( + mojo::Remote<media_session::mojom::MediaController> controller, + media_session::mojom::MediaSessionInfoPtr session_info); // This will freeze the item and start a timer to destroy the item after // some time has passed. @@ -121,7 +123,7 @@ // The source of the media session (e.g. arc, web). const Source source_; - media_session::mojom::MediaControllerPtr media_controller_ptr_; + mojo::Remote<media_session::mojom::MediaController> media_controller_remote_; media_session::mojom::MediaSessionInfoPtr session_info_;
diff --git a/components/media_message_center/media_notification_view_unittest.cc b/components/media_message_center/media_notification_view_unittest.cc index c4aa88c..c372996 100644 --- a/components/media_message_center/media_notification_view_unittest.cc +++ b/components/media_message_center/media_notification_view_unittest.cc
@@ -130,7 +130,7 @@ void CreateViewFromMediaSessionInfo( media_session::mojom::MediaSessionInfoPtr session_info) { session_info->is_controllable = true; - media_session::mojom::MediaControllerPtr controller; + mojo::Remote<media_session::mojom::MediaController> controller; item_ = std::make_unique<MediaNotificationItem>( &controller_, request_id_.ToString(), std::string(), std::move(controller), std::move(session_info)); @@ -144,7 +144,7 @@ // Inject the test media controller into the item. media_controller_ = std::make_unique<TestMediaController>(); item_->SetMediaControllerForTesting( - media_controller_->CreateMediaControllerPtr()); + media_controller_->CreateMediaControllerRemote()); } void TearDown() override {
diff --git a/components/password_manager/core/browser/leak_detection/BUILD.gn b/components/password_manager/core/browser/leak_detection/BUILD.gn index 29db9fb..dee02c1 100644 --- a/components/password_manager/core/browser/leak_detection/BUILD.gn +++ b/components/password_manager/core/browser/leak_detection/BUILD.gn
@@ -45,6 +45,7 @@ "//base", "//components/password_manager/core/common", "//components/signin/public/identity_manager", + "//third_party/private-join-and-compute/src:ec_commutative_cipher", "//url", ] }
diff --git a/components/payments/content/BUILD.gn b/components/payments/content/BUILD.gn index dec5545d..25df858 100644 --- a/components/payments/content/BUILD.gn +++ b/components/payments/content/BUILD.gn
@@ -115,6 +115,8 @@ jumbo_source_set("unit_tests") { testonly = true sources = [ + "mock_identity_observer.cc", + "mock_identity_observer.h", "payment_method_manifest_table_unittest.cc", "service_worker_payment_app_factory_unittest.cc", "test_content_payment_request_delegate.cc",
diff --git a/components/payments/content/android/java/src/org/chromium/components/payments/PaymentHandlerHost.java b/components/payments/content/android/java/src/org/chromium/components/payments/PaymentHandlerHost.java index 62b3e27..da9478cc 100644 --- a/components/payments/content/android/java/src/org/chromium/components/payments/PaymentHandlerHost.java +++ b/components/payments/content/android/java/src/org/chromium/components/payments/PaymentHandlerHost.java
@@ -7,6 +7,7 @@ import org.chromium.base.annotations.CalledByNative; import org.chromium.base.annotations.JNINamespace; import org.chromium.base.annotations.NativeMethods; +import org.chromium.content_public.browser.WebContents; import org.chromium.payments.mojom.PaymentMethodChangeResponse; import java.nio.ByteBuffer; @@ -39,10 +40,12 @@ /** * Instantiates the native bridge to the payment handler host. This Java object owns the native * bridge. The caller must call destroy() when finished using this Java object. - * @param delegate The object that can communicate to the merchant renderer process. + * @param webContents The web contents in the same browser context as the payment handler. Used + * for logging in developer tools. + * @param delegate The object that can communicate to the merchant renderer process. */ - public PaymentHandlerHost(PaymentHandlerHostDelegate delegate) { - mNativePointer = PaymentHandlerHostJni.get().init(delegate); + public PaymentHandlerHost(WebContents webContents, PaymentHandlerHostDelegate delegate) { + mNativePointer = PaymentHandlerHostJni.get().init(webContents, delegate); } /** @@ -96,10 +99,12 @@ /** * Initializes the native object. The Java caller owns the returned native object and must * call destroy(nativePaymentHandlerHost) when done. - * @param delegate The object that can communicate to the merchant renderer process. + * @param webContents The web contents in the same browser context as the payment handler. + * Used for logging in developer tools. + * @param delegate The object that can communicate to the merchant renderer process. * @return The pointer to the native payment handler host bridge. */ - long init(PaymentHandlerHostDelegate delegate); + long init(WebContents webContents, PaymentHandlerHostDelegate delegate); /** * Checks whether the payment method change is currently in progress.
diff --git a/components/payments/content/android/payment_handler_host.cc b/components/payments/content/android/payment_handler_host.cc index 4364b07af..55591be 100644 --- a/components/payments/content/android/payment_handler_host.cc +++ b/components/payments/content/android/payment_handler_host.cc
@@ -8,6 +8,7 @@ #include "base/android/jni_string.h" #include "components/payments/content/android/byte_buffer_helper.h" #include "components/payments/content/android/jni_headers/PaymentHandlerHost_jni.h" +#include "content/public/browser/web_contents.h" #include "third_party/blink/public/mojom/payments/payment_handler_host.mojom.h" namespace payments { @@ -16,13 +17,19 @@ // static jlong JNI_PaymentHandlerHost_Init( JNIEnv* env, + const base::android::JavaParamRef<jobject>& web_contents, const base::android::JavaParamRef<jobject>& delegate) { - return reinterpret_cast<intptr_t>(new PaymentHandlerHost(delegate)); + return reinterpret_cast<intptr_t>( + new PaymentHandlerHost(web_contents, delegate)); } PaymentHandlerHost::PaymentHandlerHost( + const base::android::JavaParamRef<jobject>& web_contents, const base::android::JavaParamRef<jobject>& delegate) - : delegate_(delegate), payment_handler_host_(this) {} + : delegate_(delegate), + payment_handler_host_( + content::WebContents::FromJavaWebContents(web_contents), + /*delegate=*/this) {} PaymentHandlerHost::~PaymentHandlerHost() {}
diff --git a/components/payments/content/android/payment_handler_host.h b/components/payments/content/android/payment_handler_host.h index 75248e7..4643ccd 100644 --- a/components/payments/content/android/payment_handler_host.h +++ b/components/payments/content/android/payment_handler_host.h
@@ -36,9 +36,10 @@ class PaymentHandlerHost : public payments::PaymentHandlerHost::Delegate { public: // The |delegate| must implement PaymentHandlerHostDelegate from - // PaymentHandlerHost.java. - explicit PaymentHandlerHost( - const base::android::JavaParamRef<jobject>& delegate); + // PaymentHandlerHost.java. The |web_contents| should be from the same browser + // context as the payment handler and are used for logging in developr tools. + PaymentHandlerHost(const base::android::JavaParamRef<jobject>& web_contents, + const base::android::JavaParamRef<jobject>& delegate); ~PaymentHandlerHost() override; // Checks whether the payment method change is currently in progress.
diff --git a/components/payments/content/mock_identity_observer.cc b/components/payments/content/mock_identity_observer.cc new file mode 100644 index 0000000..558b0a70 --- /dev/null +++ b/components/payments/content/mock_identity_observer.cc
@@ -0,0 +1,13 @@ +// Copyright 2019 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "components/payments/content/mock_identity_observer.h" + +namespace payments { + +MockIdentityObserver::MockIdentityObserver() = default; + +MockIdentityObserver::~MockIdentityObserver() = default; + +} // namespace payments
diff --git a/components/payments/content/mock_identity_observer.h b/components/payments/content/mock_identity_observer.h new file mode 100644 index 0000000..c074c41 --- /dev/null +++ b/components/payments/content/mock_identity_observer.h
@@ -0,0 +1,31 @@ +// Copyright 2019 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef COMPONENTS_PAYMENTS_CONTENT_MOCK_IDENTITY_OBSERVER_H_ +#define COMPONENTS_PAYMENTS_CONTENT_MOCK_IDENTITY_OBSERVER_H_ + +#include <stdint.h> + +#include "base/macros.h" +#include "components/payments/content/service_worker_payment_instrument.h" +#include "testing/gmock/include/gmock/gmock.h" +#include "url/origin.h" + +namespace payments { + +class MockIdentityObserver + : public ServiceWorkerPaymentInstrument::IdentityObserver { + public: + MockIdentityObserver(); + ~MockIdentityObserver() override; + MOCK_METHOD2(SetInvokedServiceWorkerIdentity, + void(const url::Origin& origin, int64_t registration_id)); + + private: + DISALLOW_COPY_AND_ASSIGN(MockIdentityObserver); +}; + +} // namespace payments + +#endif // COMPONENTS_PAYMENTS_CONTENT_MOCK_IDENTITY_OBSERVER_H_
diff --git a/components/payments/content/payment_handler_host.cc b/components/payments/content/payment_handler_host.cc index 6f9f5c7..d694336 100644 --- a/components/payments/content/payment_handler_host.cc +++ b/components/payments/content/payment_handler_host.cc
@@ -7,14 +7,41 @@ #include <utility> #include "base/callback.h" +#include "base/strings/string_number_conversions.h" #include "components/payments/core/error_strings.h" #include "components/payments/core/native_error_strings.h" +#include "content/public/browser/browser_context.h" #include "content/public/browser/browser_thread.h" +#include "content/public/browser/devtools_background_services_context.h" +#include "content/public/browser/storage_partition.h" +#include "content/public/browser/web_contents.h" +#include "url/origin.h" namespace payments { +namespace { -PaymentHandlerHost::PaymentHandlerHost(Delegate* delegate) - : binding_(this), delegate_(delegate) { +content::DevToolsBackgroundServicesContext* GetDevTools( + content::BrowserContext* browser_context, + const url::Origin& sw_origin) { + DCHECK_CURRENTLY_ON(content::BrowserThread::UI); + auto* storage_partition = content::BrowserContext::GetStoragePartitionForSite( + browser_context, sw_origin.GetURL(), /*can_create=*/true); + if (!storage_partition) + return nullptr; + + auto* dev_tools = storage_partition->GetDevToolsBackgroundServicesContext(); + return dev_tools && dev_tools->IsRecording( + content::DevToolsBackgroundService::kPaymentHandler) + ? dev_tools + : nullptr; +} + +} // namespace + +PaymentHandlerHost::PaymentHandlerHost(content::WebContents* web_contents, + Delegate* delegate) + : binding_(this), web_contents_(web_contents), delegate_(delegate) { + DCHECK(web_contents_); DCHECK(delegate_); } @@ -37,6 +64,45 @@ if (!change_payment_method_callback_) return; + auto* dev_tools = + GetDevTools(web_contents_->GetBrowserContext(), sw_origin_for_logs_); + if (dev_tools) { + std::map<std::string, std::string> data = {{"Error", response->error}}; + + if (response->total) { + data["Total Currency"] = response->total->currency; + data["Total Value"] = response->total->value; + } + + if (response->stringified_payment_method_errors) { + data["Payment Method Errors"] = + *response->stringified_payment_method_errors; + } + + if (response->modifiers) { + for (size_t i = 0; i < response->modifiers->size(); ++i) { + std::string prefix = + "Modifier" + (response->modifiers->size() == 1 + ? "" + : " #" + base::NumberToString(i)); + const auto& modifier = response->modifiers->at(i); + data.emplace(prefix + " Method Name", + modifier->method_data->method_name); + data.emplace(prefix + " Method Data", + modifier->method_data->stringified_data); + if (!modifier->total) + continue; + data.emplace(prefix + " Total Currency", modifier->total->currency); + data.emplace(prefix + " Total Value", modifier->total->value); + } + } + + dev_tools->LogBackgroundServiceEvent( + registration_id_for_logs_, sw_origin_for_logs_, + content::DevToolsBackgroundService::kPaymentHandler, "Update with", + /*instance_id=*/payment_request_id_for_logs_, data); + } + std::move(change_payment_method_callback_).Run(std::move(response)); } @@ -82,6 +148,18 @@ return; } + auto* dev_tools = + GetDevTools(web_contents_->GetBrowserContext(), sw_origin_for_logs_); + if (dev_tools) { + dev_tools->LogBackgroundServiceEvent( + registration_id_for_logs_, sw_origin_for_logs_, + content::DevToolsBackgroundService::kPaymentHandler, + "Change payment method", + /*instance_id=*/payment_request_id_for_logs_, + {{"Method Name", method_data->method_name}, + {"Method Data", method_data->stringified_data}}); + } + change_payment_method_callback_ = std::move(callback); }
diff --git a/components/payments/content/payment_handler_host.h b/components/payments/content/payment_handler_host.h index 0389701..e0749c2 100644 --- a/components/payments/content/payment_handler_host.h +++ b/components/payments/content/payment_handler_host.h
@@ -5,6 +5,7 @@ #ifndef COMPONENTS_PAYMENTS_CONTENT_PAYMENT_HANDLER_HOST_H_ #define COMPONENTS_PAYMENTS_CONTENT_PAYMENT_HANDLER_HOST_H_ +#include <stdint.h> #include <string> #include "base/callback_forward.h" @@ -12,6 +13,11 @@ #include "base/memory/weak_ptr.h" #include "mojo/public/cpp/bindings/binding.h" #include "third_party/blink/public/mojom/payments/payment_handler_host.mojom.h" +#include "url/origin.h" + +namespace content { +class WebContents; +} // namespace content namespace payments { @@ -19,7 +25,7 @@ // merchant renderer process. class PaymentHandlerHost : public mojom::PaymentHandlerHost { public: - // The interfce to be implemented by the object that can communicate to the + // The interface to be implemented by the object that can communicate to the // merchant's renderer process. class Delegate { public: @@ -32,10 +38,30 @@ }; // The |delegate| cannot be null and must outlive this object. Typically this - // is accomplished by the |delegate| owning this object. - explicit PaymentHandlerHost(Delegate* delegate); + // is accomplished by the |delegate| owning this object. The |web_contents| is + // used for developer tools logging and should be from the same browser + // context as the payment handler. + PaymentHandlerHost(content::WebContents* web_contents, Delegate* delegate); ~PaymentHandlerHost() override; + // Sets the origin of the payment handler / service worker registration scope. + // Used for developer tools logging. + void set_sw_origin_for_logs(const url::Origin& origin) { + sw_origin_for_logs_ = origin; + } + + // Sets the registration identifier of the payment handler / service worker. + // Used for developer tools logging. + void set_registration_id_for_logs(int64_t id) { + registration_id_for_logs_ = id; + } + + // Sets the identifier for the Payment Request object. Used for developer + // tools logging. + void set_payment_request_id_for_logs(const std::string& id) { + payment_request_id_for_logs_ = id; + } + // Returns "true" when the payment handler has changed the payment method, but // has not received the response from the merchant yet. bool is_changing_payment_method() const { @@ -71,9 +97,24 @@ // browser process. mojo::Binding<mojom::PaymentHandlerHost> binding_; + // The merchant page that invoked the Payment Request API. + content::WebContents* web_contents_; + // Not null and outlives this object. Owns this object. Delegate* delegate_; + // The origin of the payment handler / service worker registration scope. Used + // for developer tools logging. + url::Origin sw_origin_for_logs_; + + // The registration identifier for the payment handler / service worker. Used + // for developer tools logging. + int64_t registration_id_for_logs_ = -1; + + // The identifier for the Payment Request object. Used for developer tools + // logging. + std::string payment_request_id_for_logs_; + base::WeakPtrFactory<PaymentHandlerHost> weak_ptr_factory_{this}; DISALLOW_COPY_AND_ASSIGN(PaymentHandlerHost);
diff --git a/components/payments/content/payment_instrument_unittest.cc b/components/payments/content/payment_instrument_unittest.cc index a801513..2d66e23a 100644 --- a/components/payments/content/payment_instrument_unittest.cc +++ b/components/payments/content/payment_instrument_unittest.cc
@@ -10,6 +10,7 @@ #include "components/autofill/core/browser/autofill_test_utils.h" #include "components/autofill/core/browser/data_model/autofill_profile.h" #include "components/autofill/core/browser/data_model/credit_card.h" +#include "components/payments/content/mock_identity_observer.h" #include "components/payments/content/service_worker_payment_instrument.h" #include "components/payments/core/autofill_payment_instrument.h" #include "components/payments/core/mock_payment_request_delegate.h" @@ -49,7 +50,7 @@ return std::make_unique<ServiceWorkerPaymentInstrument>( &browser_context_, GURL("https://testmerchant.com"), GURL("https://testmerchant.com/bobpay"), spec_.get(), - std::move(stored_app), &delegate_); + std::move(stored_app), &delegate_, &identity_observer_); } autofill::CreditCard& local_credit_card() { return local_card_; } @@ -74,6 +75,7 @@ autofill::CreditCard local_card_; std::vector<autofill::AutofillProfile*> billing_profiles_; MockPaymentRequestDelegate delegate_; + MockIdentityObserver identity_observer_; std::unique_ptr<PaymentRequestSpec> spec_; DISALLOW_COPY_AND_ASSIGN(PaymentInstrumentTest);
diff --git a/components/payments/content/payment_request.cc b/components/payments/content/payment_request.cc index 1ba4771..4fe08ce 100644 --- a/components/payments/content/payment_request.cc +++ b/components/payments/content/payment_request.cc
@@ -87,7 +87,7 @@ display_manager_(display_manager), display_handle_(nullptr), binding_(this, std::move(request)), - payment_handler_host_(this), + payment_handler_host_(web_contents_, this), top_level_origin_(url_formatter::FormatUrlForSecurityDisplay( web_contents_->GetLastCommittedURL())), frame_origin_(url_formatter::FormatUrlForSecurityDisplay( @@ -165,12 +165,13 @@ } spec_ = std::make_unique<PaymentRequestSpec>( - std::move(options), std::move(details), std::move(method_data), this, - delegate_->GetApplicationLocale()); + std::move(options), std::move(details), std::move(method_data), + /*observer=*/this, delegate_->GetApplicationLocale()); state_ = std::make_unique<PaymentRequestState>( - web_contents_, top_level_origin_, frame_origin_, spec_.get(), this, - delegate_->GetApplicationLocale(), delegate_->GetPersonalDataManager(), - delegate_.get(), &journey_logger_); + web_contents_, top_level_origin_, frame_origin_, spec_.get(), + /*delegate=*/this, delegate_->GetApplicationLocale(), + delegate_->GetPersonalDataManager(), delegate_.get(), + /*sw_identity_observer=*/this, &journey_logger_); journey_logger_.SetRequestedInformation( spec_->request_shipping(), spec_->request_payer_email(), @@ -194,6 +195,8 @@ android_pay_url), /*requested_method_other=*/non_google_it != spec_->url_payment_method_identifiers().end()); + + payment_handler_host_.set_payment_request_id_for_logs(*spec_->details().id); } void PaymentRequest::Show(bool is_user_gesture, bool wait_for_updated_details) { @@ -210,6 +213,7 @@ } is_show_called_ = true; + journey_logger_.SetTriggerTime(); // A tab can display only one PaymentRequest UI at a time. display_handle_ = display_manager_->TryShow(delegate_.get()); @@ -616,6 +620,12 @@ client_->OnPayerDetailChange(std::move(payer_info)); } +void PaymentRequest::SetInvokedServiceWorkerIdentity(const url::Origin& origin, + int64_t registration_id) { + payment_handler_host_.set_sw_origin_for_logs(origin); + payment_handler_host_.set_registration_id_for_logs(registration_id); +} + void PaymentRequest::UserCancelled() { // If |client_| is not bound, then the object is already being destroyed as // a result of a renderer event.
diff --git a/components/payments/content/payment_request.h b/components/payments/content/payment_request.h index 4b4f766..26b532d 100644 --- a/components/payments/content/payment_request.h +++ b/components/payments/content/payment_request.h
@@ -15,6 +15,7 @@ #include "components/payments/content/payment_request_display_manager.h" #include "components/payments/content/payment_request_spec.h" #include "components/payments/content/payment_request_state.h" +#include "components/payments/content/service_worker_payment_instrument.h" #include "components/payments/core/journey_logger.h" #include "mojo/public/cpp/bindings/binding.h" #include "mojo/public/cpp/bindings/interface_request.h" @@ -40,7 +41,8 @@ class PaymentRequest : public mojom::PaymentRequest, public PaymentHandlerHost::Delegate, public PaymentRequestSpec::Observer, - public PaymentRequestState::Delegate { + public PaymentRequestState::Delegate, + public ServiceWorkerPaymentInstrument::IdentityObserver { public: class ObserverForTest { public: @@ -93,6 +95,10 @@ void OnShippingAddressSelected(mojom::PaymentAddressPtr address) override; void OnPayerInfoSelected(mojom::PayerDetailPtr payer_info) override; + // ServiceWorkerPaymentInstrument::IdentityObserver: + void SetInvokedServiceWorkerIdentity(const url::Origin& origin, + int64_t registration_id) override; + // Called when the user explicitly cancelled the flow. Will send a message // to the renderer which will indirectly destroy this object (through // OnConnectionTerminated).
diff --git a/components/payments/content/payment_request_state.cc b/components/payments/content/payment_request_state.cc index 8b4b0dd2..12695a9 100644 --- a/components/payments/content/payment_request_state.cc +++ b/components/payments/content/payment_request_state.cc
@@ -41,6 +41,7 @@ const std::string& app_locale, autofill::PersonalDataManager* personal_data_manager, ContentPaymentRequestDelegate* payment_request_delegate, + ServiceWorkerPaymentInstrument::IdentityObserver* sw_identity_observer, JourneyLogger* journey_logger) : is_ready_to_pay_(false), get_all_instruments_finished_(true), @@ -60,7 +61,9 @@ selected_instrument_(nullptr), number_of_pending_sw_payment_instruments_(0), payment_request_delegate_(payment_request_delegate), + sw_identity_observer_(sw_identity_observer), profile_comparator_(app_locale, *spec) { + DCHECK(sw_identity_observer_); if (base::FeatureList::IsEnabled(::features::kServiceWorkerPaymentApps)) { DCHECK(web_contents); get_all_instruments_finished_ = false; @@ -108,7 +111,8 @@ std::unique_ptr<ServiceWorkerPaymentInstrument> instrument = std::make_unique<ServiceWorkerPaymentInstrument>( web_contents->GetBrowserContext(), top_level_origin, frame_origin, - spec_, std::move(app.second), payment_request_delegate_); + spec_, std::move(app.second), payment_request_delegate_, + sw_identity_observer_); instrument->ValidateCanMakePayment( base::BindOnce(&PaymentRequestState::OnSWPaymentInstrumentValidated, weak_ptr_factory_.GetWeakPtr())); @@ -120,7 +124,7 @@ std::make_unique<ServiceWorkerPaymentInstrument>( web_contents, top_level_origin, frame_origin, spec_, std::move(installable_app.second), installable_app.first.spec(), - payment_request_delegate_); + payment_request_delegate_, sw_identity_observer_); instrument->ValidateCanMakePayment( base::BindOnce(&PaymentRequestState::OnSWPaymentInstrumentValidated, weak_ptr_factory_.GetWeakPtr()));
diff --git a/components/payments/content/payment_request_state.h b/components/payments/content/payment_request_state.h index 1701c43..253165ae3 100644 --- a/components/payments/content/payment_request_state.h +++ b/components/payments/content/payment_request_state.h
@@ -16,6 +16,7 @@ #include "components/payments/content/payment_request_spec.h" #include "components/payments/content/payment_response_helper.h" #include "components/payments/content/service_worker_payment_app_factory.h" +#include "components/payments/content/service_worker_payment_instrument.h" #include "components/payments/core/journey_logger.h" #include "components/payments/core/payments_profile_comparator.h" #include "content/public/browser/payment_app_provider.h" @@ -33,7 +34,6 @@ class ContentPaymentRequestDelegate; class PaymentInstrument; -class ServiceWorkerPaymentInstrument; // Keeps track of the information currently selected by the user and whether the // user is ready to pay. Uses information from the PaymentRequestSpec, which is @@ -106,15 +106,17 @@ base::OnceCallback<void(bool methods_supported, const std::string& error_message)>; - PaymentRequestState(content::WebContents* web_contents, - const GURL& top_level_origin, - const GURL& frame_origin, - PaymentRequestSpec* spec, - Delegate* delegate, - const std::string& app_locale, - autofill::PersonalDataManager* personal_data_manager, - ContentPaymentRequestDelegate* payment_request_delegate, - JourneyLogger* journey_logger); + PaymentRequestState( + content::WebContents* web_contents, + const GURL& top_level_origin, + const GURL& frame_origin, + PaymentRequestSpec* spec, + Delegate* delegate, + const std::string& app_locale, + autofill::PersonalDataManager* personal_data_manager, + ContentPaymentRequestDelegate* payment_request_delegate, + ServiceWorkerPaymentInstrument::IdentityObserver* sw_identity_observer, + JourneyLogger* journey_logger); ~PaymentRequestState() override; // PaymentResponseHelper::Delegate @@ -371,6 +373,7 @@ std::vector<std::unique_ptr<PaymentInstrument>> available_instruments_; ContentPaymentRequestDelegate* payment_request_delegate_; + ServiceWorkerPaymentInstrument::IdentityObserver* sw_identity_observer_; std::unique_ptr<PaymentResponseHelper> response_helper_;
diff --git a/components/payments/content/payment_request_state_unittest.cc b/components/payments/content/payment_request_state_unittest.cc index 866bb9a..ed1dcd4 100644 --- a/components/payments/content/payment_request_state_unittest.cc +++ b/components/payments/content/payment_request_state_unittest.cc
@@ -15,6 +15,7 @@ #include "components/autofill/core/browser/data_model/autofill_profile.h" #include "components/autofill/core/browser/data_model/credit_card.h" #include "components/autofill/core/browser/test_personal_data_manager.h" +#include "components/payments/content/mock_identity_observer.h" #include "components/payments/content/payment_request_spec.h" #include "components/payments/content/test_content_payment_request_delegate.h" #include "components/payments/core/journey_logger.h" @@ -79,7 +80,7 @@ nullptr /* context */, GURL("https://example.com"), GURL("https://example.com/pay"), spec_.get(), this, "en-US", &test_personal_data_manager_, &test_payment_request_delegate_, - &journey_logger_); + &identity_observer_, &journey_logger_); state_->AddObserver(this); } @@ -137,6 +138,7 @@ mojom::PaymentAddressPtr selected_shipping_address_; autofill::TestPersonalDataManager test_personal_data_manager_; TestContentPaymentRequestDelegate test_payment_request_delegate_; + MockIdentityObserver identity_observer_; JourneyLogger journey_logger_; // Test data.
diff --git a/components/payments/content/service_worker_payment_instrument.cc b/components/payments/content/service_worker_payment_instrument.cc index ecd2644..204e851 100644 --- a/components/payments/content/service_worker_payment_instrument.cc +++ b/components/payments/content/service_worker_payment_instrument.cc
@@ -31,7 +31,8 @@ const GURL& frame_origin, const PaymentRequestSpec* spec, std::unique_ptr<content::StoredPaymentApp> stored_payment_app_info, - PaymentRequestDelegate* payment_request_delegate) + PaymentRequestDelegate* payment_request_delegate, + IdentityObserver* identity_observer) : PaymentInstrument(0, PaymentInstrument::Type::SERVICE_WORKER_APP), browser_context_(browser_context), top_origin_(top_origin), @@ -40,6 +41,7 @@ stored_payment_app_info_(std::move(stored_payment_app_info)), delegate_(nullptr), payment_request_delegate_(payment_request_delegate), + identity_observer_(identity_observer), can_make_payment_result_(false), has_enrolled_instrument_result_(false), needs_installation_(false) { @@ -47,6 +49,7 @@ DCHECK(top_origin_.is_valid()); DCHECK(frame_origin_.is_valid()); DCHECK(spec_); + DCHECK(identity_observer_); if (stored_payment_app_info_->icon) { icon_image_ = @@ -67,13 +70,15 @@ const PaymentRequestSpec* spec, std::unique_ptr<WebAppInstallationInfo> installable_payment_app_info, const std::string& enabled_method, - PaymentRequestDelegate* payment_request_delegate) + PaymentRequestDelegate* payment_request_delegate, + IdentityObserver* identity_observer) : PaymentInstrument(0, PaymentInstrument::Type::SERVICE_WORKER_APP), top_origin_(top_origin), frame_origin_(frame_origin), spec_(spec), delegate_(nullptr), payment_request_delegate_(payment_request_delegate), + identity_observer_(identity_observer), can_make_payment_result_(false), has_enrolled_instrument_result_(false), needs_installation_(true), @@ -84,6 +89,7 @@ DCHECK(top_origin_.is_valid()); DCHECK(frame_origin_.is_valid()); DCHECK(spec_); + DCHECK(identity_observer_); if (installable_web_app_info_->icon) { icon_image_ = @@ -231,12 +237,19 @@ installable_web_app_info_->sw_js_url, installable_web_app_info_->sw_scope, installable_web_app_info_->sw_use_cache, installable_enabled_method_, + base::BindOnce( + &IdentityObserver::SetInvokedServiceWorkerIdentity, + base::Unretained(identity_observer_), + url::Origin::Create(GURL(installable_web_app_info_->sw_scope))), base::BindOnce(&ServiceWorkerPaymentInstrument::OnPaymentAppInvoked, weak_ptr_factory_.GetWeakPtr())); } else { + url::Origin sw_origin = + url::Origin::Create(stored_payment_app_info_->scope); + identity_observer_->SetInvokedServiceWorkerIdentity( + sw_origin, stored_payment_app_info_->registration_id); content::PaymentAppProvider::GetInstance()->InvokePaymentApp( - browser_context_, stored_payment_app_info_->registration_id, - url::Origin::Create(stored_payment_app_info_->scope), + browser_context_, stored_payment_app_info_->registration_id, sw_origin, CreatePaymentRequestEventData(), base::BindOnce(&ServiceWorkerPaymentInstrument::OnPaymentAppInvoked, weak_ptr_factory_.GetWeakPtr()));
diff --git a/components/payments/content/service_worker_payment_instrument.h b/components/payments/content/service_worker_payment_instrument.h index 7fd2df02..b43de27 100644 --- a/components/payments/content/service_worker_payment_instrument.h +++ b/components/payments/content/service_worker_payment_instrument.h
@@ -5,6 +5,8 @@ #ifndef COMPONENTS_PAYMENTS_CONTENT_SERVICE_WORKER_PAYMENT_INSTRUMENT_H_ #define COMPONENTS_PAYMENTS_CONTENT_SERVICE_WORKER_PAYMENT_INSTRUMENT_H_ +#include <stdint.h> + #include "components/payments/content/payment_request_spec.h" #include "components/payments/content/web_app_manifest.h" #include "components/payments/core/payment_instrument.h" @@ -18,6 +20,10 @@ class WebContents; } // namespace content +namespace url { +class Origin; +} // namespace url + namespace payments { class PaymentRequestDelegate; @@ -25,6 +31,21 @@ // Represents a service worker based payment app. class ServiceWorkerPaymentInstrument : public PaymentInstrument { public: + // Observer for identity of the service worker, which is known ahead of time + // when already installed, but may be unknown at first when using just-in-time + // installation. + class IdentityObserver { + public: + virtual ~IdentityObserver() {} + + // Notifies the observer that the service worker registration has the + // |registration_id| and its scope has |origin|. Called exactly once after + // InvokePaymentApp(). Called before the service worker actually receives + // the 'paymentrequest' event. + virtual void SetInvokedServiceWorkerIdentity(const url::Origin& origin, + int64_t registration_id) = 0; + }; + // This constructor is used for a payment app that has been installed in // Chrome. ServiceWorkerPaymentInstrument( @@ -33,9 +54,10 @@ const GURL& frame_origin, const PaymentRequestSpec* spec, std::unique_ptr<content::StoredPaymentApp> stored_payment_app_info, - PaymentRequestDelegate* payment_request_delegate); + PaymentRequestDelegate* payment_request_delegate, + IdentityObserver* identity_observer); - // This contructor is used for a payment app that has not been installed in + // This constructor is used for a payment app that has not been installed in // Chrome but can be installed when paying with it. ServiceWorkerPaymentInstrument( content::WebContents* web_contents, @@ -44,7 +66,8 @@ const PaymentRequestSpec* spec, std::unique_ptr<WebAppInstallationInfo> installable_payment_app_info, const std::string& enabled_methods, - PaymentRequestDelegate* payment_request_delegate); + PaymentRequestDelegate* payment_request_delegate, + IdentityObserver* identity_observer); ~ServiceWorkerPaymentInstrument() override; // The callback for ValidateCanMakePayment. @@ -113,6 +136,9 @@ // Weak pointer that must outlive this object. PaymentRequestDelegate* payment_request_delegate_; + // Weak pointer that must outlive this object. + IdentityObserver* identity_observer_; + mojom::PaymentHandlerHostPtrInfo payment_handler_host_; // PaymentAppProvider::CanMakePayment result of this payment instrument.
diff --git a/components/payments/content/service_worker_payment_instrument_unittest.cc b/components/payments/content/service_worker_payment_instrument_unittest.cc index 36fe9710..8f2de901 100644 --- a/components/payments/content/service_worker_payment_instrument_unittest.cc +++ b/components/payments/content/service_worker_payment_instrument_unittest.cc
@@ -9,6 +9,7 @@ #include "base/macros.h" #include "base/strings/utf_string_conversions.h" #include "base/test/scoped_feature_list.h" +#include "components/payments/content/mock_identity_observer.h" #include "components/payments/core/mock_payment_request_delegate.h" #include "content/public/browser/stored_payment_app.h" #include "content/public/common/content_features.h" @@ -120,7 +121,7 @@ instrument_ = std::make_unique<ServiceWorkerPaymentInstrument>( &browser_context_, GURL("https://testmerchant.com"), GURL("https://testmerchant.com/bobpay"), spec_.get(), - std::move(stored_app), &delegate_); + std::move(stored_app), &delegate_, &identity_observer_); } ServiceWorkerPaymentInstrument* GetInstrument() { return instrument_.get(); } @@ -135,6 +136,7 @@ private: MockPaymentRequestDelegate delegate_; + MockIdentityObserver identity_observer_; content::TestBrowserThreadBundle thread_bundle_; content::TestBrowserContext browser_context_;
diff --git a/components/payments/core/journey_logger.cc b/components/payments/core/journey_logger.cc index 048f263..c8867586 100644 --- a/components/payments/core/journey_logger.cc +++ b/components/payments/core/journey_logger.cc
@@ -73,6 +73,15 @@ return seen_true_bit; } +// Records time to checkout for payment requests. The 5-minute max is chosen +// since the payment handler window times out after 5 minutes. +void RecordTimeToCheckoutUmaHistograms(const std::string name, + const base::TimeDelta time_to_checkout) { + UmaHistogramCustomTimes( + name, time_to_checkout, base::TimeDelta::FromMilliseconds(1) /* min */, + base::TimeDelta::FromMinutes(5) /* max */, 100 /*bucket count*/); +} + enum class TransactionSize { kZeroTransaction = 0, kMicroTransaction = 1, @@ -269,6 +278,7 @@ has_recorded_ = true; RecordEventsMetric(completion_status); + RecordTimeToCheckout(completion_status); // These following metrics only make sense if the Payment Request was // triggered. @@ -359,6 +369,72 @@ .Record(ukm::UkmRecorder::Get()); } +void JourneyLogger::RecordTimeToCheckout( + CompletionStatus completion_status) const { + const base::TimeDelta time_to_checkout = + base::TimeTicks::Now() - trigger_time_; + const std::string histogram_name = "PaymentRequest.TimeToCheckout"; + + // Whether or not the payment sheet was shown shown. + std::string ui_show_suffix; + if (events_ & EVENT_SHOWN) + ui_show_suffix = ".Shown"; + else if (events_ & EVENT_SKIPPED_SHOW) + ui_show_suffix = ".SkippedShow"; + else // User aborted before request.show() + ui_show_suffix = ".BeforeShow"; + + std::string completion_suffix; + switch (completion_status) { + case COMPLETION_STATUS_COMPLETED: { + completion_suffix = ".Completed"; + // Record time to checkout for completed requests separated by payment + // sheet shown status. Requests can complete only after request.show() + // call. + DCHECK_NE(".BeforeShow", ui_show_suffix); + RecordTimeToCheckoutUmaHistograms( + histogram_name + ".Completed" + ui_show_suffix, time_to_checkout); + + // Record time to checkout for completed requests separated by payment + // sheet shown status and selected method. + std::string selected_method_suffix; + if (events_ & EVENT_SELECTED_CREDIT_CARD) { + selected_method_suffix = ".BasicCard"; + } else if (events_ & EVENT_SELECTED_GOOGLE) { + selected_method_suffix = ".Google"; + } else { + DCHECK(events_ & EVENT_SELECTED_OTHER); + selected_method_suffix = ".Other"; + } + RecordTimeToCheckoutUmaHistograms(histogram_name + ".Completed" + + ui_show_suffix + + selected_method_suffix, + time_to_checkout); + break; + } + case COMPLETION_STATUS_USER_ABORTED: { + completion_suffix = ".UserAborted"; + // Record time to checkout for requests aborted by user separated by + // payment sheet shown status. + RecordTimeToCheckoutUmaHistograms( + histogram_name + ".UserAborted" + ui_show_suffix, time_to_checkout); + break; + } + case COMPLETION_STATUS_OTHER_ABORTED: + completion_suffix = ".OtherAborted"; + break; + case COMPLETION_STATUS_COULD_NOT_SHOW: + // Do not record checkout duration when payment sheet could not shown. + return; + default: + NOTREACHED(); + } + // Record time to checkout for payment reuqests separated by completion + // status. + RecordTimeToCheckoutUmaHistograms(histogram_name + completion_suffix, + time_to_checkout); +} + void JourneyLogger::ValidateEventBits() const { std::vector<bool> bit_vector; @@ -422,4 +498,8 @@ return (events_ & EVENT_SHOWN) > 0 || (events_ & EVENT_SKIPPED_SHOW) > 0; } +void JourneyLogger::SetTriggerTime() { + trigger_time_ = base::TimeTicks::Now(); +} + } // namespace payments
diff --git a/components/payments/core/journey_logger.h b/components/payments/core/journey_logger.h index 6fce143..9939b13 100644 --- a/components/payments/core/journey_logger.h +++ b/components/payments/core/journey_logger.h
@@ -9,6 +9,7 @@ #include <unordered_map> #include "base/macros.h" +#include "base/time/time.h" #include "services/metrics/public/cpp/ukm_source_id.h" namespace payments { @@ -189,12 +190,15 @@ // reason. void SetNotShown(NotShownReason reason); - // Records the transcation amount separated by currency and completion status - // (complete vs triggered). + // Records the transcation amount after converting to USD separated by + // completion status (complete vs triggered). void RecordTransactionAmount(std::string currency, const std::string& value, bool completed); + // Records when Payment Request .show is called. + void SetTriggerTime(); + private: static const int NUMBER_OF_SECTIONS = 3; @@ -238,6 +242,9 @@ // Payment Request. void RecordEventsMetric(CompletionStatus completion_status); + // Records the time between request.show() and request completion/abort. + void RecordTimeToCheckout(CompletionStatus completion_status) const; + // Validates the recorded event sequence during the Payment Request. void ValidateEventBits() const; @@ -258,6 +265,10 @@ // multiple recording. Triggered is the first index and Completed the second. bool has_recorded_transaction_amount_[2] = {false}; + // Stores the time that request.show() is called. This is used to record + // checkout duration. + base::TimeTicks trigger_time_; + ukm::SourceId source_id_; DISALLOW_COPY_AND_ASSIGN(JourneyLogger);
diff --git a/components/signin/internal/identity_manager/android/BUILD.gn b/components/signin/internal/identity_manager/android/BUILD.gn new file mode 100644 index 0000000..d9b022f --- /dev/null +++ b/components/signin/internal/identity_manager/android/BUILD.gn
@@ -0,0 +1,9 @@ +import("//build/config/android/rules.gni") + +generate_jni("jni_headers") { + namespace = "signin" + sources = [ + "//components/signin/public/identity_manager/android/java/src/org/chromium/components/signin/identitymanager/CoreAccountInfo.java", + "//components/signin/public/identity_manager/android/java/src/org/chromium/components/signin/identitymanager/IdentityManager.java", + ] +}
diff --git a/components/signin/internal/identity_manager/profile_oauth2_token_service_unittest.cc b/components/signin/internal/identity_manager/profile_oauth2_token_service_unittest.cc index cf2a880..ff8055e 100644 --- a/components/signin/internal/identity_manager/profile_oauth2_token_service_unittest.cc +++ b/components/signin/internal/identity_manager/profile_oauth2_token_service_unittest.cc
@@ -7,8 +7,8 @@ #include <stddef.h> #include <string> -#include "base/message_loop/message_loop.h" #include "base/run_loop.h" +#include "base/test/scoped_task_environment.h" #include "base/threading/platform_thread.h" #include "components/prefs/testing_pref_service.h" #include "components/signin/internal/identity_manager/fake_profile_oauth2_token_service_delegate.h" @@ -116,7 +116,9 @@ } protected: - base::MessageLoopForIO message_loop_; // net:: stuff needs IO message loop. + base::test::ScopedTaskEnvironment scoped_task_environment_{ + base::test::ScopedTaskEnvironment::MainThreadType:: + IO}; // net:: stuff needs IO message loop. network::TestURLLoaderFactory* test_url_loader_factory_ = nullptr; FakeProfileOAuth2TokenServiceDelegate* delegate_ptr_ = nullptr; // Not owned. std::unique_ptr<ProfileOAuth2TokenService> oauth2_service_;
diff --git a/components/signin/public/identity_manager/BUILD.gn b/components/signin/public/identity_manager/BUILD.gn index 28717d1..149b8c4 100644 --- a/components/signin/public/identity_manager/BUILD.gn +++ b/components/signin/public/identity_manager/BUILD.gn
@@ -59,6 +59,11 @@ deps += [ "ios" ] } + if (is_android) { + deps += + [ "//components/signin/internal/identity_manager/android:jni_headers" ] + } + allow_circular_includes_from = [ # This target is a pair with internal/identity_manager. They always go # together and include headers from each other.
diff --git a/components/signin/public/identity_manager/account_info.cc b/components/signin/public/identity_manager/account_info.cc index afe459f..94350088 100644 --- a/components/signin/public/identity_manager/account_info.cc +++ b/components/signin/public/identity_manager/account_info.cc
@@ -5,6 +5,11 @@ #include "components/signin/public/identity_manager/account_info.h" #include "google_apis/gaia/gaia_auth_util.h" +#if defined(OS_ANDROID) +#include "base/android/jni_string.h" +#include "components/signin/internal/identity_manager/android/jni_headers/CoreAccountInfo_jni.h" +#endif + namespace { // Updates |field| with |new_value| if non-empty and different; if |new_value| @@ -119,3 +124,16 @@ << account.is_under_advanced_protection; return os; } + +#if defined(OS_ANDROID) +base::android::ScopedJavaLocalRef<jobject> ConvertToJavaCoreAccountInfo( + const CoreAccountInfo& account_info) { + if (account_info.IsEmpty()) + return base::android::ScopedJavaLocalRef<jobject>(); + JNIEnv* env = base::android::AttachCurrentThread(); + return signin::Java_CoreAccountInfo_Constructor( + env, + base::android::ConvertUTF8ToJavaString(env, account_info.account_id.id), + base::android::ConvertUTF8ToJavaString(env, account_info.email)); +} +#endif
diff --git a/components/signin/public/identity_manager/account_info.h b/components/signin/public/identity_manager/account_info.h index e8d5a61a..c5b0359 100644 --- a/components/signin/public/identity_manager/account_info.h +++ b/components/signin/public/identity_manager/account_info.h
@@ -7,9 +7,14 @@ #include <string> +#include "build/build_config.h" #include "google_apis/gaia/core_account_id.h" #include "ui/gfx/image/image.h" +#if defined(OS_ANDROID) +#include "base/android/scoped_java_ref.h" +#endif + // Value representing no hosted domain associated with an account. extern const char kNoHostedDomainFound[]; @@ -74,4 +79,10 @@ bool operator!=(const CoreAccountInfo& l, const CoreAccountInfo& r); std::ostream& operator<<(std::ostream& os, const CoreAccountInfo& account); +#if defined(OS_ANDROID) +// Constructs a Java CoreAccountInfo from the provided C++ CoreAccountInfo +base::android::ScopedJavaLocalRef<jobject> ConvertToJavaCoreAccountInfo( + const CoreAccountInfo& account_info); +#endif + #endif // COMPONENTS_SIGNIN_PUBLIC_IDENTITY_MANAGER_ACCOUNT_INFO_H_
diff --git a/components/signin/public/identity_manager/android/BUILD.gn b/components/signin/public/identity_manager/android/BUILD.gn new file mode 100644 index 0000000..6d96dc4 --- /dev/null +++ b/components/signin/public/identity_manager/android/BUILD.gn
@@ -0,0 +1,19 @@ +import("//build/config/android/rules.gni") + +android_library("java") { + deps = [ + "//base:base_java", + "//base:jni_java", + "//components/signin/core/browser/android:java", + "//third_party/android_deps:android_support_v4_java", + "//third_party/android_deps:com_android_support_support_annotations_java", + ] + + java_files = [ + "java/src/org/chromium/components/signin/identitymanager/IdentityManager.java", + "java/src/org/chromium/components/signin/identitymanager/CoreAccountId.java", + "java/src/org/chromium/components/signin/identitymanager/CoreAccountInfo.java", + ] + + annotation_processor_deps = [ "//base/android/jni_generator:jni_processor" ] +}
diff --git a/components/signin/public/identity_manager/android/DEPS b/components/signin/public/identity_manager/android/DEPS new file mode 100644 index 0000000..d803ba1 --- /dev/null +++ b/components/signin/public/identity_manager/android/DEPS
@@ -0,0 +1,5 @@ +specific_include_rules = { + "CoreAccountInfo.java": [ + "+components/signin/core/browser/android/java/src/org/chromium/components/signin/AccountManagerFacade.java" + ], +}
diff --git a/components/signin/public/identity_manager/android/java/src/org/chromium/components/signin/identitymanager/CoreAccountId.java b/components/signin/public/identity_manager/android/java/src/org/chromium/components/signin/identitymanager/CoreAccountId.java new file mode 100644 index 0000000..e690e4a --- /dev/null +++ b/components/signin/public/identity_manager/android/java/src/org/chromium/components/signin/identitymanager/CoreAccountId.java
@@ -0,0 +1,51 @@ +// Copyright 2019 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +package org.chromium.components.signin.identitymanager; + +import android.support.annotation.NonNull; + +/** + * A wrapper around Gaia ID that represents a stable account identifier. + * + * This wrapper helps to make sure that code using accounts doesn't accidentally use account name in + * place of Gaia ID and vice versa. + * + * This class has a native counterpart called CoreAccountId. + */ +public class CoreAccountId { + private final String mGaiaId; + + /** + * Constructs a new CoreAccountId from a String representation of Gaia ID. + */ + public CoreAccountId(@NonNull String gaiaId) { + assert gaiaId != null; + // Check that a user email is not used by mistake. + assert !gaiaId.contains("@"); + + mGaiaId = gaiaId; + } + + public String getGaiaIdAsString() { + return mGaiaId; + } + + @Override + public String toString() { + return mGaiaId; + } + + @Override + public int hashCode() { + return mGaiaId.hashCode(); + } + + @Override + public boolean equals(Object obj) { + if (!(obj instanceof CoreAccountId)) return false; + CoreAccountId other = (CoreAccountId) obj; + return mGaiaId.equals(other.mGaiaId); + } +}
diff --git a/components/signin/public/identity_manager/android/java/src/org/chromium/components/signin/identitymanager/CoreAccountInfo.java b/components/signin/public/identity_manager/android/java/src/org/chromium/components/signin/identitymanager/CoreAccountInfo.java new file mode 100644 index 0000000..cbb28e2 --- /dev/null +++ b/components/signin/public/identity_manager/android/java/src/org/chromium/components/signin/identitymanager/CoreAccountInfo.java
@@ -0,0 +1,84 @@ +// Copyright 2019 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +package org.chromium.components.signin.identitymanager; + +import android.accounts.Account; +import android.support.annotation.NonNull; + +import org.chromium.base.annotations.CalledByNative; +import org.chromium.components.signin.AccountManagerFacade; + +/** + * Structure storing the core information about a Google account that is always known. The {@link + * CoreAccountInfo} for a given user is almost always the same but it may change in some rare cases. + * For example, the {@link android.accounts.Account} will change if a user changes email. + * + * This class has a native counterpart called CoreAccountInfo. There are several differences between + * these two classes: + * - Android class doesn't store Gaia ID as a string because {@link CoreAccountId} already contains + * it. + * - Android class additionally exposes {@link android.accounts.Account} object for interactions + * with the system. + * - Android class has the "account name" whereas the native class has "email". This is the same + * string, only the naming in different. + */ +public class CoreAccountInfo { + private final CoreAccountId mId; + private final Account mAccount; + + public CoreAccountInfo(@NonNull CoreAccountId id, @NonNull Account account) { + assert id != null; + assert account != null; + + mId = id; + mAccount = account; + } + + @CalledByNative + private CoreAccountInfo(@NonNull String id, @NonNull String name) { + assert id != null; + assert name != null; + mAccount = AccountManagerFacade.createAccountFromName(name); + mId = new CoreAccountId(id); + } + + /** + * Returns a unique identifier of the current account. + */ + public CoreAccountId getId() { + return mId; + } + + /** + * Returns a name of the current account. + */ + public String getName() { + return mAccount.name; + } + + /** + * Returns {@link android.accounts.Account} object holding a name of the current account. + */ + public Account getAccount() { + return mAccount; + } + + @Override + public String toString() { + return String.format("CoreAccountInfo{id[%s], name[%s]}", getId(), getName()); + } + + @Override + public int hashCode() { + return 31 * mId.hashCode() + mAccount.hashCode(); + } + + @Override + public boolean equals(Object obj) { + if (!(obj instanceof CoreAccountInfo)) return false; + CoreAccountInfo other = (CoreAccountInfo) obj; + return mId.equals(other.mId) && mAccount.equals(other.mAccount); + } +}
diff --git a/components/signin/public/identity_manager/android/java/src/org/chromium/components/signin/identitymanager/IdentityManager.java b/components/signin/public/identity_manager/android/java/src/org/chromium/components/signin/identitymanager/IdentityManager.java new file mode 100644 index 0000000..29ab16b --- /dev/null +++ b/components/signin/public/identity_manager/android/java/src/org/chromium/components/signin/identitymanager/IdentityManager.java
@@ -0,0 +1,106 @@ +// Copyright 2019 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +package org.chromium.components.signin.identitymanager; + +import org.chromium.base.ObserverList; +import org.chromium.base.annotations.CalledByNative; +import org.chromium.base.annotations.NativeMethods; + +/** + * IdentityManager provides access to native IdentityManager's public API to java components. + */ +public class IdentityManager { + private static final String TAG = "IdentityManager"; + + /** + * IdentityManager.Observer is notified when the available account information are updated. This + * is a subset of native's IdentityManager::Observer. + */ + public interface Observer { + /** + * Called when an account becomes the user's primary account. + * This method is not called during a reauth. + */ + void onPrimaryAccountSet(CoreAccountInfo account); + + /** + * Called when the user moves from having a primary account to no longer having a primary + * account (note that the user may still have an *unconsented* primary account after this + * event). + */ + void onPrimaryAccountCleared(CoreAccountInfo account); + } + + private long mNativeIdentityManager; + + private final ObserverList<Observer> mObservers = new ObserverList<>(); + + /** + * Called by native to create an instance of IdentityManager. + */ + @CalledByNative + static private IdentityManager create(long nativeIdentityManager) { + return new IdentityManager(nativeIdentityManager); + } + private IdentityManager(long nativeIdentityManager) { + assert nativeIdentityManager != 0; + + mNativeIdentityManager = nativeIdentityManager; + } + + /** + * Called by native upon KeyedService's shutdown + */ + @CalledByNative + private void destroy() { + mNativeIdentityManager = 0; + } + + /** + * Registers a IdentityManager.Observer + */ + public void addObserver(Observer observer) { + mObservers.addObserver(observer); + } + + /** + * Unregisters a IdentityManager.Observer + */ + public void removeObserver(Observer observer) { + mObservers.removeObserver(observer); + } + + /** + * Notifies observers that the primary account was set in C++. + */ + @CalledByNative + private void onPrimaryAccountSet(CoreAccountInfo account) { + for (Observer observer : mObservers) { + observer.onPrimaryAccountSet(account); + } + } + + /** + * Notifies observers that the primary account was cleared in C++. + */ + @CalledByNative + private void onPrimaryAccountCleared(CoreAccountInfo account) { + for (Observer observer : mObservers) { + observer.onPrimaryAccountCleared(account); + } + } + + /** + * Returns whether the user's primary account is available. + */ + boolean hasPrimaryAccount() { + return IdentityManagerJni.get().hasPrimaryAccount(mNativeIdentityManager); + } + + @NativeMethods + interface Natives { + public boolean hasPrimaryAccount(long nativeIdentityManager); + } +}
diff --git a/components/signin/public/identity_manager/identity_manager.cc b/components/signin/public/identity_manager/identity_manager.cc index 9c482d9a..79bee2b 100644 --- a/components/signin/public/identity_manager/identity_manager.cc +++ b/components/signin/public/identity_manager/identity_manager.cc
@@ -23,6 +23,8 @@ #include "services/network/public/cpp/shared_url_loader_factory.h" #if defined(OS_ANDROID) +#include "base/android/jni_string.h" +#include "components/signin/internal/identity_manager/android/jni_headers/IdentityManager_jni.h" #include "components/signin/internal/identity_manager/oauth2_token_service_delegate_android.h" #elif !defined(OS_IOS) #include "components/signin/internal/identity_manager/mutable_profile_oauth2_token_service_delegate.h" @@ -121,6 +123,11 @@ DCHECK(!account.account_id.empty()); SetPrimaryAccountInternal(std::move(account)); } + +#if defined(OS_ANDROID) + java_identity_manager_ = Java_IdentityManager_create( + base::android::AttachCurrentThread(), reinterpret_cast<intptr_t>(this)); +#endif } IdentityManager::~IdentityManager() { @@ -131,6 +138,12 @@ token_service_->RemoveObserver(this); token_service_->RemoveAccessTokenDiagnosticsObserver(this); + +#if defined(OS_ANDROID) + if (java_identity_manager_) + Java_IdentityManager_destroy(base::android::AttachCurrentThread(), + java_identity_manager_); +#endif } void IdentityManager::AddObserver(Observer* observer) { @@ -460,11 +473,20 @@ return delegate->GetJavaObject(); } +base::android::ScopedJavaLocalRef<jobject> IdentityManager::GetJavaObject() { + DCHECK(java_identity_manager_); + return base::android::ScopedJavaLocalRef<jobject>(java_identity_manager_); +} + void IdentityManager::ForceRefreshOfExtendedAccountInfo( const CoreAccountId& account_id) { DCHECK(HasAccountWithRefreshToken(account_id)); account_fetcher_service_->ForceRefreshOfAccountInfo(account_id); } + +bool IdentityManager::HasPrimaryAccount(JNIEnv* env) const { + return HasPrimaryAccount(); +} #endif PrimaryAccountManager* IdentityManager::GetPrimaryAccountManager() { @@ -566,6 +588,12 @@ for (auto& observer : observer_list_) { observer.OnPrimaryAccountSet(account_info); } +#if defined(OS_ANDROID) + if (java_identity_manager_) + Java_IdentityManager_onPrimaryAccountSet( + base::android::AttachCurrentThread(), java_identity_manager_, + ConvertToJavaCoreAccountInfo(account_info)); +#endif } void IdentityManager::GoogleSignedOut(const AccountInfo& account_info) { @@ -573,6 +601,12 @@ for (auto& observer : observer_list_) { observer.OnPrimaryAccountCleared(account_info); } +#if defined(OS_ANDROID) + if (java_identity_manager_) + Java_IdentityManager_onPrimaryAccountCleared( + base::android::AttachCurrentThread(), java_identity_manager_, + ConvertToJavaCoreAccountInfo(account_info)); +#endif } void IdentityManager::AuthenticatedAccountSet(const AccountInfo& account_info) { DCHECK(primary_account_manager_->IsAuthenticated());
diff --git a/components/signin/public/identity_manager/identity_manager.h b/components/signin/public/identity_manager/identity_manager.h index 9264caa..010e8318e 100644 --- a/components/signin/public/identity_manager/identity_manager.h +++ b/components/signin/public/identity_manager/identity_manager.h
@@ -449,7 +449,8 @@ // API calls ProfileOAuth2TokenServiceDelegate::ReloadAccountsFromSystem and // it triggers platform specific implementation for Android. NOTE: In normal // usage, this method SHOULD NOT be called. - // TODO(https://crbug.com/930094): Eliminate the need to expose this. + // TODO(https://crbug.com/930094): Expose this through + // DeviceAccountsSynchronizer void LegacyReloadAccountsFromSystem(); // Returns a pointer to the AccountTrackerService Java instance associated @@ -466,11 +467,18 @@ base::android::ScopedJavaLocalRef<jobject> LegacyGetOAuth2TokenServiceJavaObject(); + // Get the reference on the java IdentityManager, InitializeJavaObject must + // be called before hand. + base::android::ScopedJavaLocalRef<jobject> GetJavaObject(); + // This method has the contractual assumption that the account is a known // account and has as its semantics that it fetches the account info for the // account, triggering an OnExtendedAccountInfoUpdated() callback if the info // was successfully fetched. void ForceRefreshOfExtendedAccountInfo(const CoreAccountId& account_id); + + // Overloads for calls from java: + bool HasPrimaryAccount(JNIEnv* env) const; #endif private: @@ -690,6 +698,11 @@ base::Optional<CoreAccountInfo> primary_account_; base::Optional<CoreAccountInfo> unconsented_primary_account_; +#if defined(OS_ANDROID) + // Java-side IdentityManager object. + base::android::ScopedJavaGlobalRef<jobject> java_identity_manager_; +#endif + DISALLOW_COPY_AND_ASSIGN(IdentityManager); };
diff --git a/content/browser/back_forward_cache_browsertest.cc b/content/browser/back_forward_cache_browsertest.cc index a97d2c4..dbfa823 100644 --- a/content/browser/back_forward_cache_browsertest.cc +++ b/content/browser/back_forward_cache_browsertest.cc
@@ -75,6 +75,8 @@ ASSERT_TRUE(embedded_test_server()->Start()); const GURL url_a(embedded_test_server()->GetURL("a.com", "/title1.html")); const GURL url_b(embedded_test_server()->GetURL("b.com", "/title1.html")); + const url::Origin origin_a = url::Origin::Create(url_a); + const url::Origin origin_b = url::Origin::Create(url_b); // 1) Navigate to A. EXPECT_TRUE(NavigateToURL(shell(), url_a)); @@ -88,6 +90,8 @@ EXPECT_FALSE(delete_rfh_a.deleted()); EXPECT_TRUE(rfh_a->is_in_back_forward_cache()); EXPECT_EQ(rfh_a->GetVisibilityState(), PageVisibilityState::kHidden); + EXPECT_EQ(origin_a, rfh_a->GetLastCommittedOrigin()); + EXPECT_EQ(origin_b, rfh_b->GetLastCommittedOrigin()); EXPECT_FALSE(rfh_b->is_in_back_forward_cache()); EXPECT_EQ(rfh_b->GetVisibilityState(), PageVisibilityState::kVisible); @@ -96,6 +100,8 @@ EXPECT_TRUE(WaitForLoadStop(shell()->web_contents())); EXPECT_FALSE(delete_rfh_a.deleted()); EXPECT_FALSE(delete_rfh_b.deleted()); + EXPECT_EQ(origin_a, rfh_a->GetLastCommittedOrigin()); + EXPECT_EQ(origin_b, rfh_b->GetLastCommittedOrigin()); EXPECT_EQ(rfh_a, current_frame_host()); EXPECT_FALSE(rfh_a->is_in_back_forward_cache()); EXPECT_EQ(rfh_a->GetVisibilityState(), PageVisibilityState::kVisible);
diff --git a/content/browser/background_sync/background_sync_manager.cc b/content/browser/background_sync/background_sync_manager.cc index 6abf32e..3fd21a50 100644 --- a/content/browser/background_sync/background_sync_manager.cc +++ b/content/browser/background_sync/background_sync_manager.cc
@@ -560,6 +560,21 @@ std::move(callback)); } +void BackgroundSyncManager::EmulateDispatchPeriodicSyncEvent( + const std::string& tag, + scoped_refptr<ServiceWorkerVersion> active_version, + ServiceWorkerVersion::StatusCallback callback) { + DCHECK_CURRENTLY_ON(BrowserThread::IO); + blink::ServiceWorkerStatusCode code = CanEmulateSyncEvent(active_version); + if (code != blink::ServiceWorkerStatusCode::kOk) { + std::move(callback).Run(code); + return; + } + + DispatchPeriodicSyncEvent(tag, std::move(active_version), + std::move(callback)); +} + void BackgroundSyncManager::EmulateServiceWorkerOffline( int64_t service_worker_id, bool is_offline) {
diff --git a/content/browser/background_sync/background_sync_manager.h b/content/browser/background_sync/background_sync_manager.h index 13272fd..6dba06c0 100644 --- a/content/browser/background_sync/background_sync_manager.h +++ b/content/browser/background_sync/background_sync_manager.h
@@ -133,6 +133,10 @@ scoped_refptr<ServiceWorkerVersion> active_version, bool last_chance, ServiceWorkerVersion::StatusCallback callback); + void EmulateDispatchPeriodicSyncEvent( + const std::string& tag, + scoped_refptr<ServiceWorkerVersion> active_version, + ServiceWorkerVersion::StatusCallback callback); // Called from DevTools to toggle service worker "offline" status void EmulateServiceWorkerOffline(int64_t service_worker_id, bool is_offline);
diff --git a/content/browser/background_sync/background_sync_service_impl_test_harness.cc b/content/browser/background_sync/background_sync_service_impl_test_harness.cc index 126aad88..3c534f3 100644 --- a/content/browser/background_sync/background_sync_service_impl_test_harness.cc +++ b/content/browser/background_sync/background_sync_service_impl_test_harness.cc
@@ -144,6 +144,7 @@ storage_partition_impl_ = StoragePartitionImpl::Create( embedded_worker_helper_->browser_context(), /* in_memory= */ true, base::FilePath(), /* partition_domain= */ ""); + storage_partition_impl_->Initialize(); embedded_worker_helper_->context_wrapper()->set_storage_partition( storage_partition_impl_.get()); }
diff --git a/content/browser/cookie_store/cookie_store_manager_unittest.cc b/content/browser/cookie_store/cookie_store_manager_unittest.cc index 7bde04f..e0b9511 100644 --- a/content/browser/cookie_store/cookie_store_manager_unittest.cc +++ b/content/browser/cookie_store/cookie_store_manager_unittest.cc
@@ -262,9 +262,11 @@ base::BindOnce([](bool success) { CHECK(success) << "Initialize failed"; })); - storage_partition_impl_ = base::WrapUnique( - new StoragePartitionImpl(worker_test_helper_->browser_context(), - user_data_directory_.GetPath(), nullptr)); + storage_partition_impl_ = StoragePartitionImpl::Create( + worker_test_helper_->browser_context(), true /* in_memory */, + base::FilePath() /* relative_partition_path */, + std::string() /* partition_domain */); + storage_partition_impl_->Initialize(); ::network::mojom::NetworkContext* network_context = storage_partition_impl_->GetNetworkContext(); cookie_store_context_->ListenToCookieChanges(
diff --git a/content/browser/devtools/protocol/service_worker_handler.cc b/content/browser/devtools/protocol/service_worker_handler.cc index 5f4285b..323bcbae 100644 --- a/content/browser/devtools/protocol/service_worker_handler.cc +++ b/content/browser/devtools/protocol/service_worker_handler.cc
@@ -127,11 +127,26 @@ registration->active_version()); // Keep the registration while dispatching the sync event. background_sync_manager->EmulateDispatchSyncEvent( - tag, std::move(version), last_chance, - base::BindOnce(base::DoNothing::Once< - scoped_refptr<content::ServiceWorkerRegistration>, - blink::ServiceWorkerStatusCode>(), - std::move(registration))); + tag, std::move(version), last_chance, base::DoNothing()); +} + +void DidFindRegistrationForDispatchPeriodicSyncEventOnIO( + scoped_refptr<BackgroundSyncContextImpl> sync_context, + const std::string& tag, + blink::ServiceWorkerStatusCode status, + scoped_refptr<content::ServiceWorkerRegistration> registration) { + if (status != blink::ServiceWorkerStatusCode::kOk || + !registration->active_version()) { + return; + } + + BackgroundSyncManager* background_sync_manager = + sync_context->background_sync_manager(); + scoped_refptr<content::ServiceWorkerVersion> version( + registration->active_version()); + // Keep the registration while dispatching the sync event. + background_sync_manager->EmulateDispatchPeriodicSyncEvent( + tag, std::move(version), base::DoNothing()); } void DispatchSyncEventOnIO( @@ -147,6 +162,18 @@ tag, last_chance)); } +void DispatchPeriodicSyncEventOnIO( + scoped_refptr<ServiceWorkerContextWrapper> context, + scoped_refptr<BackgroundSyncContextImpl> sync_context, + const GURL& origin, + int64_t registration_id, + const std::string& tag) { + context->FindReadyRegistrationForId( + registration_id, origin, + base::BindOnce(&DidFindRegistrationForDispatchPeriodicSyncEventOnIO, + sync_context, tag)); +} + } // namespace ServiceWorkerHandler::ServiceWorkerHandler() @@ -346,6 +373,29 @@ return Response::OK(); } +Response ServiceWorkerHandler::DispatchPeriodicSyncEvent( + const std::string& origin, + const std::string& registration_id, + const std::string& tag) { + if (!enabled_) + return CreateDomainNotEnabledErrorResponse(); + if (!storage_partition_) + return CreateContextErrorResponse(); + int64_t id = 0; + if (!base::StringToInt64(registration_id, &id)) + return CreateInvalidVersionIdErrorResponse(); + + BackgroundSyncContextImpl* sync_context = + storage_partition_->GetBackgroundSyncContext(); + + base::PostTaskWithTraits( + FROM_HERE, {BrowserThread::IO}, + base::BindOnce(&DispatchPeriodicSyncEventOnIO, context_, + base::WrapRefCounted(sync_context), GURL(origin), id, + tag)); + return Response::OK(); +} + void ServiceWorkerHandler::OpenNewDevToolsWindow(int process_id, int devtools_agent_route_id) { scoped_refptr<DevToolsAgentHostImpl> agent_host(
diff --git a/content/browser/devtools/protocol/service_worker_handler.h b/content/browser/devtools/protocol/service_worker_handler.h index ed154407..848540dc 100644 --- a/content/browser/devtools/protocol/service_worker_handler.h +++ b/content/browser/devtools/protocol/service_worker_handler.h
@@ -56,7 +56,9 @@ const std::string& registration_id, const std::string& tag, bool last_chance) override; - // TODO(crbug.com/961238): Add DispatchPeriodicSyncEvent(). + Response DispatchPeriodicSyncEvent(const std::string& origin, + const std::string& registration_id, + const std::string& tag) override; private: void OnWorkerRegistrationUpdated(
diff --git a/content/browser/frame_host/render_frame_host_manager_browsertest.cc b/content/browser/frame_host/render_frame_host_manager_browsertest.cc index 241c916..fe65218d 100644 --- a/content/browser/frame_host/render_frame_host_manager_browsertest.cc +++ b/content/browser/frame_host/render_frame_host_manager_browsertest.cc
@@ -193,6 +193,13 @@ host_resolver()->AddRule("*", "127.0.0.1"); } + void DisableBackForwardCache() const { + return static_cast<WebContentsImpl*>(shell()->web_contents()) + ->GetController() + .back_forward_cache() + .DisableForTesting(); + } + void StartServer() { ASSERT_TRUE(embedded_test_server()->Start()); @@ -3755,6 +3762,11 @@ // See https://crbug.com/590035. IN_PROC_BROWSER_TEST_F(RenderFrameHostManagerTest, LastCommittedOrigin) { StartEmbeddedServer(); + + // Disable the back-forward cache so that documents are always deleted when + // navigating. + DisableBackForwardCache(); + GURL url_a(embedded_test_server()->GetURL("a.com", "/title1.html")); EXPECT_TRUE(NavigateToURL(shell(), url_a)); @@ -6453,14 +6465,14 @@ // Only B4 is deleted. B2 and B3 are still there in a "crashed" state. delete_b4.WaitUntilDeleted(); - // A1 and C5 RenderFrameImpl are gone. + // B2, B3, B4 RenderFrame are gone. EXPECT_FALSE(delete_a1.deleted()); EXPECT_TRUE(delete_b2.deleted()); EXPECT_TRUE(delete_b3.deleted()); EXPECT_TRUE(delete_b4.deleted()); EXPECT_FALSE(delete_c5.deleted()); - // B2 and B3 are still there, but not B4. + // B2 and B3 RenderFrameHost are still there, but B4 is definitely gone. ASSERT_EQ(3u, a1->child_count()); EXPECT_EQ(b2, a1->child_at(0)->current_frame_host()); EXPECT_EQ(b3, a1->child_at(1)->current_frame_host());
diff --git a/content/browser/media/hardware_key_media_controller.cc b/content/browser/media/hardware_key_media_controller.cc index fff4816..145e9dab 100644 --- a/content/browser/media/hardware_key_media_controller.cc +++ b/content/browser/media/hardware_key_media_controller.cc
@@ -30,15 +30,16 @@ // Connect to the MediaControllerManager and create a MediaController that // controls the active session. - media_session::mojom::MediaControllerManagerPtr controller_manager_ptr; - connector->BindInterface(media_session::mojom::kServiceName, - mojo::MakeRequest(&controller_manager_ptr)); - controller_manager_ptr->CreateActiveMediaController( - mojo::MakeRequest(&media_controller_ptr_)); + mojo::Remote<media_session::mojom::MediaControllerManager> + controller_manager_remote; + connector->Connect(media_session::mojom::kServiceName, + controller_manager_remote.BindNewPipeAndPassReceiver()); + controller_manager_remote->CreateActiveMediaController( + media_controller_remote_.BindNewPipeAndPassReceiver()); // Observe the active media controller for changes to playback state and // supported actions. - media_controller_ptr_->AddObserver( + media_controller_remote_->AddObserver( media_controller_observer_receiver_.BindNewPipeAndPassRemote()); } @@ -93,7 +94,7 @@ } void HardwareKeyMediaController::FlushForTesting() { - media_controller_ptr_.FlushForTesting(); + media_controller_remote_.FlushForTesting(); } void HardwareKeyMediaController::OnMediaKeysAccelerator( @@ -121,26 +122,26 @@ DCHECK(SupportsAction(action)); switch (action) { case MediaSessionAction::kPreviousTrack: - media_controller_ptr_->PreviousTrack(); + media_controller_remote_->PreviousTrack(); ui::RecordMediaHardwareKeyAction( ui::MediaHardwareKeyAction::kPreviousTrack); return; case MediaSessionAction::kPlay: - media_controller_ptr_->Resume(); + media_controller_remote_->Resume(); ui::RecordMediaHardwareKeyAction(ui::MediaHardwareKeyAction::kPlay); return; case MediaSessionAction::kPause: - media_controller_ptr_->Suspend(); + media_controller_remote_->Suspend(); ui::RecordMediaHardwareKeyAction( ui::MediaHardwareKeyAction::kPause); return; case MediaSessionAction::kNextTrack: - media_controller_ptr_->NextTrack(); + media_controller_remote_->NextTrack(); ui::RecordMediaHardwareKeyAction( ui::MediaHardwareKeyAction::kNextTrack); return; case MediaSessionAction::kStop: - media_controller_ptr_->Stop(); + media_controller_remote_->Stop(); ui::RecordMediaHardwareKeyAction(ui::MediaHardwareKeyAction::kStop); return; case MediaSessionAction::kSeekBackward:
diff --git a/content/browser/media/hardware_key_media_controller.h b/content/browser/media/hardware_key_media_controller.h index 0aafea6..a896722 100644 --- a/content/browser/media/hardware_key_media_controller.h +++ b/content/browser/media/hardware_key_media_controller.h
@@ -12,6 +12,7 @@ #include "base/optional.h" #include "content/common/content_export.h" #include "mojo/public/cpp/bindings/receiver.h" +#include "mojo/public/cpp/bindings/remote.h" #include "services/media_session/public/mojom/media_controller.mojom.h" #include "ui/base/accelerators/media_keys_listener.h" #include "ui/events/keycodes/keyboard_codes.h" @@ -48,8 +49,8 @@ void FlushForTesting(); void SetMediaControllerForTesting( - media_session::mojom::MediaControllerPtr controller) { - media_controller_ptr_ = std::move(controller); + mojo::Remote<media_session::mojom::MediaController> controller) { + media_controller_remote_ = std::move(controller); } private: @@ -66,7 +67,7 @@ void PerformAction(media_session::mojom::MediaSessionAction action); // Used to control the active session. - media_session::mojom::MediaControllerPtr media_controller_ptr_; + mojo::Remote<media_session::mojom::MediaController> media_controller_remote_; // Used to check whether a play/pause key should play or pause (based on // current playback state).
diff --git a/content/browser/media/media_keys_listener_manager_impl_browsertest.cc b/content/browser/media/media_keys_listener_manager_impl_browsertest.cc index 2469df3..84dbb4a 100644 --- a/content/browser/media/media_keys_listener_manager_impl_browsertest.cc +++ b/content/browser/media/media_keys_listener_manager_impl_browsertest.cc
@@ -116,7 +116,7 @@ media_controller_ = std::make_unique<TestMediaController>(); media_keys_listener_manager_->hardware_key_media_controller_for_testing() ->SetMediaControllerForTesting( - media_controller_->CreateMediaControllerPtr()); + media_controller_->CreateMediaControllerRemote()); ContentBrowserTest::SetUpOnMainThread(); }
diff --git a/content/browser/media/session/media_session_impl_unittest.cc b/content/browser/media/session/media_session_impl_unittest.cc index b5309fe..e49d211 100644 --- a/content/browser/media/session/media_session_impl_unittest.cc +++ b/content/browser/media/session/media_session_impl_unittest.cc
@@ -96,10 +96,12 @@ mock_media_session_service_.reset( new testing::NiceMock<MockMediaSessionServiceImpl>(main_rfh())); - // Connect to the Media Session service and bind |audio_focus_ptr_| to it. + // Connect to the Media Session service and bind |audio_focus_remote_| to + // it. service_manager_context_ = std::make_unique<TestServiceManagerContext>(); - GetSystemConnector()->BindInterface(media_session::mojom::kServiceName, - mojo::MakeRequest(&audio_focus_ptr_)); + GetSystemConnector()->Connect( + media_session::mojom::kServiceName, + audio_focus_remote_.BindNewPipeAndPassReceiver()); } void TearDown() override { @@ -142,8 +144,8 @@ std::unique_ptr<TestAudioFocusObserver> observer = std::make_unique<TestAudioFocusObserver>(); - audio_focus_ptr_->AddObserver(observer->BindNewPipeAndPassRemote()); - audio_focus_ptr_.FlushForTesting(); + audio_focus_remote_->AddObserver(observer->BindNewPipeAndPassRemote()); + audio_focus_remote_.FlushForTesting(); return observer; } @@ -181,7 +183,7 @@ std::unique_ptr<MockMediaSessionServiceImpl> mock_media_session_service_; - media_session::mojom::AudioFocusManagerPtr audio_focus_ptr_; + mojo::Remote<media_session::mojom::AudioFocusManager> audio_focus_remote_; std::unique_ptr<TestServiceManagerContext> service_manager_context_;
diff --git a/content/browser/payments/payment_app_installer.h b/content/browser/payments/payment_app_installer.h index 67e9e5b..6522799 100644 --- a/content/browser/payments/payment_app_installer.h +++ b/content/browser/payments/payment_app_installer.h
@@ -5,6 +5,7 @@ #ifndef CONTENT_BROWSER_PAYMENTS_PAYMENT_APP_INSTALLER_H_ #define CONTENT_BROWSER_PAYMENTS_PAYMENT_APP_INSTALLER_H_ +#include <stdint.h> #include <vector> #include "base/callback.h" @@ -23,7 +24,7 @@ public: using InstallPaymentAppCallback = base::OnceCallback<void(BrowserContext* browser_context, - long registration_id)>; + int64_t registration_id)>; // Installs the payment app. // |app_name| is the name of the payment app. @@ -32,7 +33,7 @@ // |scope| is the registration scope. // |use_cache| indicates whether to use cache. // |enabled_methods| are the enabled methods of the app. - // |callback| to send back registeration result. + // |callback| to send back registration result. static void Install(WebContents* web_contents, const std::string& app_name, const std::string& app_icon,
diff --git a/content/browser/payments/payment_app_provider_impl.cc b/content/browser/payments/payment_app_provider_impl.cc index e0d088e3..122ba32 100644 --- a/content/browser/payments/payment_app_provider_impl.cc +++ b/content/browser/payments/payment_app_provider_impl.cc
@@ -404,14 +404,17 @@ registration_id, std::move(callback))); } -void OnInstallPaymentApp(const url::Origin& sw_origin, - payments::mojom::PaymentRequestEventDataPtr event_data, - PaymentAppProvider::InvokePaymentAppCallback callback, - BrowserContext* browser_context, - long registration_id) { +void OnInstallPaymentApp( + const url::Origin& sw_origin, + payments::mojom::PaymentRequestEventDataPtr event_data, + PaymentAppProvider::RegistrationIdCallback registration_id_callback, + PaymentAppProvider::InvokePaymentAppCallback callback, + BrowserContext* browser_context, + int64_t registration_id) { DCHECK_CURRENTLY_ON(BrowserThread::UI); if (registration_id >= 0 && browser_context != nullptr) { + std::move(registration_id_callback).Run(registration_id); PaymentAppProvider::GetInstance()->InvokePaymentApp( browser_context, registration_id, sw_origin, std::move(event_data), std::move(callback)); @@ -635,6 +638,7 @@ const std::string& sw_scope, bool sw_use_cache, const std::string& method, + RegistrationIdCallback registration_id_callback, InvokePaymentAppCallback callback) { DCHECK_CURRENTLY_ON(BrowserThread::UI); @@ -667,7 +671,8 @@ web_contents, app_name, string_encoded_icon, url, scope, sw_use_cache, method, base::BindOnce(&OnInstallPaymentApp, url::Origin::Create(scope), - std::move(event_data), std::move(callback))); + std::move(event_data), std::move(registration_id_callback), + std::move(callback))); } void PaymentAppProviderImpl::CanMakePayment(
diff --git a/content/browser/payments/payment_app_provider_impl.h b/content/browser/payments/payment_app_provider_impl.h index b9ce1222..b73a924 100644 --- a/content/browser/payments/payment_app_provider_impl.h +++ b/content/browser/payments/payment_app_provider_impl.h
@@ -35,6 +35,7 @@ const std::string& sw_scope, bool sw_use_cache, const std::string& method, + RegistrationIdCallback registration_id_callback, InvokePaymentAppCallback callback) override; void CanMakePayment(BrowserContext* browser_context, int64_t registration_id,
diff --git a/content/browser/renderer_host/input/web_input_event_builders_mac.mm b/content/browser/renderer_host/input/web_input_event_builders_mac.mm index 13f8e94..af5cacd7 100644 --- a/content/browser/renderer_host/input/web_input_event_builders_mac.mm +++ b/content/browser/renderer_host/input/web_input_event_builders_mac.mm
@@ -108,6 +108,10 @@ modifiers |= blink::WebInputEvent::kRightButtonDown; if (pressed_buttons & (1 << 2)) modifiers |= blink::WebInputEvent::kMiddleButtonDown; + if (pressed_buttons & (1 << 3)) + modifiers |= blink::WebInputEvent::kBackButtonDown; + if (pressed_buttons & (1 << 4)) + modifiers |= blink::WebInputEvent::kForwardButtonDown; return modifiers; } @@ -206,6 +210,23 @@ return blink::WebMouseEvent::Button::kRight; if (pressed_buttons & (1 << 2)) return blink::WebMouseEvent::Button::kMiddle; + if (pressed_buttons & (1 << 3)) + return blink::WebMouseEvent::Button::kBack; + if (pressed_buttons & (1 << 4)) + return blink::WebMouseEvent::Button::kForward; + return blink::WebMouseEvent::Button::kNoButton; +} +blink::WebMouseEvent::Button ButtonFromButtonNumber(NSEvent* event) { + NSUInteger button_number = [event buttonNumber]; + + if (button_number == 1) + return blink::WebMouseEvent::Button::kRight; + if (button_number == 2) + return blink::WebMouseEvent::Button::kMiddle; + if (button_number == 3) + return blink::WebMouseEvent::Button::kBack; + if (button_number == 4) + return blink::WebMouseEvent::Button::kForward; return blink::WebMouseEvent::Button::kNoButton; } @@ -285,7 +306,7 @@ case NSOtherMouseDown: event_type = blink::WebInputEvent::kMouseDown; click_count = [event clickCount]; - button = blink::WebMouseEvent::Button::kMiddle; + button = ButtonFromButtonNumber(event); break; case NSRightMouseDown: event_type = blink::WebInputEvent::kMouseDown; @@ -300,7 +321,7 @@ case NSOtherMouseUp: event_type = blink::WebInputEvent::kMouseUp; click_count = [event clickCount]; - button = blink::WebMouseEvent::Button::kMiddle; + button = ButtonFromButtonNumber(event); break; case NSRightMouseUp: event_type = blink::WebInputEvent::kMouseUp;
diff --git a/content/browser/renderer_host/input/web_input_event_builders_mac_unittest.mm b/content/browser/renderer_host/input/web_input_event_builders_mac_unittest.mm index 61d9010..6b0cf624 100644 --- a/content/browser/renderer_host/input/web_input_event_builders_mac_unittest.mm +++ b/content/browser/renderer_host/input/web_input_event_builders_mac_unittest.mm
@@ -66,7 +66,6 @@ keyCode:key_code]; } -#if !defined(MAC_OS_X_VERSION_10_12) NSEvent* BuildFakeMouseEvent(CGEventType mouse_type, CGPoint location, CGMouseButton button, @@ -75,7 +74,8 @@ float pressure = 0.0, float tilt_x = 0.0, float tilt_y = 0.0, - float tangential_pressure = 0.0) { + float tangential_pressure = 0.0, + NSUInteger button_number = 0) { CGEventRef cg_event = CGEventCreateMouseEvent(NULL, mouse_type, location, button); CGEventSetIntegerValueField(cg_event, kCGMouseEventSubtype, subtype); @@ -85,11 +85,12 @@ CGEventSetDoubleValueField(cg_event, kCGTabletEventTiltY, tilt_y); CGEventSetDoubleValueField(cg_event, kCGTabletEventTangentialPressure, tangential_pressure); + CGEventSetIntegerValueField(cg_event, kCGMouseEventButtonNumber, + button_number); NSEvent* event = [NSEvent eventWithCGEvent:cg_event]; CFRelease(cg_event); return event; } -#endif // MAC_OS_X_VERSION_10_12 } // namespace @@ -673,7 +674,6 @@ [window close]; } -#if !defined(MAC_OS_X_VERSION_10_12) // Test if the value of twist and rotation_angle are set correctly when the // NSEvent's rotation is less than 90. TEST(WebInputEventBuilderMacTest, TouchEventsWithPointerTypePenRotationLess90) { @@ -781,4 +781,47 @@ EXPECT_EQ(60, touch_event.touches[0].twist); EXPECT_FLOAT_EQ(60.0, touch_event.touches[0].rotation_angle); } -#endif // MAC_OS_X_VERSION_10_12 + +// Test if the mouse back button values of a WebMouseEvent are set correctly. +TEST(WebInputEventBuilderMacTest, BuildWebMouseEventsWithBackButton) { + NSEvent* mac_event = BuildFakeMouseEvent( + kCGEventOtherMouseDown, {6, 9}, kCGMouseButtonLeft, + kCGEventMouseSubtypeDefault, /* rotation */ 0.0, + /* pressure */ 0.0, /* tilt_x */ 0.0, /* tilt_y */ 0.0, + /* tangential_pressure */ 0.0, /* button_number */ 3); + // Create a dummy window, but don't show it. It will be released when closed. + NSWindow* window = + [[NSWindow alloc] initWithContentRect:NSMakeRect(0, 0, 100, 100) + styleMask:NSBorderlessWindowMask + backing:NSBackingStoreBuffered + defer:NO]; + blink::WebMouseEvent mouse_event = + content::WebMouseEventBuilder::Build(mac_event, [window contentView]); + EXPECT_EQ(blink::WebInputEvent::kMouseDown, mouse_event.GetType()); + EXPECT_EQ(blink::WebFloatPoint(6, 9), mouse_event.PositionInScreen()); + EXPECT_EQ(blink::WebPointerProperties::PointerType::kMouse, + mouse_event.pointer_type); + EXPECT_EQ(blink::WebMouseEvent::Button::kBack, mouse_event.button); +} + +// Test if the mouse forward button values of a WebMouseEvent are set correctly. +TEST(WebInputEventBuilderMacTest, BuildWebMouseEventsWithForwardButton) { + NSEvent* mac_event = BuildFakeMouseEvent( + kCGEventOtherMouseDown, {6, 9}, kCGMouseButtonLeft, + kCGEventMouseSubtypeDefault, /* rotation */ 0.0, + /* pressure */ 0.0, /* tilt_x */ 0.0, /* tilt_y */ 0.0, + /* tangential_pressure */ 0.0, /* button_number */ 4); + // Create a dummy window, but don't show it. It will be released when closed. + NSWindow* window = + [[NSWindow alloc] initWithContentRect:NSMakeRect(0, 0, 100, 100) + styleMask:NSBorderlessWindowMask + backing:NSBackingStoreBuffered + defer:NO]; + blink::WebMouseEvent mouse_event = + content::WebMouseEventBuilder::Build(mac_event, [window contentView]); + EXPECT_EQ(blink::WebInputEvent::kMouseDown, mouse_event.GetType()); + EXPECT_EQ(blink::WebFloatPoint(6, 9), mouse_event.PositionInScreen()); + EXPECT_EQ(blink::WebPointerProperties::PointerType::kMouse, + mouse_event.pointer_type); + EXPECT_EQ(blink::WebMouseEvent::Button::kForward, mouse_event.button); +}
diff --git a/content/browser/service_worker/service_worker_registration_unittest.cc b/content/browser/service_worker/service_worker_registration_unittest.cc index d433ba47..e3d58447 100644 --- a/content/browser/service_worker/service_worker_registration_unittest.cc +++ b/content/browser/service_worker/service_worker_registration_unittest.cc
@@ -183,6 +183,7 @@ storage_partition_impl_ = StoragePartitionImpl::Create( helper_->browser_context(), /* in_memory= */ true, base::FilePath(), /* partition_domain= */ ""); + storage_partition_impl_->Initialize(); helper_->context_wrapper()->set_storage_partition( storage_partition_impl_.get());
diff --git a/content/browser/service_worker/service_worker_version.cc b/content/browser/service_worker/service_worker_version.cc index b75d5905..7f6a2d5 100644 --- a/content/browser/service_worker/service_worker_version.cc +++ b/content/browser/service_worker/service_worker_version.cc
@@ -806,8 +806,6 @@ // TODO(bashi): Remove this workaround when byte-for-byte update check is // shipped. bool stop_immediately = - base::FeatureList::IsEnabled( - blink::features::kOffMainThreadServiceWorkerScriptFetch) && start_worker_status_ == blink::ServiceWorkerStatusCode::kErrorExists; if (stop_immediately || !embedded_worker()->devtools_attached()) { embedded_worker_->Stop();
diff --git a/content/browser/storage_partition_impl.cc b/content/browser/storage_partition_impl.cc index 2c57964..443809d 100644 --- a/content/browser/storage_partition_impl.cc +++ b/content/browser/storage_partition_impl.cc
@@ -721,11 +721,17 @@ StoragePartitionImpl::StoragePartitionImpl( BrowserContext* browser_context, const base::FilePath& partition_path, + bool is_in_memory, + const base::FilePath& relative_partition_path, + const std::string& partition_domain, storage::SpecialStoragePolicy* special_storage_policy) - : partition_path_(partition_path), + : browser_context_(browser_context), + partition_path_(partition_path), + is_in_memory_(is_in_memory), + relative_partition_path_(relative_partition_path), + partition_domain_(partition_domain), special_storage_policy_(special_storage_policy), network_context_client_binding_(this), - browser_context_(browser_context), deletion_helpers_running_(0) {} StoragePartitionImpl::~StoragePartitionImpl() { @@ -798,156 +804,155 @@ base::FilePath partition_path = context->GetPath().Append(relative_partition_path); - std::unique_ptr<StoragePartitionImpl> partition = - base::WrapUnique(new StoragePartitionImpl( - context, partition_path, context->GetSpecialStoragePolicy())); + return base::WrapUnique(new StoragePartitionImpl( + context, partition_path, in_memory, relative_partition_path, + partition_domain, context->GetSpecialStoragePolicy())); +} - partition->is_in_memory_ = in_memory; - partition->relative_partition_path_ = relative_partition_path; +void StoragePartitionImpl::Initialize() { + // Ensure that these methods are called on the UI thread, except for + // unittests where a UI thread might not have been created. + DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI) || + !BrowserThread::IsThreadInitialized(BrowserThread::UI)); + DCHECK(!initialized_); + initialized_ = true; // All of the clients have to be created and registered with the // QuotaManager prior to the QuotaManger being used. We do them // all together here prior to handing out a reference to anything // that utilizes the QuotaManager. - partition->quota_manager_ = new storage::QuotaManager( - in_memory, partition_path, + quota_manager_ = new storage::QuotaManager( + is_in_memory_, partition_path_, base::CreateSingleThreadTaskRunner({BrowserThread::IO}).get(), - context->GetSpecialStoragePolicy(), + browser_context_->GetSpecialStoragePolicy(), base::BindRepeating(&StoragePartitionImpl::GetQuotaSettings, - partition->weak_factory_.GetWeakPtr())); + weak_factory_.GetWeakPtr())); scoped_refptr<storage::QuotaManagerProxy> quota_manager_proxy = - partition->quota_manager_->proxy(); + quota_manager_->proxy(); // Each consumer is responsible for registering its QuotaClient during // its construction. - partition->filesystem_context_ = CreateFileSystemContext( - context, partition_path, in_memory, quota_manager_proxy.get()); + filesystem_context_ = + CreateFileSystemContext(browser_context_, partition_path_, is_in_memory_, + quota_manager_proxy.get()); - partition->database_tracker_ = base::MakeRefCounted<storage::DatabaseTracker>( - partition_path, in_memory, context->GetSpecialStoragePolicy(), - quota_manager_proxy.get()); + database_tracker_ = base::MakeRefCounted<storage::DatabaseTracker>( + partition_path_, is_in_memory_, + browser_context_->GetSpecialStoragePolicy(), quota_manager_proxy.get()); - partition->dom_storage_context_ = DOMStorageContextWrapper::Create( - BrowserContext::GetConnectorFor(context), - in_memory ? base::FilePath() : context->GetPath(), - relative_partition_path, context->GetSpecialStoragePolicy()); + dom_storage_context_ = DOMStorageContextWrapper::Create( + BrowserContext::GetConnectorFor(browser_context_), + is_in_memory_ ? base::FilePath() : browser_context_->GetPath(), + relative_partition_path_, browser_context_->GetSpecialStoragePolicy()); - partition->idle_manager_ = std::make_unique<IdleManager>(); - partition->lock_manager_ = new LockManager(); + idle_manager_ = std::make_unique<IdleManager>(); + lock_manager_ = new LockManager(); - base::FilePath path = in_memory ? base::FilePath() : partition_path; - partition->indexed_db_context_ = new IndexedDBContextImpl( - path, context->GetSpecialStoragePolicy(), quota_manager_proxy, + base::FilePath path = is_in_memory_ ? base::FilePath() : partition_path_; + indexed_db_context_ = new IndexedDBContextImpl( + path, browser_context_->GetSpecialStoragePolicy(), quota_manager_proxy, base::DefaultClock::GetInstance(), /*task_runner=*/nullptr); - partition->cache_storage_context_ = new CacheStorageContextImpl(context); - partition->cache_storage_context_->Init( - path, context->GetSpecialStoragePolicy(), quota_manager_proxy); + cache_storage_context_ = new CacheStorageContextImpl(browser_context_); + cache_storage_context_->Init( + path, browser_context_->GetSpecialStoragePolicy(), quota_manager_proxy); - partition->service_worker_context_ = new ServiceWorkerContextWrapper(context); - partition->service_worker_context_->set_storage_partition(partition.get()); + service_worker_context_ = new ServiceWorkerContextWrapper(browser_context_); + service_worker_context_->set_storage_partition(this); - partition->appcache_service_ = base::MakeRefCounted<ChromeAppCacheService>( - quota_manager_proxy.get(), partition->weak_factory_.GetWeakPtr()); + appcache_service_ = base::MakeRefCounted<ChromeAppCacheService>( + quota_manager_proxy.get(), weak_factory_.GetWeakPtr()); - partition->shared_worker_service_ = std::make_unique<SharedWorkerServiceImpl>( - partition.get(), partition->service_worker_context_, - partition->appcache_service_); + shared_worker_service_ = std::make_unique<SharedWorkerServiceImpl>( + this, service_worker_context_, appcache_service_); - partition->push_messaging_context_ = - new PushMessagingContext(context, partition->service_worker_context_); + push_messaging_context_ = + new PushMessagingContext(browser_context_, service_worker_context_); #if !defined(OS_ANDROID) - partition->host_zoom_level_context_ = new HostZoomLevelContext( - context->CreateZoomLevelDelegate(partition_path)); + host_zoom_level_context_ = new HostZoomLevelContext( + browser_context_->CreateZoomLevelDelegate(partition_path_)); #endif // !defined(OS_ANDROID) - partition->platform_notification_context_ = - new PlatformNotificationContextImpl(path, context, - partition->service_worker_context_); - partition->platform_notification_context_->Initialize(); + platform_notification_context_ = new PlatformNotificationContextImpl( + path, browser_context_, service_worker_context_); + platform_notification_context_->Initialize(); - partition->devtools_background_services_context_ = + devtools_background_services_context_ = base::MakeRefCounted<DevToolsBackgroundServicesContextImpl>( - context, partition->service_worker_context_); + browser_context_, service_worker_context_); - partition->content_index_context_ = - base::MakeRefCounted<ContentIndexContextImpl>( - context, partition->service_worker_context_); + content_index_context_ = base::MakeRefCounted<ContentIndexContextImpl>( + browser_context_, service_worker_context_); - partition->background_fetch_context_ = - base::MakeRefCounted<BackgroundFetchContext>( - context, partition->service_worker_context_, - partition->cache_storage_context_, quota_manager_proxy, - partition->devtools_background_services_context_); + background_fetch_context_ = base::MakeRefCounted<BackgroundFetchContext>( + browser_context_, service_worker_context_, cache_storage_context_, + quota_manager_proxy, devtools_background_services_context_); - partition->background_sync_context_ = - base::MakeRefCounted<BackgroundSyncContextImpl>(); - partition->background_sync_context_->Init( - partition->service_worker_context_, - partition->devtools_background_services_context_); + background_sync_context_ = base::MakeRefCounted<BackgroundSyncContextImpl>(); + background_sync_context_->Init(service_worker_context_, + devtools_background_services_context_); - partition->payment_app_context_ = new PaymentAppContextImpl(); - partition->payment_app_context_->Init(partition->service_worker_context_); + payment_app_context_ = new PaymentAppContextImpl(); + payment_app_context_->Init(service_worker_context_); - partition->broadcast_channel_provider_ = new BroadcastChannelProvider(); + broadcast_channel_provider_ = new BroadcastChannelProvider(); - partition->bluetooth_allowed_devices_map_ = new BluetoothAllowedDevicesMap(); + bluetooth_allowed_devices_map_ = new BluetoothAllowedDevicesMap(); scoped_refptr<ChromeBlobStorageContext> blob_context = - ChromeBlobStorageContext::GetFor(context); + ChromeBlobStorageContext::GetFor(browser_context_); - partition->url_loader_factory_getter_ = new URLLoaderFactoryGetter(); - partition->url_loader_factory_getter_->Initialize(partition.get()); + url_loader_factory_getter_ = new URLLoaderFactoryGetter(); + url_loader_factory_getter_->Initialize(this); - partition->service_worker_context_->Init( - path, quota_manager_proxy.get(), context->GetSpecialStoragePolicy(), - blob_context.get(), partition->url_loader_factory_getter_.get()); + service_worker_context_->Init(path, quota_manager_proxy.get(), + browser_context_->GetSpecialStoragePolicy(), + blob_context.get(), + url_loader_factory_getter_.get()); - partition->blob_registry_ = - BlobRegistryWrapper::Create(blob_context, partition->filesystem_context_); + blob_registry_ = + BlobRegistryWrapper::Create(blob_context, filesystem_context_); - partition->prefetch_url_loader_service_ = - base::MakeRefCounted<PrefetchURLLoaderService>(context); + prefetch_url_loader_service_ = + base::MakeRefCounted<PrefetchURLLoaderService>(browser_context_); - partition->cookie_store_context_ = base::MakeRefCounted<CookieStoreContext>(); + cookie_store_context_ = base::MakeRefCounted<CookieStoreContext>(); // Unit tests use the Initialize() callback to crash early if restoring the // CookieManagerStore's state from ServiceWorkerStorage fails. Production and // browser tests rely on CookieStoreManager's well-defined behavior when // restoring the state fails. - partition->cookie_store_context_->Initialize( - partition->service_worker_context_, base::DoNothing()); + cookie_store_context_->Initialize(service_worker_context_, base::DoNothing()); - partition->native_file_system_manager_ = + native_file_system_manager_ = base::MakeRefCounted<NativeFileSystemManagerImpl>( - partition->filesystem_context_, blob_context, - context->GetNativeFileSystemPermissionContext()); + filesystem_context_, blob_context, + browser_context_->GetNativeFileSystemPermissionContext()); GeneratedCodeCacheSettings settings = - GetContentClient()->browser()->GetGeneratedCodeCacheSettings(context); + GetContentClient()->browser()->GetGeneratedCodeCacheSettings( + browser_context_); // For Incognito mode, we should not persist anything on the disk so // we do not create a code cache. Caching the generated code in memory // is not useful, since V8 already maintains one copy in memory. - if (!in_memory && settings.enabled()) { - partition->generated_code_cache_context_ = + if (!is_in_memory_ && settings.enabled()) { + generated_code_cache_context_ = base::MakeRefCounted<GeneratedCodeCacheContext>(); base::FilePath code_cache_path; - if (partition_domain.empty()) { + if (partition_domain_.empty()) { code_cache_path = settings.path().AppendASCII("Code Cache"); } else { // For site isolated partitions use the config directory. code_cache_path = settings.path() - .Append(relative_partition_path) + .Append(relative_partition_path_) .AppendASCII("Code Cache"); } DCHECK_GE(settings.size_in_bytes(), 0); - partition->GetGeneratedCodeCacheContext()->Initialize( - code_cache_path, settings.size_in_bytes()); + GetGeneratedCodeCacheContext()->Initialize(code_cache_path, + settings.size_in_bytes()); } - - return partition; } base::FilePath StoragePartitionImpl::GetPath() { @@ -955,6 +960,7 @@ } network::mojom::NetworkContext* StoragePartitionImpl::GetNetworkContext() { + DCHECK(initialized_); if (!network_context_.is_bound()) InitNetworkContext(); return network_context_.get(); @@ -962,6 +968,7 @@ scoped_refptr<network::SharedURLLoaderFactory> StoragePartitionImpl::GetURLLoaderFactoryForBrowserProcess() { + DCHECK(initialized_); if (!shared_url_loader_factory_for_browser_process_) { shared_url_loader_factory_for_browser_process_ = new URLLoaderFactoryForBrowserProcess(this, false /* corb_enabled */); @@ -971,6 +978,7 @@ scoped_refptr<network::SharedURLLoaderFactory> StoragePartitionImpl::GetURLLoaderFactoryForBrowserProcessWithCORBEnabled() { + DCHECK(initialized_); if (!shared_url_loader_factory_for_browser_process_with_corb_) { shared_url_loader_factory_for_browser_process_with_corb_ = new URLLoaderFactoryForBrowserProcess(this, true /* corb_enabled */); @@ -980,11 +988,13 @@ std::unique_ptr<network::SharedURLLoaderFactoryInfo> StoragePartitionImpl::GetURLLoaderFactoryForBrowserProcessIOThread() { + DCHECK(initialized_); return url_loader_factory_getter_->GetNetworkFactoryInfo(); } network::mojom::CookieManager* StoragePartitionImpl::GetCookieManagerForBrowserProcess() { + DCHECK(initialized_); // Create the CookieManager as needed. if (!cookie_manager_for_browser_process_ || cookie_manager_for_browser_process_.encountered_error()) { @@ -1001,6 +1011,7 @@ int process_id, int routing_id, network::mojom::RestrictedCookieManagerRequest request) { + DCHECK(initialized_); if (!GetContentClient()->browser()->WillCreateRestrictedCookieManager( role, browser_context_, origin, is_service_worker, process_id, routing_id, &request)) { @@ -1011,69 +1022,85 @@ } storage::QuotaManager* StoragePartitionImpl::GetQuotaManager() { + DCHECK(initialized_); return quota_manager_.get(); } ChromeAppCacheService* StoragePartitionImpl::GetAppCacheService() { + DCHECK(initialized_); return appcache_service_.get(); } BackgroundSyncContextImpl* StoragePartitionImpl::GetBackgroundSyncContext() { + DCHECK(initialized_); return background_sync_context_.get(); } storage::FileSystemContext* StoragePartitionImpl::GetFileSystemContext() { + DCHECK(initialized_); return filesystem_context_.get(); } storage::DatabaseTracker* StoragePartitionImpl::GetDatabaseTracker() { + DCHECK(initialized_); return database_tracker_.get(); } DOMStorageContextWrapper* StoragePartitionImpl::GetDOMStorageContext() { + DCHECK(initialized_); return dom_storage_context_.get(); } IdleManager* StoragePartitionImpl::GetIdleManager() { + DCHECK(initialized_); return idle_manager_.get(); } LockManager* StoragePartitionImpl::GetLockManager() { + DCHECK(initialized_); return lock_manager_.get(); } IndexedDBContextImpl* StoragePartitionImpl::GetIndexedDBContext() { + DCHECK(initialized_); return indexed_db_context_.get(); } NativeFileSystemEntryFactory* StoragePartitionImpl::GetNativeFileSystemEntryFactory() { + DCHECK(initialized_); return native_file_system_manager_.get(); } CacheStorageContextImpl* StoragePartitionImpl::GetCacheStorageContext() { + DCHECK(initialized_); return cache_storage_context_.get(); } ServiceWorkerContextWrapper* StoragePartitionImpl::GetServiceWorkerContext() { + DCHECK(initialized_); return service_worker_context_.get(); } SharedWorkerServiceImpl* StoragePartitionImpl::GetSharedWorkerService() { + DCHECK(initialized_); return shared_worker_service_.get(); } #if !defined(OS_ANDROID) HostZoomMap* StoragePartitionImpl::GetHostZoomMap() { + DCHECK(initialized_); DCHECK(host_zoom_level_context_.get()); return host_zoom_level_context_->GetHostZoomMap(); } HostZoomLevelContext* StoragePartitionImpl::GetHostZoomLevelContext() { + DCHECK(initialized_); return host_zoom_level_context_.get(); } ZoomLevelDelegate* StoragePartitionImpl::GetZoomLevelDelegate() { + DCHECK(initialized_); DCHECK(host_zoom_level_context_.get()); return host_zoom_level_context_->GetZoomLevelDelegate(); } @@ -1081,54 +1108,66 @@ PlatformNotificationContextImpl* StoragePartitionImpl::GetPlatformNotificationContext() { + DCHECK(initialized_); return platform_notification_context_.get(); } BackgroundFetchContext* StoragePartitionImpl::GetBackgroundFetchContext() { + DCHECK(initialized_); return background_fetch_context_.get(); } PaymentAppContextImpl* StoragePartitionImpl::GetPaymentAppContext() { + DCHECK(initialized_); return payment_app_context_.get(); } BroadcastChannelProvider* StoragePartitionImpl::GetBroadcastChannelProvider() { + DCHECK(initialized_); return broadcast_channel_provider_.get(); } BluetoothAllowedDevicesMap* StoragePartitionImpl::GetBluetoothAllowedDevicesMap() { + DCHECK(initialized_); return bluetooth_allowed_devices_map_.get(); } BlobRegistryWrapper* StoragePartitionImpl::GetBlobRegistry() { + DCHECK(initialized_); return blob_registry_.get(); } PrefetchURLLoaderService* StoragePartitionImpl::GetPrefetchURLLoaderService() { + DCHECK(initialized_); return prefetch_url_loader_service_.get(); } CookieStoreContext* StoragePartitionImpl::GetCookieStoreContext() { + DCHECK(initialized_); return cookie_store_context_.get(); } GeneratedCodeCacheContext* StoragePartitionImpl::GetGeneratedCodeCacheContext() { + DCHECK(initialized_); return generated_code_cache_context_.get(); } DevToolsBackgroundServicesContextImpl* StoragePartitionImpl::GetDevToolsBackgroundServicesContext() { + DCHECK(initialized_); return devtools_background_services_context_.get(); } NativeFileSystemManagerImpl* StoragePartitionImpl::GetNativeFileSystemManager() { + DCHECK(initialized_); return native_file_system_manager_.get(); } ContentIndexContextImpl* StoragePartitionImpl::GetContentIndexContext() { + DCHECK(initialized_); return content_index_context_.get(); } @@ -1150,6 +1189,7 @@ void StoragePartitionImpl::OpenLocalStorage( const url::Origin& origin, blink::mojom::StorageAreaRequest request) { + DCHECK(initialized_); int process_id = bindings_.dispatch_context(); // TODO(943887): Replace HasSecurityState() call with something that can // preserve security state after process shutdown. The security state check @@ -1170,6 +1210,7 @@ void StoragePartitionImpl::OpenSessionStorage( const std::string& namespace_id, blink::mojom::SessionStorageNamespaceRequest request) { + DCHECK(initialized_); int process_id = bindings_.dispatch_context(); dom_storage_context_->OpenSessionStorage(process_id, namespace_id, bindings_.GetBadMessageCallback(), @@ -1179,6 +1220,7 @@ void StoragePartitionImpl::OnCanSendReportingReports( const std::vector<url::Origin>& origins, OnCanSendReportingReportsCallback callback) { + DCHECK(initialized_); PermissionController* permission_controller = BrowserContext::GetPermissionController(browser_context_); DCHECK(permission_controller); @@ -1199,6 +1241,7 @@ void StoragePartitionImpl::OnCanSendDomainReliabilityUpload( const GURL& origin, OnCanSendDomainReliabilityUploadCallback callback) { + DCHECK(initialized_); PermissionController* permission_controller = BrowserContext::GetPermissionController(browser_context_); std::move(callback).Run( @@ -1213,6 +1256,7 @@ const std::string& header_value, int load_flags, OnClearSiteDataCallback callback) { + DCHECK(initialized_); auto browser_context_getter = base::BindRepeating( GetBrowserContextFromStoragePartition, weak_factory_.GetWeakPtr()); auto web_contents_getter = base::BindRepeating( @@ -1230,6 +1274,7 @@ const GURL& site_for_cookies, const std::vector<net::CookieWithStatus>& cookie_list) { DCHECK_CURRENTLY_ON(BrowserThread::UI); + DCHECK(initialized_); if (is_service_worker) { base::PostTask(FROM_HERE, {BrowserThread::IO}, base::BindOnce(&OnServiceWorkerCookiesChangedOnIO, @@ -1250,6 +1295,7 @@ const GURL& site_for_cookies, const std::vector<net::CookieWithStatus>& cookie_list) { DCHECK_CURRENTLY_ON(BrowserThread::UI); + DCHECK(initialized_); if (is_service_worker) { base::PostTask( FROM_HERE, {BrowserThread::IO}, @@ -1554,6 +1600,7 @@ uint32_t quota_storage_remove_mask, const GURL& storage_origin) { DCHECK_CURRENTLY_ON(BrowserThread::UI); + DCHECK(initialized_); CookieDeletionFilterPtr deletion_filter = CookieDeletionFilter::New(); if (!storage_origin.host().empty()) deletion_filter->host_name = storage_origin.host(); @@ -1568,6 +1615,7 @@ const base::Time begin, const base::Time end, base::OnceClosure callback) { + DCHECK(initialized_); CookieDeletionFilterPtr deletion_filter = CookieDeletionFilter::New(); if (!storage_origin.host().empty()) deletion_filter->host_name = storage_origin.host(); @@ -1587,6 +1635,7 @@ const base::Time begin, const base::Time end, base::OnceClosure callback) { + DCHECK(initialized_); ClearDataImpl(remove_mask, quota_storage_remove_mask, GURL(), origin_matcher, std::move(cookie_deletion_filter), perform_storage_cleanup, begin, end, std::move(callback)); @@ -1597,6 +1646,7 @@ const base::Time end, const base::RepeatingCallback<bool(const GURL&)>& url_matcher, base::OnceClosure callback) { + DCHECK(initialized_); // StoragePartitionCodeCacheDataRemover deletes itself when it is done. StoragePartitionCodeCacheDataRemover::Create(this, url_matcher, begin, end) ->Remove(std::move(callback)); @@ -1604,11 +1654,13 @@ void StoragePartitionImpl::Flush() { DCHECK_CURRENTLY_ON(BrowserThread::UI); + DCHECK(initialized_); if (GetDOMStorageContext()) GetDOMStorageContext()->Flush(); } void StoragePartitionImpl::ResetURLLoaderFactories() { + DCHECK(initialized_); GetNetworkContext()->ResetURLLoaderFactories(); url_loader_factory_for_browser_process_.reset(); url_loader_factory_for_browser_process_with_corb_.reset(); @@ -1616,10 +1668,12 @@ } void StoragePartitionImpl::ClearBluetoothAllowedDevicesMapForTesting() { + DCHECK(initialized_); bluetooth_allowed_devices_map_->Clear(); } void StoragePartitionImpl::FlushNetworkInterfaceForTesting() { + DCHECK(initialized_); DCHECK(network_context_); network_context_.FlushForTesting(); if (url_loader_factory_for_browser_process_) @@ -1633,6 +1687,7 @@ } void StoragePartitionImpl::WaitForDeletionTasksForTesting() { + DCHECK(initialized_); if (deletion_helpers_running_) { base::RunLoop loop; on_deletion_helpers_done_callback_ = loop.QuitClosure(); @@ -1641,6 +1696,7 @@ } void StoragePartitionImpl::WaitForCodeCacheShutdownForTesting() { + DCHECK(initialized_); if (generated_code_cache_context_) { // If this is still running its initialization task it may check // enabled features on a sequenced worker pool which could race @@ -1662,30 +1718,36 @@ mojo::BindingId StoragePartitionImpl::Bind( int process_id, mojo::InterfaceRequest<blink::mojom::StoragePartitionService> request) { + DCHECK(initialized_); return bindings_.AddBinding(this, std::move(request), process_id); } void StoragePartitionImpl::Unbind(mojo::BindingId binding_id) { + DCHECK(initialized_); bindings_.RemoveBinding(binding_id); } void StoragePartitionImpl::OverrideQuotaManagerForTesting( storage::QuotaManager* quota_manager) { + DCHECK(initialized_); quota_manager_ = quota_manager; } void StoragePartitionImpl::OverrideSpecialStoragePolicyForTesting( storage::SpecialStoragePolicy* special_storage_policy) { + DCHECK(initialized_); special_storage_policy_ = special_storage_policy; } void StoragePartitionImpl::ShutdownBackgroundSyncContextForTesting() { + DCHECK(initialized_); if (GetBackgroundSyncContext()) GetBackgroundSyncContext()->Shutdown(); } void StoragePartitionImpl::OverrideBackgroundSyncContextForTesting( BackgroundSyncContextImpl* background_sync_context) { + DCHECK(initialized_); DCHECK(!GetBackgroundSyncContext() || !GetBackgroundSyncContext()->background_sync_manager()); background_sync_context_ = background_sync_context; @@ -1754,6 +1816,7 @@ network::mojom::OriginPolicyManager* StoragePartitionImpl::GetOriginPolicyManagerForBrowserProcess() { + DCHECK(initialized_); if (!origin_policy_manager_for_browser_process_ || origin_policy_manager_for_browser_process_.encountered_error()) { GetNetworkContext()->GetOriginPolicyManager( @@ -1764,12 +1827,14 @@ void StoragePartitionImpl::SetOriginPolicyManagerForBrowserProcessForTesting( network::mojom::OriginPolicyManagerPtr test_origin_policy_manager) { + DCHECK(initialized_); origin_policy_manager_for_browser_process_ = std::move(test_origin_policy_manager); } void StoragePartitionImpl:: ResetOriginPolicyManagerForBrowserProcessForTesting() { + DCHECK(initialized_); origin_policy_manager_for_browser_process_ = nullptr; }
diff --git a/content/browser/storage_partition_impl.h b/content/browser/storage_partition_impl.h index 40df282f6..2ef45ac 100644 --- a/content/browser/storage_partition_impl.h +++ b/content/browser/storage_partition_impl.h
@@ -302,6 +302,8 @@ // If |in_memory| is true, the |relative_partition_path| is (ab)used as a way // of distinguishing different in-memory partitions, but nothing is persisted // on to disk. + // + // Initialize() must be called on the StoragePartitionImpl before using it. static std::unique_ptr<StoragePartitionImpl> Create( BrowserContext* context, bool in_memory, @@ -310,8 +312,18 @@ StoragePartitionImpl(BrowserContext* browser_context, const base::FilePath& partition_path, + bool is_in_memory, + const base::FilePath& relative_partition_path, + const std::string& partition_domain, storage::SpecialStoragePolicy* special_storage_policy); + // This must be called before calling any members of the StoragePartitionImpl + // except for GetPath and browser_context(). + // The purpose of the Create, Initialize sequence is that code that + // initializes members of the StoragePartitionImpl and gets a pointer to it + // can query properties of the StoragePartitionImpl (notably GetPath()). + void Initialize(); + // We will never have both remove_origin be populated and a cookie_matcher. void ClearDataImpl( uint32_t remove_mask, @@ -337,11 +349,24 @@ network::mojom::URLLoaderFactory* GetURLLoaderFactoryForBrowserProcessInternal(bool corb_enabled); - // |is_in_memory_| and |relative_partition_path_| are cached from - // |StoragePartitionImpl::Create()| in order to re-create |NetworkContext|. - bool is_in_memory_; - base::FilePath relative_partition_path_; - base::FilePath partition_path_; + // Raw pointer that should always be valid. The BrowserContext owns the + // StoragePartitionImplMap which then owns StoragePartitionImpl. When the + // BrowserContext is destroyed, |this| will be destroyed too. + BrowserContext* browser_context_; + + const base::FilePath partition_path_; + + // |is_in_memory_|, |relative_partition_path_| and |partition_domain_| are + // cached from |StoragePartitionImpl::Create()| in order to re-create + // |NetworkContext|. + const bool is_in_memory_; + const base::FilePath relative_partition_path_; + const std::string partition_domain_; + + // Until a StoragePartitionImpl is initialized using Initialize(), only + // querying its path abd BrowserContext is allowed. + bool initialized_ = false; + scoped_refptr<URLLoaderFactoryGetter> url_loader_factory_getter_; scoped_refptr<storage::QuotaManager> quota_manager_; scoped_refptr<ChromeAppCacheService> appcache_service_; @@ -410,11 +435,6 @@ network::mojom::OriginPolicyManagerPtr origin_policy_manager_for_browser_process_; - // Raw pointer that should always be valid. The BrowserContext owns the - // StoragePartitionImplMap which then owns StoragePartitionImpl. When the - // BrowserContext is destroyed, |this| will be destroyed too. - BrowserContext* browser_context_; - // See comments for site_for_service_worker(). GURL site_for_service_worker_;
diff --git a/content/browser/storage_partition_impl_map.cc b/content/browser/storage_partition_impl_map.cc index a68b4c5..b11e9dd 100644 --- a/content/browser/storage_partition_impl_map.cc +++ b/content/browser/storage_partition_impl_map.cc
@@ -350,6 +350,7 @@ relative_partition_path, partition_domain)); StoragePartitionImpl* partition = partition_ptr.get(); partitions_[partition_config] = std::move(partition_ptr); + partition->Initialize(); // Arm the serviceworker cookie change observation API. partition->GetCookieStoreContext()->ListenToCookieChanges(
diff --git a/content/child/blink_platform_impl.cc b/content/child/blink_platform_impl.cc index 0fe0175..acf0685 100644 --- a/content/child/blink_platform_impl.cc +++ b/content/child/blink_platform_impl.cc
@@ -427,10 +427,6 @@ false}, {"generatePasswordHover", IDR_PASSWORD_GENERATION_ICON_HOVER, ui::SCALE_FACTOR_100P, false}, - {"html.css", IDR_UASTYLE_HTML_CSS, ui::SCALE_FACTOR_NONE, true}, - {"quirks.css", IDR_UASTYLE_QUIRKS_CSS, ui::SCALE_FACTOR_NONE, true}, - {"view-source.css", IDR_UASTYLE_VIEW_SOURCE_CSS, ui::SCALE_FACTOR_NONE, - true}, // Not limited to Android since it's used for mobile layouts in inspector. {"android.css", IDR_UASTYLE_THEME_CHROMIUM_ANDROID_CSS, ui::SCALE_FACTOR_NONE, true}, @@ -452,18 +448,10 @@ ui::SCALE_FACTOR_NONE, true}, {"forced_colors.css", IDR_UASTYLE_THEME_FORCED_COLORS_CSS, ui::SCALE_FACTOR_NONE, true}, - {"svg.css", IDR_UASTYLE_SVG_CSS, ui::SCALE_FACTOR_NONE, true}, - {"mathml.css", IDR_UASTYLE_MATHML_CSS, ui::SCALE_FACTOR_NONE, true}, - {"fullscreen.css", IDR_UASTYLE_FULLSCREEN_CSS, ui::SCALE_FACTOR_NONE, true}, - {"xhtmlmp.css", IDR_UASTYLE_XHTMLMP_CSS, ui::SCALE_FACTOR_NONE, true}, - {"viewportAndroid.css", IDR_UASTYLE_VIEWPORT_ANDROID_CSS, - ui::SCALE_FACTOR_NONE, true}, #if defined(ENABLE_TOUCHLESS_UASTYLE_THEME) {"touchless.css", IDR_UASTYLE_THEME_TOUCHLESS_CSS, ui::SCALE_FACTOR_NONE, true}, #endif - {"viewportTelevision.css", IDR_UASTYLE_VIEWPORT_TELEVISION_CSS, - ui::SCALE_FACTOR_NONE, true}, {"DocumentXMLTreeViewer.css", IDR_DOCUMENTXMLTREEVIEWER_CSS, ui::SCALE_FACTOR_NONE, true}, {"DocumentXMLTreeViewer.js", IDR_DOCUMENTXMLTREEVIEWER_JS,
diff --git a/content/public/browser/payment_app_provider.h b/content/public/browser/payment_app_provider.h index 99cbd894..10de961 100644 --- a/content/public/browser/payment_app_provider.h +++ b/content/public/browser/payment_app_provider.h
@@ -41,6 +41,8 @@ using PaymentApps = std::map<int64_t, std::unique_ptr<StoredPaymentApp>>; using GetAllPaymentAppsCallback = base::OnceCallback<void(PaymentApps)>; + using RegistrationIdCallback = + base::OnceCallback<void(int64_t registration_id)>; using InvokePaymentAppCallback = base::OnceCallback<void(payments::mojom::PaymentHandlerResponsePtr)>; using PaymentEventResultCallback = base::OnceCallback<void(bool)>; @@ -63,6 +65,7 @@ const std::string& sw_scope, bool sw_use_cache, const std::string& method, + RegistrationIdCallback registration_id_callback, InvokePaymentAppCallback callback) = 0; virtual void CanMakePayment( BrowserContext* browser_context,
diff --git a/content/renderer/BUILD.gn b/content/renderer/BUILD.gn index 45daafa..f632b1e8c 100644 --- a/content/renderer/BUILD.gn +++ b/content/renderer/BUILD.gn
@@ -347,8 +347,6 @@ "service_worker/service_worker_fetch_context_impl.h", "service_worker/service_worker_network_provider_for_frame.cc", "service_worker/service_worker_network_provider_for_frame.h", - "service_worker/service_worker_network_provider_for_service_worker.cc", - "service_worker/service_worker_network_provider_for_service_worker.h", "service_worker/service_worker_provider_context.cc", "service_worker/service_worker_provider_context.h", "service_worker/service_worker_subresource_loader.cc",
diff --git a/content/renderer/service_worker/service_worker_context_client.cc b/content/renderer/service_worker/service_worker_context_client.cc index 8ad42b58..b40d242 100644 --- a/content/renderer/service_worker/service_worker_context_client.cc +++ b/content/renderer/service_worker/service_worker_context_client.cc
@@ -36,7 +36,6 @@ #include "content/renderer/service_worker/embedded_worker_instance_client_impl.h" #include "content/renderer/service_worker/navigation_preload_request.h" #include "content/renderer/service_worker/service_worker_fetch_context_impl.h" -#include "content/renderer/service_worker/service_worker_network_provider_for_service_worker.h" #include "content/renderer/service_worker/service_worker_type_converters.h" #include "net/base/net_errors.h" #include "services/network/public/cpp/features.h" @@ -385,41 +384,6 @@ blink::WebStringToGURL(source_url)); } -std::unique_ptr<blink::WebServiceWorkerNetworkProvider> -ServiceWorkerContextClient::CreateServiceWorkerNetworkProviderOnMainThread() { - DCHECK(starter_thread_task_runner_->RunsTasksInCurrentSequence()); - return std::make_unique<ServiceWorkerNetworkProviderForServiceWorker>( - std::move(service_worker_provider_info_->script_loader_factory_ptr_info)); -} - -scoped_refptr<blink::WebWorkerFetchContext> -ServiceWorkerContextClient::CreateWorkerFetchContextOnMainThreadLegacy( - blink::WebServiceWorkerNetworkProvider* provider) { - DCHECK(starter_thread_task_runner_->RunsTasksInCurrentSequence()); - DCHECK(preference_watcher_request_.is_pending()); - - // TODO(crbug.com/796425): Temporarily wrap the raw - // mojom::URLLoaderFactory pointer into SharedURLLoaderFactory. - std::unique_ptr<network::SharedURLLoaderFactoryInfo> - script_loader_factory_info = - base::MakeRefCounted<network::WeakWrapperSharedURLLoaderFactory>( - static_cast<ServiceWorkerNetworkProviderForServiceWorker*>( - provider) - ->script_loader_factory()) - ->Clone(); - - return base::MakeRefCounted<ServiceWorkerFetchContextImpl>( - *renderer_preferences_, script_url_, loader_factories_->PassInterface(), - std::move(script_loader_factory_info), - GetContentClient()->renderer()->CreateURLLoaderThrottleProvider( - URLLoaderThrottleProviderType::kWorker), - GetContentClient() - ->renderer() - ->CreateWebSocketHandshakeThrottleProvider(), - std::move(preference_watcher_request_), - std::move(pending_subresource_loader_updater_)); -} - scoped_refptr<blink::WebWorkerFetchContext> ServiceWorkerContextClient::CreateWorkerFetchContextOnMainThread() { DCHECK(starter_thread_task_runner_->RunsTasksInCurrentSequence());
diff --git a/content/renderer/service_worker/service_worker_context_client.h b/content/renderer/service_worker/service_worker_context_client.h index 11d30e6..3fffb0f 100644 --- a/content/renderer/service_worker/service_worker_context_client.h +++ b/content/renderer/service_worker/service_worker_context_client.h
@@ -144,11 +144,6 @@ std::unique_ptr<blink::WebFetchEventPreloadHandle> preload_handle) override; void RequestTermination(RequestTerminationCallback callback) override; - std::unique_ptr<blink::WebServiceWorkerNetworkProvider> - CreateServiceWorkerNetworkProviderOnMainThread() override; - scoped_refptr<blink::WebWorkerFetchContext> - CreateWorkerFetchContextOnMainThreadLegacy( - blink::WebServiceWorkerNetworkProvider*) override; scoped_refptr<blink::WebWorkerFetchContext> CreateWorkerFetchContextOnMainThread() override;
diff --git a/content/renderer/service_worker/service_worker_network_provider_for_service_worker.cc b/content/renderer/service_worker/service_worker_network_provider_for_service_worker.cc deleted file mode 100644 index ff00bb2..0000000 --- a/content/renderer/service_worker/service_worker_network_provider_for_service_worker.cc +++ /dev/null
@@ -1,88 +0,0 @@ -// Copyright 2019 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "content/renderer/service_worker/service_worker_network_provider_for_service_worker.h" - -#include <utility> - -#include "content/public/common/resource_type.h" -#include "content/public/renderer/url_loader_throttle_provider.h" -#include "content/renderer/loader/request_extra_data.h" -#include "content/renderer/loader/web_url_loader_impl.h" -#include "content/renderer/loader/web_url_request_util.h" -#include "content/renderer/render_thread_impl.h" -#include "ipc/ipc_message.h" -#include "services/network/public/cpp/weak_wrapper_shared_url_loader_factory.h" -#include "third_party/blink/public/mojom/service_worker/service_worker_object.mojom.h" -#include "third_party/blink/public/platform/web_url.h" -#include "third_party/blink/public/platform/web_url_request.h" - -namespace content { - -ServiceWorkerNetworkProviderForServiceWorker:: - ServiceWorkerNetworkProviderForServiceWorker( - network::mojom::URLLoaderFactoryPtrInfo script_loader_factory_info) - : script_loader_factory_(std::move(script_loader_factory_info)) {} - -ServiceWorkerNetworkProviderForServiceWorker:: - ~ServiceWorkerNetworkProviderForServiceWorker() = default; - -void ServiceWorkerNetworkProviderForServiceWorker::WillSendRequest( - blink::WebURLRequest& request) { - auto extra_data = std::make_unique<RequestExtraData>(); - extra_data->set_originated_from_service_worker(true); - - // The RenderThreadImpl or its URLLoaderThrottleProvider member may not be - // valid in some tests. - RenderThreadImpl* render_thread = RenderThreadImpl::current(); - if (render_thread && render_thread->url_loader_throttle_provider()) { - extra_data->set_url_loader_throttles( - render_thread->url_loader_throttle_provider()->CreateThrottles( - MSG_ROUTING_NONE, request, WebURLRequestToResourceType(request))); - } - - request.SetExtraData(std::move(extra_data)); -} - -std::unique_ptr<blink::WebURLLoader> -ServiceWorkerNetworkProviderForServiceWorker::CreateURLLoader( - const blink::WebURLRequest& request, - std::unique_ptr<blink::scheduler::WebResourceLoadingTaskRunnerHandle> - task_runner_handle) { - if (request.GetRequestContext() != - blink::mojom::RequestContextType::SERVICE_WORKER) { - // This provider is only used for requests from the shadow page, which is - // created to load the service worker's main script. But shadow pages - // sometimes request strange things like CSS resources because consumers - // think it's a real frame. Just return nullptr to use the default loader - // instead of the script loader. - return nullptr; - } - - RenderThreadImpl* render_thread = RenderThreadImpl::current(); - // RenderThreadImpl may be null in some tests. - if (render_thread && script_loader_factory()) { - // TODO(crbug.com/796425): Temporarily wrap the raw - // mojom::URLLoaderFactory pointer into SharedURLLoaderFactory. - return std::make_unique<WebURLLoaderImpl>( - render_thread->resource_dispatcher(), std::move(task_runner_handle), - base::MakeRefCounted<network::WeakWrapperSharedURLLoaderFactory>( - script_loader_factory())); - } - return nullptr; -} - -blink::mojom::ControllerServiceWorkerMode -ServiceWorkerNetworkProviderForServiceWorker::GetControllerServiceWorkerMode() { - return blink::mojom::ControllerServiceWorkerMode::kNoController; -} - -int64_t -ServiceWorkerNetworkProviderForServiceWorker::ControllerServiceWorkerID() { - return blink::mojom::kInvalidServiceWorkerVersionId; -} - -void ServiceWorkerNetworkProviderForServiceWorker::DispatchNetworkQuiet() {} - -} // namespace content
diff --git a/content/renderer/service_worker/service_worker_network_provider_for_service_worker.h b/content/renderer/service_worker/service_worker_network_provider_for_service_worker.h deleted file mode 100644 index f130ebd..0000000 --- a/content/renderer/service_worker/service_worker_network_provider_for_service_worker.h +++ /dev/null
@@ -1,50 +0,0 @@ -// Copyright 2019 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CONTENT_RENDERER_SERVICE_WORKER_SERVICE_WORKER_NETWORK_PROVIDER_FOR_SERVICE_WORKER_H_ -#define CONTENT_RENDERER_SERVICE_WORKER_SERVICE_WORKER_NETWORK_PROVIDER_FOR_SERVICE_WORKER_H_ - -#include <memory> - -#include "services/network/public/mojom/url_loader_factory.mojom.h" -#include "third_party/blink/public/platform/modules/service_worker/web_service_worker_network_provider.h" -#include "third_party/blink/public/platform/web_url_request.h" - -namespace content { - -// The WebServiceWorkerNetworkProvider implementation for service worker -// execution contexts. -// -// This class is only used for the main script request from the shadow page. -// Remove it when the shadow page is removed (https://crbug.com/538751). -class ServiceWorkerNetworkProviderForServiceWorker final - : public blink::WebServiceWorkerNetworkProvider { - public: - explicit ServiceWorkerNetworkProviderForServiceWorker( - network::mojom::URLLoaderFactoryPtrInfo script_loader_factory_info); - ~ServiceWorkerNetworkProviderForServiceWorker() override; - - // blink::WebServiceWorkerNetworkProvider: - void WillSendRequest(blink::WebURLRequest& request) override; - std::unique_ptr<blink::WebURLLoader> CreateURLLoader( - const blink::WebURLRequest& request, - std::unique_ptr<blink::scheduler::WebResourceLoadingTaskRunnerHandle> - task_runner_handle) override; - blink::mojom::ControllerServiceWorkerMode GetControllerServiceWorkerMode() - override; - int64_t ControllerServiceWorkerID() override; - void DispatchNetworkQuiet() override; - - network::mojom::URLLoaderFactory* script_loader_factory() { - return script_loader_factory_.get(); - } - - private: - // The URL loader factory for loading the service worker's scripts. - network::mojom::URLLoaderFactoryPtr script_loader_factory_; -}; - -} // namespace content - -#endif // CONTENT_RENDERER_SERVICE_WORKER_SERVICE_WORKER_NETWORK_PROVIDER_FOR_SERVICE_WORKER_H_
diff --git a/content/renderer/worker/embedded_shared_worker_stub.cc b/content/renderer/worker/embedded_shared_worker_stub.cc index c65aae96..e9f9ca5 100644 --- a/content/renderer/worker/embedded_shared_worker_stub.cc +++ b/content/renderer/worker/embedded_shared_worker_stub.cc
@@ -24,7 +24,6 @@ #include "third_party/blink/public/common/features.h" #include "third_party/blink/public/common/loader/url_loader_factory_bundle.h" #include "third_party/blink/public/common/messaging/message_port_channel.h" -#include "third_party/blink/public/common/privacy_preferences.h" #include "third_party/blink/public/mojom/appcache/appcache.mojom.h" #include "third_party/blink/public/mojom/renderer_preferences.mojom.h" #include "third_party/blink/public/mojom/service_worker/controller_service_worker.mojom.h" @@ -79,13 +78,6 @@ main_script_load_params->redirect_response_heads; response_override_->redirect_infos = main_script_load_params->redirect_infos; - impl_ = blink::WebSharedWorker::Create(this, appcache_host_id); - if (pause_on_start) { - // Pause worker context when it starts and wait until either DevTools client - // is attached or explicit resume notification is received. - impl_->PauseWorkerContextOnStart(); - } - // If the network service crashes, then self-destruct so clients don't get // stuck with a worker with a broken loader. Self-destruction is effectively // the same as the worker's process crashing. @@ -116,18 +108,15 @@ std::move(controller_info), subresource_loader_factory_bundle_); } + impl_ = blink::WebSharedWorker::Create(this, appcache_host_id); impl_->StartWorkerContext( url_, blink::WebString::FromUTF8(info->name), blink::WebString::FromUTF8(user_agent), blink::WebString::FromUTF8(info->content_security_policy), info->content_security_policy_type, info->creation_address_space, - devtools_worker_token, - blink::PrivacyPreferences(renderer_preferences_.enable_do_not_track, - renderer_preferences_.enable_referrers), - subresource_loader_factory_bundle_, - content_settings.PassInterface().PassHandle(), + devtools_worker_token, content_settings.PassInterface().PassHandle(), interface_provider.PassInterface().PassHandle(), - browser_interface_broker.PassPipe()); + browser_interface_broker.PassPipe(), pause_on_start); // If the host drops its connection, then self-destruct. binding_.set_connection_error_handler(base::BindOnce(
diff --git a/content/shell/resources/brokenCanvas.png b/content/shell/resources/brokenCanvas.png index d357c8b..e9185bf 100644 --- a/content/shell/resources/brokenCanvas.png +++ b/content/shell/resources/brokenCanvas.png Binary files differ
diff --git a/content/test/gpu/gpu_tests/test_expectations/webgl_conformance_expectations.txt b/content/test/gpu/gpu_tests/test_expectations/webgl_conformance_expectations.txt index 5d95bde..89bc7b6 100644 --- a/content/test/gpu/gpu_tests/test_expectations/webgl_conformance_expectations.txt +++ b/content/test/gpu/gpu_tests/test_expectations/webgl_conformance_expectations.txt
@@ -1,7 +1,7 @@ # tags: [ android chromeos linux mac win win10 win7 ] # tags: [ android-chromium android-webview-instrumentation ] # tags: [ debug release ] -# tags: [ amd amd-0x6613 amd-0x699f intel intel-0xa011 intel-0xa2e nvidia +# tags: [ amd amd-0x6613 amd-0x699f amd-0x679e intel intel-0xa011 intel-0xa2e nvidia # nvidia-0x1cb3 nvidia-0x2184 nvidia-0xfe9 qualcomm # qualcomm-adreno-(tm)-330 qualcomm-adreno-(tm)-418 # qualcomm-adreno-(tm)-420 qualcomm-adreno-(tm)-430 ] @@ -190,6 +190,7 @@ crbug.com/617148 [ win d3d9 ] conformance/glsl/matrices/glsl-mat3-construction.html [ RetryOnFailure ] crbug.com/674572 [ win d3d9 ] conformance/glsl/misc/large-loop-compile.html [ Skip ] crbug.com/956134 [ win d3d9 ] conformance/extensions/webgl-depth-texture.html [ Skip ] +crbug.com/992224 [ win d3d9 ] conformance/glsl/samplers/glsl-function-texture2dproj.html [ RetryOnFailure ] # WIN / OpenGL / NVIDIA failures crbug.com/715001 [ win nvidia opengl passthrough ] conformance/limits/gl-max-texture-dimensions.html [ Failure ] @@ -385,6 +386,9 @@ # Mac / Passthrough command decoder / AMD crbug.com/angleproject/3767 [ mac passthrough amd ] conformance/rendering/rendering-stencil-large-viewport.html [ Failure ] +# Mac Pro (AMD) / Passthrough command decoder +crbug.com/992231 [ mac passthrough amd-0x679e ] conformance/context/context-size-change.html [ Failure ] + #################### # Linux failures # ####################
diff --git a/dbus/bus_unittest.cc b/dbus/bus_unittest.cc index 1981a71e..f24678b9 100644 --- a/dbus/bus_unittest.cc +++ b/dbus/bus_unittest.cc
@@ -318,11 +318,8 @@ } TEST(BusTest, ListenForServiceOwnerChange) { - base::MessageLoopForIO message_loop; - - // This enables FileDescriptorWatcher, which is required by dbus::Watch. - base::FileDescriptorWatcher file_descriptor_watcher( - message_loop.task_runner()); + base::test::ScopedTaskEnvironment scoped_task_environment( + base::test::ScopedTaskEnvironment::MainThreadType::IO); RunLoopWithExpectedCount run_loop_state;
diff --git a/docs/flag_expiry.md b/docs/flag_expiry.md index f739ccb..adef5f9 100644 --- a/docs/flag_expiry.md +++ b/docs/flag_expiry.md
@@ -82,7 +82,6 @@ * cct-module-post-message * cct-module-use-intent-extras * crostini-usb-support -* cryptauth-v2-enrollment * document-passive-wheel-event-listeners * enable-app-list-search-autocomplete * enable-arc-cups-api
diff --git a/docs/ui/android/mvc_simple_list_tutorial.md b/docs/ui/android/mvc_simple_list_tutorial.md index 442cbdf..360a13c 100644 --- a/docs/ui/android/mvc_simple_list_tutorial.md +++ b/docs/ui/android/mvc_simple_list_tutorial.md
@@ -37,13 +37,10 @@ // Once this is attached to the ListView, there is no need to hold a reference to it. ModelListAdapter adapter = new ModelListAdapter(listItems); - final LayoutInflater layoutInflater = - (LayoutInflater) context.getSystemService(LAYOUT_INFLATER_SERVICE); - // If this is a heterogeneous list, register more than one type. adapter.registerType( ListItemType.DEFAULT, - () -> layoutInflater.inflate(R.layout.simple_menu_item, null), + () -> LayoutInflater.from(context).inflate(R.layout.simple_menu_item, null), SimpleMenuItemViewBinder::bind); listView.setAdapter(adapter);
diff --git a/ios/chrome/app/application_delegate/app_state.mm b/ios/chrome/app/application_delegate/app_state.mm index 7177e862..a97ba2a2 100644 --- a/ios/chrome/app/application_delegate/app_state.mm +++ b/ios/chrome/app/application_delegate/app_state.mm
@@ -65,7 +65,7 @@ namespace { // Helper method to post |closure| on the UI thread. void PostTaskOnUIThread(base::OnceClosure closure) { - base::PostTaskWithTraits(FROM_HERE, {web::WebThread::UI}, std::move(closure)); + base::PostTask(FROM_HERE, {web::WebThread::UI}, std::move(closure)); } NSString* const kStartupAttemptReset = @"StartupAttempReset"; } // namespace @@ -242,7 +242,7 @@ DCHECK_CURRENTLY_ON(web::WebThread::UI); _savingCookies = NO; })); - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {web::WebThread::IO}, base::BindOnce(^{ net::CookieStoreIOS* store = static_cast<net::CookieStoreIOS*>( getter->GetURLRequestContext()->cookie_store());
diff --git a/ios/chrome/app/application_delegate/metrics_mediator.mm b/ios/chrome/app/application_delegate/metrics_mediator.mm index 9c409dc..8e4bdf8 100644 --- a/ios/chrome/app/application_delegate/metrics_mediator.mm +++ b/ios/chrome/app/application_delegate/metrics_mediator.mm
@@ -260,7 +260,7 @@ callback = ^(NSData* log_content) { std::string log(static_cast<const char*>([log_content bytes]), static_cast<size_t>([log_content length])); - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {web::WebThread::UI}, base::BindOnce(^{ GetApplicationContext()->GetMetricsService()->PushExternalLog(log); })); @@ -270,8 +270,9 @@ } app_group::main_app::RecordWidgetUsage(); - base::PostTaskWithTraits( - FROM_HERE, {base::MayBlock(), base::TaskPriority::BEST_EFFORT}, + base::PostTask( + FROM_HERE, + {base::ThreadPool(), base::MayBlock(), base::TaskPriority::BEST_EFFORT}, base::BindOnce(&app_group::main_app::ProcessPendingLogs, callback)); }
diff --git a/ios/chrome/app/main_controller.mm b/ios/chrome/app/main_controller.mm index 9cc1c15..d40ab38 100644 --- a/ios/chrome/app/main_controller.mm +++ b/ios/chrome/app/main_controller.mm
@@ -1944,10 +1944,10 @@ // OffTheRecordProfileIOData cannot be deleted before all the requests are // deleted. Queue browser state recreation on IO thread. - base::PostTaskWithTraitsAndReply( - FROM_HERE, {web::WebThread::IO}, base::DoNothing(), base::BindRepeating(^{ - [self destroyAndRebuildIncognitoBrowserState]; - })); + base::PostTaskAndReply(FROM_HERE, {web::WebThread::IO}, base::DoNothing(), + base::BindRepeating(^{ + [self destroyAndRebuildIncognitoBrowserState]; + })); // a) The first condition can happen when the last incognito tab is closed // from the tab switcher.
diff --git a/ios/chrome/app/memory_monitor.mm b/ios/chrome/app/memory_monitor.mm index 5b99c4c..5483f8c 100644 --- a/ios/chrome/app/memory_monitor.mm +++ b/ios/chrome/app/memory_monitor.mm
@@ -57,15 +57,17 @@ // |kMemoryMonitorDelayInSeconds|. void AsynchronousFreeMemoryMonitor() { UpdateMemoryValues(); - base::PostDelayedTaskWithTraits( - FROM_HERE, {base::MayBlock(), base::TaskPriority::BEST_EFFORT}, + base::PostDelayedTask( + FROM_HERE, + {base::ThreadPool(), base::MayBlock(), base::TaskPriority::BEST_EFFORT}, base::BindOnce(&AsynchronousFreeMemoryMonitor), base::TimeDelta::FromSeconds(kMemoryMonitorDelayInSeconds)); } } // namespace void StartFreeMemoryMonitor() { - base::PostTaskWithTraits(FROM_HERE, - {base::MayBlock(), base::TaskPriority::BEST_EFFORT}, - base::BindOnce(&AsynchronousFreeMemoryMonitor)); + base::PostTask( + FROM_HERE, + {base::ThreadPool(), base::MayBlock(), base::TaskPriority::BEST_EFFORT}, + base::BindOnce(&AsynchronousFreeMemoryMonitor)); }
diff --git a/ios/chrome/browser/application_context_impl.cc b/ios/chrome/browser/application_context_impl.cc index 6e46fc65..1893e7d 100644 --- a/ios/chrome/browser/application_context_impl.cc +++ b/ios/chrome/browser/application_context_impl.cc
@@ -78,10 +78,9 @@ void RequestProxyResolvingSocketFactory( ApplicationContextImpl* app_context, network::mojom::ProxyResolvingSocketFactoryRequest request) { - base::PostTaskWithTraits( - FROM_HERE, {web::WebThread::UI}, - base::BindOnce(&RequestProxyResolvingSocketFactoryOnUIThread, app_context, - std::move(request))); + base::PostTask(FROM_HERE, {web::WebThread::UI}, + base::BindOnce(&RequestProxyResolvingSocketFactoryOnUIThread, + app_context, std::move(request))); } // Passed to NetworkConnectionTracker to bind a NetworkChangeManagerRequest. @@ -405,8 +404,9 @@ CHECK(base::PathService::Get(ios::DIR_GLOBAL_GCM_STORE, &store_path)); scoped_refptr<base::SequencedTaskRunner> blocking_task_runner( - base::CreateSequencedTaskRunnerWithTraits( - {base::MayBlock(), base::TaskPriority::BEST_EFFORT, + base::CreateSequencedTaskRunner( + {base::ThreadPool(), base::MayBlock(), + base::TaskPriority::BEST_EFFORT, base::TaskShutdownBehavior::SKIP_ON_SHUTDOWN})); gcm_driver_ = gcm::CreateGCMDriverDesktop( @@ -418,7 +418,7 @@ GetSharedURLLoaderFactory(), GetApplicationContext()->GetNetworkConnectionTracker(), ::GetChannel(), IOSChromeGCMProfileServiceFactory::GetProductCategoryForSubtypes(), - base::CreateSingleThreadTaskRunnerWithTraits({web::WebThread::UI}), - base::CreateSingleThreadTaskRunnerWithTraits({web::WebThread::IO}), + base::CreateSingleThreadTaskRunner({web::WebThread::UI}), + base::CreateSingleThreadTaskRunner({web::WebThread::IO}), blocking_task_runner); }
diff --git a/ios/chrome/browser/bookmarks/bookmark_model_factory.cc b/ios/chrome/browser/bookmarks/bookmark_model_factory.cc index ffecba03..450644a5 100644 --- a/ios/chrome/browser/bookmarks/bookmark_model_factory.cc +++ b/ios/chrome/browser/bookmarks/bookmark_model_factory.cc
@@ -72,7 +72,7 @@ browser_state->GetPrefs(), browser_state->GetStatePath(), ios::StartupTaskRunnerServiceFactory::GetForBrowserState(browser_state) ->GetBookmarkTaskRunner(), - base::CreateSingleThreadTaskRunnerWithTraits({web::WebThread::UI})); + base::CreateSingleThreadTaskRunner({web::WebThread::UI})); ios::BookmarkUndoServiceFactory::GetForBrowserState(browser_state) ->Start(bookmark_model.get()); return bookmark_model;
diff --git a/ios/chrome/browser/browsing_data/browsing_data_remover_impl.mm b/ios/chrome/browser/browsing_data/browsing_data_remover_impl.mm index 1da7ba3f..ebb4f15 100644 --- a/ios/chrome/browser/browsing_data/browsing_data_remover_impl.mm +++ b/ios/chrome/browser/browsing_data/browsing_data_remover_impl.mm
@@ -293,7 +293,7 @@ if (IsRemoveDataMaskSet(mask, BrowsingDataRemoveMask::REMOVE_COOKIES)) { base::RecordAction(base::UserMetricsAction("ClearBrowsingData_Cookies")); - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, task_traits, base::BindOnce( &ClearCookies, context_getter_, @@ -336,7 +336,7 @@ IOSChromeIOThread* ios_chrome_io_thread = GetApplicationContext()->GetIOSChromeIOThread(); if (ios_chrome_io_thread) { - base::PostTaskWithTraitsAndReply( + base::PostTaskAndReply( FROM_HERE, task_traits, base::BindOnce(&IOSChromeIOThread::ClearHostCache, base::Unretained(ios_chrome_io_thread)), @@ -451,7 +451,7 @@ if (IsRemoveDataMaskSet(mask, BrowsingDataRemoveMask::REMOVE_CACHE)) { base::RecordAction(base::UserMetricsAction("ClearBrowsingData_Cache")); ClearHttpCache(context_getter_, - base::CreateSingleThreadTaskRunnerWithTraits(task_traits), + base::CreateSingleThreadTaskRunner(task_traits), delete_begin, delete_end, base::BindOnce(&NetCompletionCallbackAdapter, CreatePendingTaskCompletionClosure()));
diff --git a/ios/chrome/browser/browsing_data/cache_counter.cc b/ios/chrome/browser/browsing_data/cache_counter.cc index fadbec1e..20e4b21 100644 --- a/ios/chrome/browser/browsing_data/cache_counter.cc +++ b/ios/chrome/browser/browsing_data/cache_counter.cc
@@ -32,10 +32,9 @@ backend_(nullptr) {} void Count() { - base::PostTaskWithTraits( - FROM_HERE, {web::WebThread::IO}, - base::BindRepeating(&IOThreadCacheCounter::CountInternal, - base::Unretained(this), net::OK)); + base::PostTask(FROM_HERE, {web::WebThread::IO}, + base::BindRepeating(&IOThreadCacheCounter::CountInternal, + base::Unretained(this), net::OK)); } private: @@ -84,7 +83,7 @@ case STEP_CALLBACK: { result_ = rv; - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {web::WebThread::UI}, base::BindOnce(&IOThreadCacheCounter::OnCountingFinished, base::Unretained(this)));
diff --git a/ios/chrome/browser/browsing_data/cache_counter_unittest.cc b/ios/chrome/browser/browsing_data/cache_counter_unittest.cc index 9b52873d..764a918 100644 --- a/ios/chrome/browser/browsing_data/cache_counter_unittest.cc +++ b/ios/chrome/browser/browsing_data/cache_counter_unittest.cc
@@ -61,10 +61,9 @@ current_operation_ = OPERATION_ADD_ENTRY; next_step_ = STEP_GET_BACKEND; - base::PostTaskWithTraits( - FROM_HERE, {web::WebThread::IO}, - base::BindOnce(&CacheCounterTest::CacheOperationStep, - base::Unretained(this), net::OK)); + base::PostTask(FROM_HERE, {web::WebThread::IO}, + base::BindOnce(&CacheCounterTest::CacheOperationStep, + base::Unretained(this), net::OK)); WaitForIOThread(); } @@ -73,10 +72,9 @@ current_operation_ = OPERATION_CLEAR_CACHE; next_step_ = STEP_GET_BACKEND; - base::PostTaskWithTraits( - FROM_HERE, {web::WebThread::IO}, - base::BindOnce(&CacheCounterTest::CacheOperationStep, - base::Unretained(this), net::OK)); + base::PostTask(FROM_HERE, {web::WebThread::IO}, + base::BindOnce(&CacheCounterTest::CacheOperationStep, + base::Unretained(this), net::OK)); WaitForIOThread(); } @@ -196,9 +194,9 @@ if (current_operation_ == OPERATION_ADD_ENTRY) entry_->Close(); - base::PostTaskWithTraits(FROM_HERE, {web::WebThread::UI}, - base::BindOnce(&CacheCounterTest::Callback, - base::Unretained(this))); + base::PostTask(FROM_HERE, {web::WebThread::UI}, + base::BindOnce(&CacheCounterTest::Callback, + base::Unretained(this))); break; }
diff --git a/ios/chrome/browser/crash_report/breakpad_helper.mm b/ios/chrome/browser/crash_report/breakpad_helper.mm index 73054a7c..b30e3f8 100644 --- a/ios/chrome/browser/crash_report/breakpad_helper.mm +++ b/ios/chrome/browser/crash_report/breakpad_helper.mm
@@ -205,8 +205,9 @@ void CleanupCrashReports() { base::FilePath crash_directory; base::PathService::Get(ios::DIR_CRASH_DUMPS, &crash_directory); - base::PostTaskWithTraits( - FROM_HERE, {base::MayBlock(), base::TaskPriority::BEST_EFFORT}, + base::PostTask( + FROM_HERE, + {base::ThreadPool(), base::MayBlock(), base::TaskPriority::BEST_EFFORT}, base::BindOnce(&DeleteAllReportsInDirectory, crash_directory)); }
diff --git a/ios/chrome/browser/external_files/external_file_remover_impl.mm b/ios/chrome/browser/external_files/external_file_remover_impl.mm index 7860350..ec73ebe 100644 --- a/ios/chrome/browser/external_files/external_file_remover_impl.mm +++ b/ios/chrome/browser/external_files/external_file_remover_impl.mm
@@ -220,8 +220,9 @@ const NSInteger kMinimumAgeInDays = 30; NSInteger age_in_days = all_files ? 0 : kMinimumAgeInDays; - base::PostTaskWithTraitsAndReply( - FROM_HERE, {base::MayBlock(), base::TaskPriority::BEST_EFFORT}, + base::PostTaskAndReply( + FROM_HERE, + {base::ThreadPool(), base::MayBlock(), base::TaskPriority::BEST_EFFORT}, base::BindOnce(&RemoveFilesWithOptions, referenced_files, age_in_days), base::Bind(&RunCallback, base::Passed(&closure_runner))); }
diff --git a/ios/chrome/browser/ios_chrome_main_parts.mm b/ios/chrome/browser/ios_chrome_main_parts.mm index 96c5e58..f503a5cf 100644 --- a/ios/chrome/browser/ios_chrome_main_parts.mm +++ b/ios/chrome/browser/ios_chrome_main_parts.mm
@@ -100,8 +100,9 @@ // remaining BACKGROUND+BLOCK_SHUTDOWN tasks is bumped by the ThreadPool on // shutdown. scoped_refptr<base::SequencedTaskRunner> local_state_task_runner = - base::CreateSequencedTaskRunnerWithTraits( - {base::MayBlock(), base::TaskPriority::BEST_EFFORT, + base::CreateSequencedTaskRunner( + {base::ThreadPool(), base::MayBlock(), + base::TaskPriority::BEST_EFFORT, base::TaskShutdownBehavior::BLOCK_SHUTDOWN}); base::FilePath local_state_path; @@ -212,7 +213,7 @@ // This will be called after the command-line has been mutated by about:flags void IOSChromeMainParts::SetupFieldTrials() { base::SetRecordActionTaskRunner( - base::CreateSingleThreadTaskRunnerWithTraits({web::WebThread::UI})); + base::CreateSingleThreadTaskRunner({web::WebThread::UI})); // Initialize FieldTrialList to support FieldTrials that use one-time // randomization.
diff --git a/ios/chrome/browser/json_parser/in_process_json_parser.cc b/ios/chrome/browser/json_parser/in_process_json_parser.cc index 72e6be7..a7aca30 100644 --- a/ios/chrome/browser/json_parser/in_process_json_parser.cc +++ b/ios/chrome/browser/json_parser/in_process_json_parser.cc
@@ -41,8 +41,9 @@ void InProcessJsonParser::Parse(const std::string& unsafe_json, SuccessCallback success_callback, ErrorCallback error_callback) { - base::PostTaskWithTraits( - FROM_HERE, {base::MayBlock(), base::TaskPriority::BEST_EFFORT}, + base::PostTask( + FROM_HERE, + {base::ThreadPool(), base::MayBlock(), base::TaskPriority::BEST_EFFORT}, base::BindOnce(&ParseJsonOnBackgroundThread, base::ThreadTaskRunnerHandle::Get(), unsafe_json, std::move(success_callback), std::move(error_callback)));
diff --git a/ios/chrome/browser/ui/badges/badge_view_controller.h b/ios/chrome/browser/ui/badges/badge_view_controller.h index 33cb847..66175e15 100644 --- a/ios/chrome/browser/ui/badges/badge_view_controller.h +++ b/ios/chrome/browser/ui/badges/badge_view_controller.h
@@ -8,13 +8,15 @@ #import <UIKit/UIKit.h> #import "ios/chrome/browser/ui/badges/badge_consumer.h" +#import "ios/chrome/browser/ui/fullscreen/fullscreen_ui_element.h" @class BadgeButtonFactory; @protocol InfobarCommands; // Manages badges to display that are received through BadgeConsumer. Currently // only displays the newest badge. -@interface BadgeViewController : UIViewController <BadgeConsumer> +@interface BadgeViewController + : UIViewController <BadgeConsumer, FullscreenUIElement> // The dispatcher for badge button actions. @property(nonatomic, weak) id<InfobarCommands> dispatcher;
diff --git a/ios/chrome/browser/ui/badges/badge_view_controller.mm b/ios/chrome/browser/ui/badges/badge_view_controller.mm index b3b1e53d..89cdd92 100644 --- a/ios/chrome/browser/ui/badges/badge_view_controller.mm +++ b/ios/chrome/browser/ui/badges/badge_view_controller.mm
@@ -9,14 +9,13 @@ #import "ios/chrome/browser/ui/badges/badge_button_factory.h" #import "ios/chrome/browser/ui/badges/badge_item.h" #import "ios/chrome/browser/ui/elements/extended_touch_target_button.h" -#import "ios/chrome/browser/ui/fullscreen/fullscreen_ui_element.h" #import "ios/chrome/common/ui_util/constraints_ui_util.h" #if !defined(__has_feature) || !__has_feature(objc_arc) #error "This file requires ARC support." #endif -@interface BadgeViewController () <FullscreenUIElement> +@interface BadgeViewController () // Button factory. @property(nonatomic, strong) BadgeButtonFactory* buttonFactory;
diff --git a/ios/chrome/browser/ui/collection_view/BUILD.gn b/ios/chrome/browser/ui/collection_view/BUILD.gn index f7742d99..801b3829 100644 --- a/ios/chrome/browser/ui/collection_view/BUILD.gn +++ b/ios/chrome/browser/ui/collection_view/BUILD.gn
@@ -14,6 +14,7 @@ "//base", "//ios/chrome/browser/ui/list_model", "//ios/chrome/browser/ui/material_components", + "//ios/chrome/common/colors", ] public_deps = [ "//ios/chrome/browser/ui/collection_view/cells",
diff --git a/ios/chrome/browser/ui/collection_view/collection_view_controller.mm b/ios/chrome/browser/ui/collection_view/collection_view_controller.mm index db02aea..ddb4256 100644 --- a/ios/chrome/browser/ui/collection_view/collection_view_controller.mm +++ b/ios/chrome/browser/ui/collection_view/collection_view_controller.mm
@@ -11,6 +11,7 @@ #import "ios/chrome/browser/ui/collection_view/collection_view_model.h" #import "ios/chrome/browser/ui/material_components/chrome_app_bar_view_controller.h" #import "ios/chrome/browser/ui/material_components/utils.h" +#import "ios/chrome/common/colors/UIColor+cr_semantic_colors.h" #import "ios/third_party/material_components_ios/src/components/CollectionCells/src/MaterialCollectionCells.h" #if !defined(__has_feature) || !__has_feature(objc_arc) @@ -61,6 +62,9 @@ name:UIContentSizeCategoryDidChangeNotification object:nil]; } + + // Suport dark mode. + self.collectionView.backgroundColor = UIColor.cr_systemGroupedBackgroundColor; } - (void)contentSizeCategoryDidChange:(id)sender {
diff --git a/ios/chrome/browser/ui/location_bar/location_bar_coordinator.mm b/ios/chrome/browser/ui/location_bar/location_bar_coordinator.mm index b87a0ac..5505640 100644 --- a/ios/chrome/browser/ui/location_bar/location_bar_coordinator.mm +++ b/ios/chrome/browser/ui/location_bar/location_bar_coordinator.mm
@@ -76,6 +76,8 @@ std::unique_ptr<WebOmniboxEditControllerImpl> _editController; // Observer that updates |viewController| for fullscreen events. std::unique_ptr<FullscreenControllerObserver> _fullscreenObserver; + // Observer that updates BadgeViewController for fullscreen events. + std::unique_ptr<FullscreenControllerObserver> _fullscreenBadgeObserver; } // Whether the coordinator is started. @property(nonatomic, assign, getter=isStarted) BOOL started; @@ -83,6 +85,8 @@ @property(nonatomic, strong) OmniboxPopupCoordinator* omniboxPopupCoordinator; // Mediator for the badges displayed in the LocationBar. @property(nonatomic, strong) BadgeMediator* badgeMediator; +// ViewController for the badges displayed in the LocationBar. +@property(nonatomic, strong) BadgeViewController* badgeViewController; // Coordinator for the omnibox. @property(nonatomic, strong) OmniboxCoordinator* omniboxCoordinator; @property(nonatomic, strong) LocationBarMediator* mediator; @@ -164,14 +168,19 @@ // Create BadgeMediator and set the viewController as its consumer. if (IsInfobarUIRebootEnabled()) { - BadgeViewController* badgeViewController = - [[BadgeViewController alloc] init]; - [self.viewController addChildViewController:badgeViewController]; - [self.viewController setBadgeView:badgeViewController.view]; - [badgeViewController didMoveToParentViewController:self.viewController]; + self.badgeViewController = [[BadgeViewController alloc] init]; + [self.viewController addChildViewController:self.badgeViewController]; + [self.viewController setBadgeView:self.badgeViewController.view]; + [self.badgeViewController + didMoveToParentViewController:self.viewController]; self.badgeMediator = - [[BadgeMediator alloc] initWithConsumer:badgeViewController + [[BadgeMediator alloc] initWithConsumer:self.badgeViewController webStateList:self.webStateList]; + _fullscreenBadgeObserver = + std::make_unique<FullscreenUIUpdater>(self.badgeViewController); + FullscreenControllerFactory::GetInstance() + ->GetForBrowserState(self.browserState) + ->AddObserver(_fullscreenBadgeObserver.get()); } self.mediator = [[LocationBarMediator alloc] @@ -207,6 +216,11 @@ FullscreenControllerFactory::GetInstance() ->GetForBrowserState(self.browserState) ->RemoveObserver(_fullscreenObserver.get()); + if (IsInfobarUIRebootEnabled()) { + FullscreenControllerFactory::GetInstance() + ->GetForBrowserState(self.browserState) + ->RemoveObserver(_fullscreenBadgeObserver.get()); + } self.started = NO; }
diff --git a/ios/chrome/browser/ui/payments/BUILD.gn b/ios/chrome/browser/ui/payments/BUILD.gn index 9923339..405f349b 100644 --- a/ios/chrome/browser/ui/payments/BUILD.gn +++ b/ios/chrome/browser/ui/payments/BUILD.gn
@@ -89,6 +89,7 @@ "//ios/chrome/browser/ui/icons", "//ios/chrome/browser/ui/payments/cells", "//ios/chrome/browser/ui/util", + "//ios/chrome/common/colors", "//ios/third_party/material_roboto_font_loader_ios", "//ios/web/common", "//ios/web/public", @@ -168,6 +169,7 @@ "//ios/chrome/browser/ui/material_components", "//ios/chrome/browser/ui/payments/cells", "//ios/chrome/browser/ui/util", + "//ios/chrome/common/colors", "//ios/third_party/material_components_ios", "//third_party/libaddressinput:strings_grit", "//ui/base",
diff --git a/ios/chrome/browser/ui/payments/billing_address_selection_mediator.mm b/ios/chrome/browser/ui/payments/billing_address_selection_mediator.mm index 7ba787f..12cb1ad0 100644 --- a/ios/chrome/browser/ui/payments/billing_address_selection_mediator.mm +++ b/ios/chrome/browser/ui/payments/billing_address_selection_mediator.mm
@@ -12,10 +12,10 @@ #include "components/strings/grit/components_strings.h" #include "ios/chrome/browser/payments/payment_request.h" #import "ios/chrome/browser/payments/payment_request_util.h" -#import "ios/chrome/browser/ui/colors/MDCPalette+CrAdditions.h" #import "ios/chrome/browser/ui/payments/cells/autofill_profile_item.h" #import "ios/chrome/browser/ui/payments/cells/payments_text_item.h" #include "ios/chrome/browser/ui/util/uikit_ui_util.h" +#import "ios/chrome/common/colors/semantic_color_names.h" #include "ui/base/l10n/l10n_util.h" #if !defined(__has_feature) || !__has_feature(objc_arc) @@ -88,8 +88,9 @@ PaymentsTextItem* addButtonItem = [[PaymentsTextItem alloc] init]; addButtonItem.text = l10n_util::GetNSString(IDS_PAYMENTS_ADD_BILLING_ADDRESS_LABEL); - addButtonItem.trailingImage = TintImage([UIImage imageNamed:@"ic_add"], - [[MDCPalette greyPalette] tint400]); + addButtonItem.trailingImage = [[UIImage imageNamed:@"ic_add"] + imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate]; + addButtonItem.trailingImageTintColor = [UIColor colorNamed:kGrey400Color]; addButtonItem.cellType = PaymentsTextCellTypeCallToAction; return addButtonItem; }
diff --git a/ios/chrome/browser/ui/payments/cells/BUILD.gn b/ios/chrome/browser/ui/payments/cells/BUILD.gn index 4dbfeae..55fa8f6 100644 --- a/ios/chrome/browser/ui/payments/cells/BUILD.gn +++ b/ios/chrome/browser/ui/payments/cells/BUILD.gn
@@ -29,8 +29,8 @@ "//ios/chrome/browser/ui/collection_view/cells", "//ios/chrome/browser/ui/colors", "//ios/chrome/browser/ui/util", + "//ios/chrome/common/colors", "//ios/chrome/common/ui_util", - "//ios/third_party/material_components_ios", "//ios/third_party/material_roboto_font_loader_ios", "//url/", ] @@ -55,7 +55,6 @@ ":cells", "//ios/chrome/browser/ui/collection_view/cells", "//ios/chrome/browser/ui/collection_view/cells:test_support", - "//ios/third_party/material_components_ios", "//testing/gtest", ]
diff --git a/ios/chrome/browser/ui/payments/cells/accepted_payment_methods_item.mm b/ios/chrome/browser/ui/payments/cells/accepted_payment_methods_item.mm index 97427cb..cc2d5a3 100644 --- a/ios/chrome/browser/ui/payments/cells/accepted_payment_methods_item.mm +++ b/ios/chrome/browser/ui/payments/cells/accepted_payment_methods_item.mm
@@ -4,8 +4,8 @@ #import "ios/chrome/browser/ui/payments/cells/accepted_payment_methods_item.h" -#import "ios/chrome/browser/ui/colors/MDCPalette+CrAdditions.h" #import "ios/chrome/browser/ui/util/uikit_ui_util.h" +#import "ios/chrome/common/colors/semantic_color_names.h" #import "ios/third_party/material_components_ios/src/components/Typography/src/MaterialTypography.h" #if !defined(__has_feature) || !__has_feature(objc_arc) @@ -95,7 +95,7 @@ // Set default font and text colors for labels. - (void)setDefaultViewStyling { SetUILabelScaledFont(_messageLabel, [MDCTypography body2Font]); - _messageLabel.textColor = [[MDCPalette greyPalette] tint600]; + _messageLabel.textColor = [UIColor colorNamed:kTextSecondaryColor]; _messageLabel.numberOfLines = 0; _messageLabel.lineBreakMode = NSLineBreakByWordWrapping; }
diff --git a/ios/chrome/browser/ui/payments/cells/autofill_profile_item.mm b/ios/chrome/browser/ui/payments/cells/autofill_profile_item.mm index f69a1d1..7782425b 100644 --- a/ios/chrome/browser/ui/payments/cells/autofill_profile_item.mm +++ b/ios/chrome/browser/ui/payments/cells/autofill_profile_item.mm
@@ -5,9 +5,9 @@ #import "ios/chrome/browser/ui/payments/cells/autofill_profile_item.h" #import "ios/chrome/browser/ui/collection_view/cells/MDCCollectionViewCell+Chrome.h" -#import "ios/chrome/browser/ui/colors/MDCPalette+CrAdditions.h" #import "ios/chrome/browser/ui/payments/cells/accessibility_util.h" #include "ios/chrome/browser/ui/util/uikit_ui_util.h" +#import "ios/chrome/common/colors/semantic_color_names.h" #import "ios/chrome/common/ui_util/constraints_ui_util.h" #import "ios/third_party/material_components_ios/src/components/Typography/src/MaterialTypography.h" @@ -123,19 +123,19 @@ // Set default font and text colors for labels. - (void)setDefaultViewStyling { [self useScaledFont:NO]; - _nameLabel.textColor = [[MDCPalette greyPalette] tint900]; + _nameLabel.textColor = [UIColor colorNamed:kTextPrimaryColor]; _nameLabel.numberOfLines = 0; _nameLabel.lineBreakMode = NSLineBreakByWordWrapping; - _addressLabel.textColor = [[MDCPalette greyPalette] tint900]; + _addressLabel.textColor = [UIColor colorNamed:kTextPrimaryColor]; _addressLabel.numberOfLines = 0; _addressLabel.lineBreakMode = NSLineBreakByWordWrapping; - _phoneNumberLabel.textColor = [[MDCPalette greyPalette] tint900]; + _phoneNumberLabel.textColor = [UIColor colorNamed:kTextPrimaryColor]; - _emailLabel.textColor = [[MDCPalette greyPalette] tint900]; + _emailLabel.textColor = [UIColor colorNamed:kTextPrimaryColor]; - _notificationLabel.textColor = [[MDCPalette cr_bluePalette] tint500]; + _notificationLabel.textColor = [UIColor colorNamed:kBlueColor]; } - (void)useScaledFont:(BOOL)useScaledFont {
diff --git a/ios/chrome/browser/ui/payments/cells/page_info_item.mm b/ios/chrome/browser/ui/payments/cells/page_info_item.mm index 690e2c4..94e1e8c 100644 --- a/ios/chrome/browser/ui/payments/cells/page_info_item.mm +++ b/ios/chrome/browser/ui/payments/cells/page_info_item.mm
@@ -4,9 +4,9 @@ #import "ios/chrome/browser/ui/payments/cells/page_info_item.h" -#import "ios/chrome/browser/ui/colors/MDCPalette+CrAdditions.h" #import "ios/chrome/browser/ui/payments/cells/accessibility_util.h" #import "ios/chrome/browser/ui/util/uikit_ui_util.h" +#import "ios/chrome/common/colors/semantic_color_names.h" #include "ios/chrome/grit/ios_theme_resources.h" #import "ios/third_party/material_components_ios/src/components/Palettes/src/MaterialPalettes.h" #import "ios/third_party/material_components_ios/src/components/Typography/src/MaterialTypography.h" @@ -66,7 +66,7 @@ NSMutableAttributedString* text = [[NSMutableAttributedString alloc] initWithString:cell.pageHostLabel.text]; [text addAttribute:NSForegroundColorAttributeName - value:[[MDCPalette cr_greenPalette] tint700] + value:[UIColor colorNamed:kGreenColor] range:NSMakeRange(0, strlen(url::kHttpsScheme))]; // We need to set the font to the attributed portion, or the field doesn't // asjust with dynamic types. @@ -116,7 +116,7 @@ _pageTitleLabel = [[UILabel alloc] initWithFrame:CGRectZero]; SetUILabelScaledFont(_pageTitleLabel, [[MDCTypography fontLoader] mediumFontOfSize:12]); - _pageTitleLabel.textColor = [[MDCPalette greyPalette] tint900]; + _pageTitleLabel.textColor = [UIColor colorNamed:kTextPrimaryColor]; _pageTitleLabel.backgroundColor = [UIColor clearColor]; _pageTitleLabel.translatesAutoresizingMaskIntoConstraints = NO; [self.contentView addSubview:_pageTitleLabel]; @@ -125,7 +125,7 @@ _pageHostLabel = [[UILabel alloc] initWithFrame:CGRectZero]; SetUILabelScaledFont(_pageHostLabel, [[MDCTypography fontLoader] regularFontOfSize:12]); - _pageHostLabel.textColor = [[MDCPalette greyPalette] tint600]; + _pageHostLabel.textColor = [UIColor colorNamed:kTextSecondaryColor]; // Truncate host name from the leading side if it is too long. This is // according to Eliding Origin Names and Hostnames guideline found here: // https://www.chromium.org/Home/chromium-security/enamel#TOC-Presenting-Origins @@ -146,8 +146,7 @@ _pageLockIndicatorView.accessibilityIdentifier = kPageInfoLockIndicatorImageViewID; _pageLockIndicatorView.contentMode = UIViewContentModeScaleAspectFit; - [_pageLockIndicatorView - setTintColor:[[MDCPalette cr_greenPalette] tint700]]; + [_pageLockIndicatorView setTintColor:[UIColor colorNamed:kGreenColor]]; [self.contentView addSubview:_pageLockIndicatorView]; // Layout
diff --git a/ios/chrome/browser/ui/payments/cells/payment_method_item.mm b/ios/chrome/browser/ui/payments/cells/payment_method_item.mm index 0086511..e0eaea89 100644 --- a/ios/chrome/browser/ui/payments/cells/payment_method_item.mm +++ b/ios/chrome/browser/ui/payments/cells/payment_method_item.mm
@@ -5,9 +5,9 @@ #import "ios/chrome/browser/ui/payments/cells/payment_method_item.h" #import "ios/chrome/browser/ui/collection_view/cells/MDCCollectionViewCell+Chrome.h" -#import "ios/chrome/browser/ui/colors/MDCPalette+CrAdditions.h" #import "ios/chrome/browser/ui/payments/cells/accessibility_util.h" #include "ios/chrome/browser/ui/util/uikit_ui_util.h" +#import "ios/chrome/common/colors/semantic_color_names.h" #import "ios/third_party/material_components_ios/src/components/Typography/src/MaterialTypography.h" #if !defined(__has_feature) || !__has_feature(objc_arc) @@ -92,25 +92,25 @@ // Method ID. _methodIDLabel = [[UILabel alloc] initWithFrame:CGRectZero]; SetUILabelScaledFont(_methodIDLabel, [MDCTypography body2Font]); - _methodIDLabel.textColor = [[MDCPalette greyPalette] tint900]; + _methodIDLabel.textColor = [UIColor colorNamed:kTextPrimaryColor]; [_stackView addArrangedSubview:_methodIDLabel]; // Method detail. _methodDetailLabel = [[UILabel alloc] initWithFrame:CGRectZero]; SetUILabelScaledFont(_methodDetailLabel, [MDCTypography body1Font]); - _methodDetailLabel.textColor = [[MDCPalette greyPalette] tint900]; + _methodDetailLabel.textColor = [UIColor colorNamed:kTextPrimaryColor]; [_stackView addArrangedSubview:_methodDetailLabel]; // Method address. _methodAddressLabel = [[UILabel alloc] initWithFrame:CGRectZero]; SetUILabelScaledFont(_methodAddressLabel, [MDCTypography body1Font]); - _methodAddressLabel.textColor = [[MDCPalette greyPalette] tint900]; + _methodAddressLabel.textColor = [UIColor colorNamed:kTextPrimaryColor]; [_stackView addArrangedSubview:_methodAddressLabel]; // Notification label. _notificationLabel = [[UILabel alloc] initWithFrame:CGRectZero]; SetUILabelScaledFont(_notificationLabel, [MDCTypography body1Font]); - _notificationLabel.textColor = [[MDCPalette cr_bluePalette] tint500]; + _notificationLabel.textColor = [UIColor colorNamed:kBlueColor]; [_stackView addArrangedSubview:_notificationLabel]; // Method type icon.
diff --git a/ios/chrome/browser/ui/payments/cells/payments_selector_edit_item.mm b/ios/chrome/browser/ui/payments/cells/payments_selector_edit_item.mm index 763697c..c54cf71 100644 --- a/ios/chrome/browser/ui/payments/cells/payments_selector_edit_item.mm +++ b/ios/chrome/browser/ui/payments/cells/payments_selector_edit_item.mm
@@ -7,7 +7,7 @@ #include <algorithm> #import "ios/chrome/browser/ui/collection_view/cells/MDCCollectionViewCell+Chrome.h" -#import "ios/chrome/browser/ui/colors/MDCPalette+CrAdditions.h" +#import "ios/chrome/common/colors/semantic_color_names.h" #import "ios/third_party/material_components_ios/src/components/Typography/src/MaterialTypography.h" #if !defined(__has_feature) || !__has_feature(objc_arc) @@ -60,7 +60,7 @@ - (UIColor*)nameColor { if (!_nameColor) { - _nameColor = [[MDCPalette greyPalette] tint900]; + _nameColor = [UIColor colorNamed:kTextPrimaryColor]; } return _nameColor; } @@ -75,7 +75,7 @@ - (UIColor*)valueColor { if (!_valueColor) { - _valueColor = [[MDCPalette greyPalette] tint500]; + _valueColor = [UIColor colorNamed:kTextSecondaryColor]; } return _valueColor; } @@ -122,7 +122,7 @@ [contentView addSubview:_textLabel]; _textLabel.font = [[MDCTypography fontLoader] mediumFontOfSize:14]; - _textLabel.textColor = [[MDCPalette greyPalette] tint900]; + _textLabel.textColor = [UIColor colorNamed:kTextPrimaryColor]; _detailTextLabel = [[UILabel alloc] init]; _detailTextLabel.translatesAutoresizingMaskIntoConstraints = NO; @@ -130,7 +130,7 @@ [contentView addSubview:_detailTextLabel]; _detailTextLabel.font = [[MDCTypography fontLoader] regularFontOfSize:14]; - _detailTextLabel.textColor = [[MDCPalette greyPalette] tint500]; + _detailTextLabel.textColor = [UIColor colorNamed:kTextSecondaryColor]; // Set up the width constraints. They are activated here and updated in // layoutSubviews.
diff --git a/ios/chrome/browser/ui/payments/cells/payments_text_item.h b/ios/chrome/browser/ui/payments/cells/payments_text_item.h index ea12c1be..e662485f 100644 --- a/ios/chrome/browser/ui/payments/cells/payments_text_item.h +++ b/ios/chrome/browser/ui/payments/cells/payments_text_item.h
@@ -28,12 +28,10 @@ // The secondary text to display. @property(nonatomic, nullable, copy) NSString* detailText; -// The color of the main text. Default is the 900 tint color of the grey -// palette. +// The color of the main text. @property(nonatomic, null_resettable, copy) UIColor* textColor; -// The color of the secondary text. Default is the 900 tint color of the grey -// palette. +// The color of the secondary text. @property(nonatomic, null_resettable, copy) UIColor* detailTextColor; // The leading image to display. @@ -42,6 +40,9 @@ // The trailing image to display. @property(nonatomic, nullable, strong) UIImage* trailingImage; +// The tint color for the trailing image. +@property(nonatomic, nullable, strong) UIColor* trailingImageTintColor; + // The accessory type for the represented cell. @property(nonatomic) MDCCollectionViewCellAccessoryType accessoryType;
diff --git a/ios/chrome/browser/ui/payments/cells/payments_text_item.mm b/ios/chrome/browser/ui/payments/cells/payments_text_item.mm index dfdb7a08..7d4110801 100644 --- a/ios/chrome/browser/ui/payments/cells/payments_text_item.mm +++ b/ios/chrome/browser/ui/payments/cells/payments_text_item.mm
@@ -8,6 +8,7 @@ #import "ios/chrome/browser/ui/payments/cells/accessibility_util.h" #import "ios/chrome/browser/ui/util/rtl_geometry.h" #include "ios/chrome/browser/ui/util/uikit_ui_util.h" +#import "ios/chrome/common/colors/semantic_color_names.h" #import "ios/third_party/material_components_ios/src/components/Palettes/src/MaterialPalettes.h" #import "ios/third_party/material_components_ios/src/components/Typography/src/MaterialTypography.h" @@ -31,15 +32,7 @@ @implementation PaymentsTextItem -@synthesize text = _text; -@synthesize detailText = _detailText; -@synthesize textColor = _textColor; -@synthesize detailTextColor = _detailTextColor; -@synthesize leadingImage = _leadingImage; -@synthesize trailingImage = _trailingImage; -@synthesize accessoryType = _accessoryType; @synthesize complete = _complete; -@synthesize cellType = _cellType; #pragma mark CollectionViewItem @@ -53,14 +46,14 @@ - (UIColor*)textColor { if (!_textColor) { - _textColor = [[MDCPalette greyPalette] tint900]; + _textColor = [UIColor colorNamed:kTextPrimaryColor]; } return _textColor; } - (UIColor*)detailTextColor { if (!_detailTextColor) { - _detailTextColor = [[MDCPalette greyPalette] tint900]; + _detailTextColor = [UIColor colorNamed:kTextPrimaryColor]; } return _detailTextColor; } @@ -74,6 +67,7 @@ cell.detailTextLabel.textColor = self.detailTextColor; cell.leadingImageView.image = self.leadingImage; cell.trailingImageView.image = self.trailingImage; + cell.trailingImageView.tintColor = self.trailingImageTintColor; cell.cellType = self.cellType; } @@ -248,6 +242,7 @@ self.detailTextLabel.text = nil; self.leadingImageView.image = nil; self.trailingImageView.image = nil; + self.trailingImageView.tintColor = nil; self.cellType = PaymentsTextCellTypeNormal; }
diff --git a/ios/chrome/browser/ui/payments/cells/price_item.mm b/ios/chrome/browser/ui/payments/cells/price_item.mm index 1b9b087c..68ffff7 100644 --- a/ios/chrome/browser/ui/payments/cells/price_item.mm +++ b/ios/chrome/browser/ui/payments/cells/price_item.mm
@@ -7,9 +7,9 @@ #include <algorithm> #import "ios/chrome/browser/ui/collection_view/cells/MDCCollectionViewCell+Chrome.h" -#import "ios/chrome/browser/ui/colors/MDCPalette+CrAdditions.h" #import "ios/chrome/browser/ui/payments/cells/accessibility_util.h" #include "ios/chrome/browser/ui/util/uikit_ui_util.h" +#import "ios/chrome/common/colors/semantic_color_names.h" #import "ios/third_party/material_components_ios/src/components/Typography/src/MaterialTypography.h" #if !defined(__has_feature) || !__has_feature(objc_arc) @@ -99,13 +99,12 @@ // Set default font and text colors for labels. - (void)setDefaultViewStyling { SetUILabelScaledFont(_itemLabel, [MDCTypography body2Font]); - _itemLabel.textColor = [[MDCPalette greyPalette] tint900]; + _itemLabel.textColor = [UIColor colorNamed:kTextPrimaryColor]; SetUILabelScaledFont(_notificationLabel, [MDCTypography body2Font]); - _notificationLabel.textColor = [[MDCPalette greenPalette] tint800]; - + _notificationLabel.textColor = [UIColor colorNamed:kGreenColor]; SetUILabelScaledFont(_priceLabel, [MDCTypography body1Font]); - _priceLabel.textColor = [[MDCPalette greyPalette] tint900]; + _priceLabel.textColor = [UIColor colorNamed:kTextPrimaryColor]; } // Set constraints on subviews.
diff --git a/ios/chrome/browser/ui/payments/contact_info_selection_mediator.mm b/ios/chrome/browser/ui/payments/contact_info_selection_mediator.mm index 4f50a5b9..54859e75 100644 --- a/ios/chrome/browser/ui/payments/contact_info_selection_mediator.mm +++ b/ios/chrome/browser/ui/payments/contact_info_selection_mediator.mm
@@ -12,10 +12,10 @@ #include "components/strings/grit/components_strings.h" #include "ios/chrome/browser/payments/payment_request.h" #import "ios/chrome/browser/payments/payment_request_util.h" -#import "ios/chrome/browser/ui/colors/MDCPalette+CrAdditions.h" #import "ios/chrome/browser/ui/payments/cells/autofill_profile_item.h" #import "ios/chrome/browser/ui/payments/cells/payments_text_item.h" #include "ios/chrome/browser/ui/util/uikit_ui_util.h" +#import "ios/chrome/common/colors/semantic_color_names.h" #include "ui/base/l10n/l10n_util.h" #if !defined(__has_feature) || !__has_feature(objc_arc) @@ -80,8 +80,9 @@ PaymentsTextItem* addButtonItem = [[PaymentsTextItem alloc] init]; addButtonItem.text = l10n_util::GetNSString(IDS_PAYMENTS_ADD_CONTACT_DETAILS_LABEL); - addButtonItem.trailingImage = TintImage([UIImage imageNamed:@"ic_add"], - [[MDCPalette greyPalette] tint400]); + addButtonItem.trailingImage = [[UIImage imageNamed:@"ic_add"] + imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate]; + addButtonItem.trailingImageTintColor = [UIColor colorNamed:kGrey400Color]; addButtonItem.cellType = PaymentsTextCellTypeCallToAction; return addButtonItem; }
diff --git a/ios/chrome/browser/ui/payments/payment_items_display_view_controller.mm b/ios/chrome/browser/ui/payments/payment_items_display_view_controller.mm index 6aeb484..0431450 100644 --- a/ios/chrome/browser/ui/payments/payment_items_display_view_controller.mm +++ b/ios/chrome/browser/ui/payments/payment_items_display_view_controller.mm
@@ -9,13 +9,13 @@ #import "ios/chrome/browser/ui/collection_view/cells/MDCCollectionViewCell+Chrome.h" #import "ios/chrome/browser/ui/collection_view/cells/collection_view_item.h" #import "ios/chrome/browser/ui/collection_view/collection_view_model.h" -#import "ios/chrome/browser/ui/colors/MDCPalette+CrAdditions.h" #import "ios/chrome/browser/ui/icons/chrome_icon.h" #import "ios/chrome/browser/ui/list_model/list_item+Controller.h" #import "ios/chrome/browser/ui/payments/cells/price_item.h" #import "ios/chrome/browser/ui/payments/payment_items_display_view_controller_actions.h" #include "ios/chrome/browser/ui/util/rtl_geometry.h" #include "ios/chrome/browser/ui/util/uikit_ui_util.h" +#import "ios/chrome/common/colors/semantic_color_names.h" #include "ios/chrome/grit/ios_strings.h" #import "ios/third_party/material_components_ios/src/components/Buttons/src/MaterialButtons.h" #import "ios/third_party/material_components_ios/src/components/Typography/src/MaterialTypography.h" @@ -76,12 +76,12 @@ _payButton = [[MDCButton alloc] init]; [_payButton setTitle:l10n_util::GetNSString(IDS_PAYMENTS_PAY_BUTTON) forState:UIControlStateNormal]; - [_payButton setBackgroundColor:[[MDCPalette cr_bluePalette] tint500]]; - [_payButton setTitleColor:[UIColor whiteColor] + [_payButton setBackgroundColor:[UIColor colorNamed:kBlueColor]]; + [_payButton setTitleColor:[UIColor colorNamed:kSolidButtonTextColor] forState:UIControlStateNormal]; - [_payButton setTitleColor:[UIColor whiteColor] + [_payButton setTitleColor:[UIColor colorNamed:kSolidButtonTextColor] forState:UIControlStateDisabled]; - [_payButton setInkColor:[UIColor colorWithWhite:1 alpha:0.2]]; + [_payButton setInkColor:[UIColor colorNamed:kMDCInkColor]]; [_payButton addTarget:self action:@selector(onConfirm) forControlEvents:UIControlEventTouchUpInside];
diff --git a/ios/chrome/browser/ui/payments/payment_method_selection_mediator.mm b/ios/chrome/browser/ui/payments/payment_method_selection_mediator.mm index f891de6..a30734d 100644 --- a/ios/chrome/browser/ui/payments/payment_method_selection_mediator.mm +++ b/ios/chrome/browser/ui/payments/payment_method_selection_mediator.mm
@@ -18,10 +18,10 @@ #include "ios/chrome/browser/payments/ios_payment_instrument.h" #include "ios/chrome/browser/payments/payment_request.h" #include "ios/chrome/browser/payments/payment_request_util.h" -#import "ios/chrome/browser/ui/colors/MDCPalette+CrAdditions.h" #import "ios/chrome/browser/ui/payments/cells/payment_method_item.h" #import "ios/chrome/browser/ui/payments/cells/payments_text_item.h" #include "ios/chrome/browser/ui/util/uikit_ui_util.h" +#import "ios/chrome/common/colors/semantic_color_names.h" #include "ui/base/l10n/l10n_util.h" #if !defined(__has_feature) || !__has_feature(objc_arc) @@ -92,8 +92,9 @@ - (CollectionViewItem*)addButtonItem { PaymentsTextItem* addButtonItem = [[PaymentsTextItem alloc] init]; addButtonItem.text = l10n_util::GetNSString(IDS_PAYMENTS_ADD_CARD); - addButtonItem.trailingImage = TintImage([UIImage imageNamed:@"ic_add"], - [[MDCPalette greyPalette] tint400]); + addButtonItem.trailingImage = [[UIImage imageNamed:@"ic_add"] + imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate]; + addButtonItem.trailingImageTintColor = [UIColor colorNamed:kGrey400Color]; addButtonItem.cellType = PaymentsTextCellTypeCallToAction; return addButtonItem; }
diff --git a/ios/chrome/browser/ui/payments/payment_request_edit_view_controller.mm b/ios/chrome/browser/ui/payments/payment_request_edit_view_controller.mm index 5f4c428..1195fc1 100644 --- a/ios/chrome/browser/ui/payments/payment_request_edit_view_controller.mm +++ b/ios/chrome/browser/ui/payments/payment_request_edit_view_controller.mm
@@ -13,13 +13,13 @@ #import "ios/chrome/browser/ui/collection_view/cells/MDCCollectionViewCell+Chrome.h" #import "ios/chrome/browser/ui/collection_view/cells/collection_view_footer_item.h" #import "ios/chrome/browser/ui/collection_view/cells/collection_view_switch_item.h" -#import "ios/chrome/browser/ui/colors/MDCPalette+CrAdditions.h" #import "ios/chrome/browser/ui/list_model/list_item+Controller.h" #import "ios/chrome/browser/ui/payments/cells/payments_selector_edit_item.h" #import "ios/chrome/browser/ui/payments/cells/payments_text_item.h" #import "ios/chrome/browser/ui/payments/payment_request_edit_view_controller_actions.h" #import "ios/chrome/browser/ui/payments/payment_request_editor_field.h" #import "ios/chrome/browser/ui/util/uikit_ui_util.h" +#import "ios/chrome/common/colors/semantic_color_names.h" #include "ios/chrome/grit/ios_theme_resources.h" #import "ios/third_party/material_components_ios/src/components/Typography/src/MaterialTypography.h" #include "ui/base/l10n/l10n_util.h" @@ -198,7 +198,7 @@ target:self action:@selector(didCancel)]; [cancelButton setTitleTextAttributes:@{ - NSForegroundColorAttributeName : [UIColor lightGrayColor] + NSForegroundColorAttributeName : [UIColor colorNamed:kDisabledTintColor] } forState:UIControlStateDisabled]; [cancelButton @@ -212,7 +212,7 @@ target:nil action:@selector(didSave)]; [saveButton setTitleTextAttributes:@{ - NSForegroundColorAttributeName : [UIColor lightGrayColor] + NSForegroundColorAttributeName : [UIColor colorNamed:kDisabledTintColor] } forState:UIControlStateDisabled]; [saveButton setAccessibilityLabel:l10n_util::GetNSString(IDS_ACCNAME_SAVE)]; @@ -609,11 +609,11 @@ autofillEditCell.textField.clearButtonMode = UITextFieldViewModeNever; SetUILabelScaledFont(autofillEditCell.textLabel, [MDCTypography body2Font]); - autofillEditCell.textLabel.textColor = [[MDCPalette greyPalette] tint900]; + autofillEditCell.textLabel.textColor = + [UIColor colorNamed:kTextPrimaryColor]; SetUITextFieldScaledFont(autofillEditCell.textField, [MDCTypography body1Font]); - autofillEditCell.textField.textColor = - [[MDCPalette cr_bluePalette] tint500]; + autofillEditCell.textField.textColor = [UIColor colorNamed:kBlueColor]; break; } case ItemTypeSwitchField: { @@ -629,15 +629,14 @@ base::mac::ObjCCastStrict<PaymentsTextCell>(cell); SetUILabelScaledFont(errorMessageCell.textLabel, [MDCTypography body1Font]); - errorMessageCell.textLabel.textColor = - [[MDCPalette cr_redPalette] tint600]; + errorMessageCell.textLabel.textColor = [UIColor colorNamed:kRedColor]; break; } case ItemTypeFooter: { CollectionViewFooterCell* footerCell = base::mac::ObjCCastStrict<CollectionViewFooterCell>(cell); SetUILabelScaledFont(footerCell.textLabel, [MDCTypography body2Font]); - footerCell.textLabel.textColor = [[MDCPalette greyPalette] tint600]; + footerCell.textLabel.textColor = [UIColor colorNamed:kTextSecondaryColor]; footerCell.textLabel.shadowColor = nil; // No shadow. footerCell.horizontalPadding = kFooterCellHorizontalPadding; break;
diff --git a/ios/chrome/browser/ui/payments/payment_request_error_view_controller.mm b/ios/chrome/browser/ui/payments/payment_request_error_view_controller.mm index c092b6a2..eb73da40 100644 --- a/ios/chrome/browser/ui/payments/payment_request_error_view_controller.mm +++ b/ios/chrome/browser/ui/payments/payment_request_error_view_controller.mm
@@ -9,9 +9,9 @@ #import "ios/chrome/browser/ui/collection_view/cells/MDCCollectionViewCell+Chrome.h" #import "ios/chrome/browser/ui/collection_view/cells/collection_view_item.h" #import "ios/chrome/browser/ui/collection_view/collection_view_model.h" -#import "ios/chrome/browser/ui/colors/MDCPalette+CrAdditions.h" #import "ios/chrome/browser/ui/payments/cells/payments_text_item.h" #import "ios/chrome/browser/ui/payments/payment_request_error_view_controller_actions.h" +#import "ios/chrome/common/colors/semantic_color_names.h" #include "ios/chrome/grit/ios_strings.h" #import "ios/third_party/material_components_ios/src/components/Buttons/src/MaterialButtons.h" #include "ui/base/l10n/l10n_util.h" @@ -62,7 +62,7 @@ target:self action:@selector(onOk)]; [_okButton setTitleTextAttributes:@{ - NSForegroundColorAttributeName : [UIColor lightGrayColor] + NSForegroundColorAttributeName : [UIColor colorNamed:kDisabledTintColor] } forState:UIControlStateDisabled]; [_okButton setAccessibilityLabel:l10n_util::GetNSString(IDS_ACCNAME_OK)]; @@ -114,7 +114,8 @@ case ItemTypeMessage: { PaymentsTextCell* messageCell = base::mac::ObjCCastStrict<PaymentsTextCell>(cell); - messageCell.textLabel.textColor = [[MDCPalette greyPalette] tint600]; + messageCell.textLabel.textColor = + [UIColor colorNamed:kTextSecondaryColor]; break; } default:
diff --git a/ios/chrome/browser/ui/payments/payment_request_mediator.mm b/ios/chrome/browser/ui/payments/payment_request_mediator.mm index f27e8cc4..22636370 100644 --- a/ios/chrome/browser/ui/payments/payment_request_mediator.mm +++ b/ios/chrome/browser/ui/payments/payment_request_mediator.mm
@@ -25,12 +25,12 @@ #import "ios/chrome/browser/payments/payment_request_util.h" #import "ios/chrome/browser/ui/collection_view/cells/collection_view_footer_item.h" #import "ios/chrome/browser/ui/collection_view/cells/collection_view_item.h" -#import "ios/chrome/browser/ui/colors/MDCPalette+CrAdditions.h" #import "ios/chrome/browser/ui/payments/cells/autofill_profile_item.h" #import "ios/chrome/browser/ui/payments/cells/payment_method_item.h" #import "ios/chrome/browser/ui/payments/cells/payments_text_item.h" #import "ios/chrome/browser/ui/payments/cells/price_item.h" #include "ios/chrome/browser/ui/util/uikit_ui_util.h" +#import "ios/chrome/common/colors/semantic_color_names.h" #include "ui/base/l10n/l10n_util.h" #include "ui/base/resource/resource_bundle.h" @@ -142,8 +142,9 @@ if (self.paymentRequest->shipping_profiles().empty()) { item.text = base::SysUTF16ToNSString( GetAddShippingAddressButtonLabel(self.paymentRequest->shipping_type())); - item.trailingImage = TintImage([UIImage imageNamed:@"ic_add"], - [[MDCPalette greyPalette] tint400]); + item.trailingImage = [[UIImage imageNamed:@"ic_add"] + imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate]; + item.trailingImageTintColor = [UIColor colorNamed:kGrey400Color]; } else { item.text = base::SysUTF16ToNSString(GetChooseShippingAddressButtonLabel( self.paymentRequest->shipping_type())); @@ -221,8 +222,9 @@ PaymentsTextItem* item = [[PaymentsTextItem alloc] init]; if (self.paymentRequest->payment_methods().empty()) { item.text = l10n_util::GetNSString(IDS_ADD_PAYMENT_METHOD); - item.trailingImage = TintImage([UIImage imageNamed:@"ic_add"], - [[MDCPalette greyPalette] tint400]); + item.trailingImage = [[UIImage imageNamed:@"ic_add"] + imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate]; + item.trailingImageTintColor = [UIColor colorNamed:kGrey400Color]; } else { item.text = l10n_util::GetNSString(IDS_CHOOSE_PAYMENT_METHOD); item.accessoryType = MDCCollectionViewCellAccessoryDisclosureIndicator; @@ -263,8 +265,9 @@ PaymentsTextItem* item = [[PaymentsTextItem alloc] init]; if (self.paymentRequest->contact_profiles().empty()) { item.text = l10n_util::GetNSString(IDS_PAYMENT_REQUEST_ADD_CONTACT_INFO); - item.trailingImage = TintImage([UIImage imageNamed:@"ic_add"], - [[MDCPalette greyPalette] tint400]); + item.trailingImage = [[UIImage imageNamed:@"ic_add"] + imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate]; + item.trailingImageTintColor = [UIColor colorNamed:kGrey400Color]; } else { item.text = l10n_util::GetNSString(IDS_PAYMENT_REQUEST_CHOOSE_CONTACT_INFO); item.accessoryType = MDCCollectionViewCellAccessoryDisclosureIndicator;
diff --git a/ios/chrome/browser/ui/payments/payment_request_selector_view_controller.mm b/ios/chrome/browser/ui/payments/payment_request_selector_view_controller.mm index 1b87d9a..f97f4f1 100644 --- a/ios/chrome/browser/ui/payments/payment_request_selector_view_controller.mm +++ b/ios/chrome/browser/ui/payments/payment_request_selector_view_controller.mm
@@ -10,13 +10,13 @@ #import "ios/chrome/browser/ui/collection_view/cells/MDCCollectionViewCell+Chrome.h" #import "ios/chrome/browser/ui/collection_view/cells/collection_view_item.h" #import "ios/chrome/browser/ui/collection_view/collection_view_model.h" -#import "ios/chrome/browser/ui/colors/MDCPalette+CrAdditions.h" #import "ios/chrome/browser/ui/icons/chrome_icon.h" #import "ios/chrome/browser/ui/list_model/list_item+Controller.h" #import "ios/chrome/browser/ui/payments/cells/payments_is_selectable.h" #import "ios/chrome/browser/ui/payments/cells/payments_text_item.h" #import "ios/chrome/browser/ui/payments/payment_request_selector_view_controller_actions.h" #import "ios/chrome/browser/ui/payments/payment_request_selector_view_controller_data_source.h" +#import "ios/chrome/common/colors/semantic_color_names.h" #include "ios/chrome/grit/ios_strings.h" #import "ios/third_party/material_components_ios/src/components/Typography/src/MaterialTypography.h" #include "ui/base/l10n/l10n_util.h" @@ -205,8 +205,8 @@ base::mac::ObjCCastStrict<PaymentsTextCell>(cell); textCell.textLabel.textColor = self.dataSource.state == PaymentRequestSelectorStateError - ? [[MDCPalette cr_redPalette] tint600] - : [[MDCPalette greyPalette] tint600]; + ? [UIColor colorNamed:kRedColor] + : [UIColor colorNamed:kTextSecondaryColor]; } break; } @@ -217,7 +217,7 @@ // Style call to action cells. if (paymentsTextCell.cellType == PaymentsTextCellTypeCallToAction) { paymentsTextCell.textLabel.textColor = - [[MDCPalette cr_bluePalette] tint500]; + [UIColor colorNamed:kBlueColor]; } } break;
diff --git a/ios/chrome/browser/ui/payments/payment_request_view_controller.mm b/ios/chrome/browser/ui/payments/payment_request_view_controller.mm index 995e612c..f0e8e15 100644 --- a/ios/chrome/browser/ui/payments/payment_request_view_controller.mm +++ b/ios/chrome/browser/ui/payments/payment_request_view_controller.mm
@@ -12,7 +12,6 @@ #import "ios/chrome/browser/ui/collection_view/cells/collection_view_footer_item.h" #import "ios/chrome/browser/ui/collection_view/cells/collection_view_item.h" #import "ios/chrome/browser/ui/collection_view/collection_view_model.h" -#import "ios/chrome/browser/ui/colors/MDCPalette+CrAdditions.h" #import "ios/chrome/browser/ui/list_model/list_item+Controller.h" #import "ios/chrome/browser/ui/payments/cells/page_info_item.h" #import "ios/chrome/browser/ui/payments/cells/payments_text_item.h" @@ -20,6 +19,7 @@ #import "ios/chrome/browser/ui/payments/payment_request_view_controller_actions.h" #include "ios/chrome/browser/ui/util/rtl_geometry.h" #include "ios/chrome/browser/ui/util/uikit_ui_util.h" +#import "ios/chrome/common/colors/semantic_color_names.h" #include "ios/chrome/grit/ios_strings.h" #import "ios/third_party/material_components_ios/src/components/Buttons/src/MaterialButtons.h" #import "ios/third_party/material_components_ios/src/components/Typography/src/MaterialTypography.h" @@ -94,7 +94,7 @@ target:nil action:@selector(onCancel)]; [_cancelButton setTitleTextAttributes:@{ - NSForegroundColorAttributeName : [UIColor lightGrayColor] + NSForegroundColorAttributeName : [UIColor colorNamed:kDisabledTintColor] } forState:UIControlStateDisabled]; [_cancelButton @@ -105,12 +105,12 @@ _payButton = [[MDCButton alloc] init]; [_payButton setTitle:l10n_util::GetNSString(IDS_PAYMENTS_PAY_BUTTON) forState:UIControlStateNormal]; - [_payButton setBackgroundColor:[[MDCPalette cr_bluePalette] tint500]]; - [_payButton setTitleColor:[UIColor whiteColor] + [_payButton setBackgroundColor:[UIColor colorNamed:kBlueColor]]; + [_payButton setTitleColor:[UIColor colorNamed:kSolidButtonTextColor] forState:UIControlStateNormal]; - [_payButton setTitleColor:[UIColor whiteColor] + [_payButton setTitleColor:[UIColor colorNamed:kSolidButtonTextColor] forState:UIControlStateDisabled]; - [_payButton setInkColor:[UIColor colorWithWhite:1 alpha:0.2]]; + [_payButton setInkColor:[UIColor colorNamed:kMDCInkColor]]; [_payButton addTarget:self action:@selector(onConfirm) forControlEvents:UIControlEventTouchUpInside]; @@ -202,7 +202,8 @@ PaymentsTextItem* shippingSectionHeaderItem = [_dataSource shippingSectionHeaderItem]; - [shippingSectionHeaderItem setTextColor:[[MDCPalette greyPalette] tint500]]; + [shippingSectionHeaderItem + setTextColor:[UIColor colorNamed:kTextSecondaryColor]]; [shippingSectionHeaderItem setType:ItemTypeShippingHeader]; [model setHeader:shippingSectionHeaderItem forSectionWithIdentifier:SectionIdentifierShipping]; @@ -329,7 +330,7 @@ // Style call to action cells. if (paymentsTextCell.cellType == PaymentsTextCellTypeCallToAction) { paymentsTextCell.textLabel.textColor = - [[MDCPalette cr_bluePalette] tint500]; + [UIColor colorNamed:kBlueColor]; } } break; @@ -338,7 +339,7 @@ CollectionViewFooterCell* footerCell = base::mac::ObjCCastStrict<CollectionViewFooterCell>(cell); SetUILabelScaledFont(footerCell.textLabel, [MDCTypography body2Font]); - footerCell.textLabel.textColor = [[MDCPalette greyPalette] tint600]; + footerCell.textLabel.textColor = [UIColor colorNamed:kTextSecondaryColor]; footerCell.textLabel.shadowColor = nil; // No shadow. footerCell.horizontalPadding = kFooterCellHorizontalPadding; break; @@ -503,7 +504,7 @@ if (paymentMethodSectionHeaderItem) { [paymentMethodSectionHeaderItem setType:ItemTypePaymentHeader]; [paymentMethodSectionHeaderItem - setTextColor:[[MDCPalette greyPalette] tint500]]; + setTextColor:[UIColor colorNamed:kTextSecondaryColor]]; [model setHeader:paymentMethodSectionHeaderItem forSectionWithIdentifier:SectionIdentifierPayment]; } @@ -529,7 +530,7 @@ if (contactInfoSectionHeaderItem) { [contactInfoSectionHeaderItem setType:ItemTypeContactInfoHeader]; [contactInfoSectionHeaderItem - setTextColor:[[MDCPalette greyPalette] tint500]]; + setTextColor:[UIColor colorNamed:kTextSecondaryColor]]; [model setHeader:contactInfoSectionHeaderItem forSectionWithIdentifier:SectionIdentifierContactInfo]; }
diff --git a/ios/chrome/browser/ui/payments/shipping_address_selection_mediator.mm b/ios/chrome/browser/ui/payments/shipping_address_selection_mediator.mm index 2e4bbe62..a0489e3 100644 --- a/ios/chrome/browser/ui/payments/shipping_address_selection_mediator.mm +++ b/ios/chrome/browser/ui/payments/shipping_address_selection_mediator.mm
@@ -12,10 +12,10 @@ #include "components/strings/grit/components_strings.h" #include "ios/chrome/browser/payments/payment_request.h" #import "ios/chrome/browser/payments/payment_request_util.h" -#import "ios/chrome/browser/ui/colors/MDCPalette+CrAdditions.h" #import "ios/chrome/browser/ui/payments/cells/autofill_profile_item.h" #import "ios/chrome/browser/ui/payments/cells/payments_text_item.h" #include "ios/chrome/browser/ui/util/uikit_ui_util.h" +#import "ios/chrome/common/colors/semantic_color_names.h" #include "ios/chrome/grit/ios_theme_resources.h" #include "ui/base/l10n/l10n_util.h" @@ -104,8 +104,9 @@ PaymentsTextItem* addButtonItem = [[PaymentsTextItem alloc] init]; addButtonItem.text = base::SysUTF16ToNSString( GetAddShippingAddressButtonLabel(self.paymentRequest->shipping_type())); - addButtonItem.trailingImage = TintImage([UIImage imageNamed:@"ic_add"], - [[MDCPalette greyPalette] tint400]); + addButtonItem.trailingImage = [[UIImage imageNamed:@"ic_add"] + imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate]; + addButtonItem.trailingImageTintColor = [UIColor colorNamed:kGrey400Color]; addButtonItem.cellType = PaymentsTextCellTypeCallToAction; return addButtonItem; }
diff --git a/ios/chrome/browser/ui/qr_scanner/qr_scanner_view_controller_egtest.mm b/ios/chrome/browser/ui/qr_scanner/qr_scanner_view_controller_egtest.mm index 271ec22..5660d97 100644 --- a/ios/chrome/browser/ui/qr_scanner/qr_scanner_view_controller_egtest.mm +++ b/ios/chrome/browser/ui/qr_scanner/qr_scanner_view_controller_egtest.mm
@@ -119,11 +119,9 @@ waitForSufficientlyVisibleElementWithMatcher:chrome_test_util::Omnibox()]; // Tap the QR Code scanner button in the keyboard accessory view. - id<GREYMatcher> matcher = - grey_allOf(grey_accessibilityLabel(@"QR code Search"), - grey_kindOfClass([UIButton class]), nil); - - [[EarlGrey selectElementWithMatcher:matcher] performAction:grey_tap()]; + [[EarlGrey + selectElementWithMatcher:grey_accessibilityLabel(@"QR code Search")] + performAction:grey_tap()]; } // Taps the |button|.
diff --git a/ios/chrome/browser/ui/toolbar/keyboard_assist/toolbar_input_assistant_items.mm b/ios/chrome/browser/ui/toolbar/keyboard_assist/toolbar_input_assistant_items.mm index 316bd40..3742f14f 100644 --- a/ios/chrome/browser/ui/toolbar/keyboard_assist/toolbar_input_assistant_items.mm +++ b/ios/chrome/browser/ui/toolbar/keyboard_assist/toolbar_input_assistant_items.mm
@@ -8,6 +8,8 @@ #import "ios/chrome/browser/ui/toolbar/keyboard_assist/toolbar_assistive_keyboard_views.h" #import "ios/chrome/browser/ui/toolbar/keyboard_assist/toolbar_assistive_keyboard_views_utils.h" #import "ios/chrome/browser/ui/toolbar/keyboard_assist/toolbar_ui_bar_button_item.h" +#import "ios/chrome/browser/ui/util/uikit_ui_util.h" +#include "ios/chrome/grit/ios_strings.h" #if !defined(__has_feature) || !__has_feature(objc_arc) #error "This file requires ARC support." @@ -15,19 +17,33 @@ NSArray<UIBarButtonItemGroup*>* ToolbarAssistiveKeyboardLeadingBarButtonGroups( id<ToolbarAssistiveKeyboardDelegate> delegate) { - NSArray<UIButton*>* buttons = - ToolbarAssistiveKeyboardLeadingButtons(delegate); - NSMutableArray<UIBarButtonItem*>* barButtonItems = - [NSMutableArray arrayWithCapacity:[buttons count]]; + UIImage* voiceSearchIcon = + [[UIImage imageNamed:@"keyboard_accessory_voice_search"] + imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal]; + UIBarButtonItem* voiceSearchItem = [[UIBarButtonItem alloc] + initWithImage:voiceSearchIcon + style:UIBarButtonItemStylePlain + target:delegate + action:@selector(keyboardAccessoryVoiceSearchTouchDown:)]; + SetA11yLabelAndUiAutomationName(voiceSearchItem, + IDS_IOS_KEYBOARD_ACCESSORY_VIEW_VOICE_SEARCH, + @"Voice Search"); - for (UIButton* button in buttons) { - UIBarButtonItem* item = [[UIBarButtonItem alloc] initWithCustomView:button]; - item.accessibilityLabel = button.accessibilityLabel; - [barButtonItems addObject:item]; - } + UIImage* cameraIcon = [[UIImage imageNamed:@"keyboard_accessory_qr_scanner"] + imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal]; + UIBarButtonItem* cameraItem = [[UIBarButtonItem alloc] + initWithImage:cameraIcon + style:UIBarButtonItemStylePlain + target:delegate + action:@selector(keyboardAccessoryCameraSearchTouchUp)]; + SetA11yLabelAndUiAutomationName( + cameraItem, IDS_IOS_KEYBOARD_ACCESSORY_VIEW_QR_CODE_SEARCH, + @"QR code Search"); + + NSArray* items = @[ voiceSearchItem, cameraItem ]; UIBarButtonItemGroup* group = - [[UIBarButtonItemGroup alloc] initWithBarButtonItems:barButtonItems + [[UIBarButtonItemGroup alloc] initWithBarButtonItems:items representativeItem:nil]; return @[ group ]; }
diff --git a/ios/chrome/browser/ui/util/uikit_ui_util.h b/ios/chrome/browser/ui/util/uikit_ui_util.h index 84318e3..9a8c47cc 100644 --- a/ios/chrome/browser/ui/util/uikit_ui_util.h +++ b/ios/chrome/browser/ui/util/uikit_ui_util.h
@@ -24,9 +24,10 @@ // localized string corresponding to |idsAccessibilityLabel|. // |englishUiAutomationName| is the name used in JavaScript UI Automation test // scripts to identify the |element|. -void SetA11yLabelAndUiAutomationName(UIView* element, - int idsAccessibilityLabel, - NSString* englishUiAutomationName); +void SetA11yLabelAndUiAutomationName( + NSObject<UIAccessibilityIdentification>* element, + int idsAccessibilityLabel, + NSString* englishUiAutomationName); // Sets the given |button|'s width to exactly fit its image and text. Does not // modify the button's height.
diff --git a/ios/chrome/browser/ui/util/uikit_ui_util.mm b/ios/chrome/browser/ui/util/uikit_ui_util.mm index 2184bf7..b079cb2e 100644 --- a/ios/chrome/browser/ui/util/uikit_ui_util.mm +++ b/ios/chrome/browser/ui/util/uikit_ui_util.mm
@@ -67,9 +67,10 @@ } // namespace -void SetA11yLabelAndUiAutomationName(UIView* element, - int idsAccessibilityLabel, - NSString* englishUiAutomationName) { +void SetA11yLabelAndUiAutomationName( + NSObject<UIAccessibilityIdentification>* element, + int idsAccessibilityLabel, + NSString* englishUiAutomationName) { [element setAccessibilityLabel:l10n_util::GetNSString(idsAccessibilityLabel)]; [element setAccessibilityIdentifier:englishUiAutomationName]; }
diff --git a/ios/chrome/browser/webdata_services/web_data_service_factory.cc b/ios/chrome/browser/webdata_services/web_data_service_factory.cc index e2541f4..ddf7b50 100644 --- a/ios/chrome/browser/webdata_services/web_data_service_factory.cc +++ b/ios/chrome/browser/webdata_services/web_data_service_factory.cc
@@ -102,7 +102,7 @@ const base::FilePath& browser_state_path = context->GetStatePath(); return std::make_unique<WebDataServiceWrapper>( browser_state_path, GetApplicationContext()->GetApplicationLocale(), - base::CreateSingleThreadTaskRunnerWithTraits({web::WebThread::UI}), + base::CreateSingleThreadTaskRunner({web::WebThread::UI}), base::DoNothing()); }
diff --git a/ios/components/io_thread/ios_io_thread.mm b/ios/components/io_thread/ios_io_thread.mm index 9994deec..a866c95a 100644 --- a/ios/components/io_thread/ios_io_thread.mm +++ b/ios/components/io_thread/ios_io_thread.mm
@@ -131,7 +131,7 @@ IOSIOThread* io_thread) : io_thread_(io_thread), network_task_runner_( - base::CreateSingleThreadTaskRunnerWithTraits({web::WebThread::IO})) {} + base::CreateSingleThreadTaskRunner({web::WebThread::IO})) {} SystemURLRequestContextGetter::~SystemURLRequestContextGetter() {} @@ -210,10 +210,9 @@ void IOSIOThread::ChangedToOnTheRecord() { DCHECK_CURRENTLY_ON(web::WebThread::UI); - base::PostTaskWithTraits( - FROM_HERE, {web::WebThread::IO}, - base::BindOnce(&IOSIOThread::ChangedToOnTheRecordOnIOThread, - base::Unretained(this))); + base::PostTask(FROM_HERE, {web::WebThread::IO}, + base::BindOnce(&IOSIOThread::ChangedToOnTheRecordOnIOThread, + base::Unretained(this))); } net::URLRequestContextGetter* IOSIOThread::system_url_request_context_getter() {
diff --git a/ios/web/download/download_task_impl.mm b/ios/web/download/download_task_impl.mm index 9932993..cb4f45b 100644 --- a/ios/web/download/download_task_impl.mm +++ b/ios/web/download/download_task_impl.mm
@@ -115,12 +115,12 @@ task:(NSURLSessionTask*)task didCompleteWithError:(nullable NSError*)error { __weak CRWURLSessionDelegate* weakSelf = self; - base::PostTaskWithTraits(FROM_HERE, {WebThread::UI}, base::BindOnce(^{ - CRWURLSessionDelegate* strongSelf = weakSelf; - if (strongSelf.propertiesBlock) - strongSelf.propertiesBlock( - task, error, /*terminal_callback=*/true); - })); + base::PostTask(FROM_HERE, {WebThread::UI}, base::BindOnce(^{ + CRWURLSessionDelegate* strongSelf = weakSelf; + if (strongSelf.propertiesBlock) + strongSelf.propertiesBlock(task, error, + /*terminal_callback=*/true); + })); } - (void)URLSession:(NSURLSession*)session @@ -132,26 +132,26 @@ using Bytes = const void* _Nonnull; [data enumerateByteRangesUsingBlock:^(Bytes bytes, NSRange range, BOOL*) { auto buffer = GetBuffer(bytes, range.length); - base::PostTaskWithTraits(FROM_HERE, {WebThread::UI}, base::BindOnce(^{ - CRWURLSessionDelegate* strongSelf = weakSelf; - if (!strongSelf.dataBlock) { - dispatch_semaphore_signal(semaphore); - return; - } - strongSelf.dataBlock(std::move(buffer), ^{ - // Data was written to disk, unblock queue to - // read the next chunk of downloaded data. - dispatch_semaphore_signal(semaphore); - }); - })); + base::PostTask(FROM_HERE, {WebThread::UI}, base::BindOnce(^{ + CRWURLSessionDelegate* strongSelf = weakSelf; + if (!strongSelf.dataBlock) { + dispatch_semaphore_signal(semaphore); + return; + } + strongSelf.dataBlock(std::move(buffer), ^{ + // Data was written to disk, unblock queue to + // read the next chunk of downloaded data. + dispatch_semaphore_signal(semaphore); + }); + })); dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER); }]; - base::PostTaskWithTraits(FROM_HERE, {WebThread::UI}, base::BindOnce(^{ - CRWURLSessionDelegate* strongSelf = weakSelf; - if (strongSelf.propertiesBlock) - weakSelf.propertiesBlock( - task, nil, /*terminal_callback=*/false); - })); + base::PostTask(FROM_HERE, {WebThread::UI}, base::BindOnce(^{ + CRWURLSessionDelegate* strongSelf = weakSelf; + if (strongSelf.propertiesBlock) + weakSelf.propertiesBlock(task, nil, + /*terminal_callback=*/false); + })); } - (void)URLSession:(NSURLSession*)session
diff --git a/ios/web/find_in_page/find_in_page_manager_impl.mm b/ios/web/find_in_page/find_in_page_manager_impl.mm index 3e8b46b..7cfdca75 100644 --- a/ios/web/find_in_page/find_in_page_manager_impl.mm +++ b/ios/web/find_in_page/find_in_page_manager_impl.mm
@@ -112,7 +112,7 @@ if (all_frames.size() == 0) { // No frames to search in. // Call asyncronously to match behavior if find was successful in frames. - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {WebThread::UI}, base::BindOnce(&FindInPageManagerImpl::LastFindRequestCompleted, weak_factory_.GetWeakPtr())); @@ -135,7 +135,7 @@ last_find_request_.DidReceiveFindResponseFromOneFrame(); if (last_find_request_.AreAllFindResponsesReturned()) { // Call asyncronously to match behavior if find was done in frames. - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {WebThread::UI}, base::BindOnce(&FindInPageManagerImpl::LastFindRequestCompleted, weak_factory_.GetWeakPtr()));
diff --git a/ios/web/init/web_main_loop.mm b/ios/web/init/web_main_loop.mm index 22d8975..b24f4f1 100644 --- a/ios/web/init/web_main_loop.mm +++ b/ios/web/init/web_main_loop.mm
@@ -156,7 +156,7 @@ // Teardown may start in PostMainMessageLoopRun, and during teardown we // need to be able to perform IO. base::ThreadRestrictions::SetIOAllowed(true); - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {WebThread::IO}, base::BindOnce( base::IgnoreResult(&base::ThreadRestrictions::SetIOAllowed), true)); @@ -167,7 +167,7 @@ // no persistent work is being done after ThreadPoolInstance::Shutdown() in // order to move towards atomic shutdown. base::ThreadRestrictions::SetWaitAllowed(true); - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {WebThread::IO}, base::BindOnce( base::IgnoreResult(&base::ThreadRestrictions::SetWaitAllowed), true));
diff --git a/ios/web/js_messaging/web_frame_impl.mm b/ios/web/js_messaging/web_frame_impl.mm index 0b0cdf7..0905d13 100644 --- a/ios/web/js_messaging/web_frame_impl.mm +++ b/ios/web/js_messaging/web_frame_impl.mm
@@ -155,7 +155,7 @@ std::move(callback), std::move(timeout_callback)); pending_requests_[message_id] = std::move(callbacks); - base::PostDelayedTaskWithTraits( + base::PostDelayedTask( FROM_HERE, {web::WebThread::UI}, pending_requests_[message_id]->timeout_callback->callback(), timeout); bool called =
diff --git a/ios/web/net/cookie_notification_bridge.mm b/ios/web/net/cookie_notification_bridge.mm index b7ec466..1004380f 100644 --- a/ios/web/net/cookie_notification_bridge.mm +++ b/ios/web/net/cookie_notification_bridge.mm
@@ -38,7 +38,7 @@ NSNotification* notification) { DCHECK([[notification name] isEqualToString:NSHTTPCookieManagerCookiesChangedNotification]); - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {web::WebThread::IO}, base::BindOnce(&net::CookieStoreIOS::NotifySystemCookiesChanged)); }
diff --git a/ios/web/net/cookies/wk_http_system_cookie_store.mm b/ios/web/net/cookies/wk_http_system_cookie_store.mm index 5b5eba4..20400842 100644 --- a/ios/web/net/cookies/wk_http_system_cookie_store.mm +++ b/ios/web/net/cookies/wk_http_system_cookie_store.mm
@@ -28,8 +28,7 @@ // SystemCookieStore should operate on IO thread. void RunBlockOnIOThread(ProceduralBlock block) { DCHECK(block != nil); - base::PostTaskWithTraits(FROM_HERE, {web::WebThread::IO}, - base::BindOnce(block)); + base::PostTask(FROM_HERE, {web::WebThread::IO}, base::BindOnce(block)); } // Returns wether |cookie| should be included for queries about |url|. @@ -85,7 +84,7 @@ creation_time_manager_->GetWeakPtr(); NSHTTPCookie* block_cookie = cookie; __weak __typeof(crw_cookie_store_) block_cookie_store = crw_cookie_store_; - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {web::WebThread::UI}, base::BindOnce(^{ [block_cookie_store deleteCookie:block_cookie @@ -114,7 +113,7 @@ if (optional_creation_time && !optional_creation_time->is_null()) cookie_time = *optional_creation_time; __weak __typeof(crw_cookie_store_) block_cookie_store = crw_cookie_store_; - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {web::WebThread::UI}, base::BindOnce(^{ [block_cookie_store setCookie:block_cookie @@ -137,7 +136,7 @@ base::WeakPtr<net::CookieCreationTimeManager> weak_time_manager = creation_time_manager_->GetWeakPtr(); __weak __typeof(crw_cookie_store_) block_cookie_store = crw_cookie_store_; - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {web::WebThread::UI}, base::BindOnce(^{ [block_cookie_store getAllCookies:^(NSArray<NSHTTPCookie*>* cookies) { ProceduralBlock completionHandler = ^{ @@ -196,7 +195,7 @@ creation_time_manager_->GetWeakPtr(); __weak __typeof(crw_cookie_store_) weak_cookie_store = crw_cookie_store_; GURL block_url = include_url; - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {web::WebThread::UI}, base::BindOnce(^{ __typeof(weak_cookie_store) strong_cookie_store = weak_cookie_store; if (strong_cookie_store) {
diff --git a/ios/web/network_context_owner.cc b/ios/web/network_context_owner.cc index 0fdb956..aa53819 100644 --- a/ios/web/network_context_owner.cc +++ b/ios/web/network_context_owner.cc
@@ -24,7 +24,7 @@ network::mojom::NetworkContextPtr* network_context_client) : request_context_(request_context) { DCHECK_CURRENTLY_ON(WebThread::UI); - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {web::WebThread::IO}, base::BindOnce(&NetworkContextOwner::InitializeOnIOThread, // This is safe, since |this| will be deleted on the IO
diff --git a/ios/web/network_context_owner_unittest.cc b/ios/web/network_context_owner_unittest.cc index 00526a88..0885a6a3 100644 --- a/ios/web/network_context_owner_unittest.cc +++ b/ios/web/network_context_owner_unittest.cc
@@ -25,7 +25,7 @@ NetworkContextOwnerTest() : saw_connection_error_(false), context_getter_(base::MakeRefCounted<net::TestURLRequestContextGetter>( - base::CreateSingleThreadTaskRunnerWithTraits({WebThread::IO}))) {} + base::CreateSingleThreadTaskRunner({WebThread::IO}))) {} ~NetworkContextOwnerTest() override { // Tests should cleanup after themselves. @@ -79,7 +79,7 @@ base::RunLoop().RunUntilIdle(); EXPECT_FALSE(saw_connection_error_); - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {web::WebThread::IO}, base::BindOnce( &net::TestURLRequestContextGetter::NotifyContextShuttingDown,
diff --git a/ios/web/public/test/fakes/fake_web_frame.cc b/ios/web/public/test/fakes/fake_web_frame.cc index ee08b23..1c114ff 100644 --- a/ios/web/public/test/fakes/fake_web_frame.cc +++ b/ios/web/public/test/fakes/fake_web_frame.cc
@@ -70,8 +70,8 @@ return false; } const base::Value* js_result = result_map_[name].get(); - base::PostTaskWithTraits(FROM_HERE, {WebThread::UI}, - base::BindOnce(std::move(callback), js_result)); + base::PostTask(FROM_HERE, {WebThread::UI}, + base::BindOnce(std::move(callback), js_result)); return true; }
diff --git a/ios/web/public/test/fakes/test_browser_state.cc b/ios/web/public/test/fakes/test_browser_state.cc index 278e0e6..03e9309 100644 --- a/ios/web/public/test/fakes/test_browser_state.cc +++ b/ios/web/public/test/fakes/test_browser_state.cc
@@ -33,7 +33,7 @@ scoped_refptr<base::SingleThreadTaskRunner> GetNetworkTaskRunner() const override { - return base::CreateSingleThreadTaskRunnerWithTraits({web::WebThread::IO}); + return base::CreateSingleThreadTaskRunner({web::WebThread::IO}); } private:
diff --git a/ios/web/public/test/fakes/test_web_client.mm b/ios/web/public/test/fakes/test_web_client.mm index 3619656..557c62a 100644 --- a/ios/web/public/test/fakes/test_web_client.mm +++ b/ios/web/public/test/fakes/test_web_client.mm
@@ -77,8 +77,8 @@ last_cert_error_overridable_ = overridable; // Embedder should consult the user, so reply is asynchronous. - base::PostTaskWithTraits(FROM_HERE, {WebThread::UI}, - base::BindOnce(callback, allow_certificate_errors_)); + base::PostTask(FROM_HERE, {WebThread::UI}, + base::BindOnce(callback, allow_certificate_errors_)); } void TestWebClient::SetAllowCertificateErrors(bool flag) {
diff --git a/ios/web/public/thread/web_task_traits.h b/ios/web/public/thread/web_task_traits.h index bd6d569c..e39ea37 100644 --- a/ios/web/public/thread/web_task_traits.h +++ b/ios/web/public/thread/web_task_traits.h
@@ -26,10 +26,10 @@ // to a WebThread. // // To post a task to the UI thread (analogous for IO thread): -// base::PostTaskWithTraits(FROM_HERE, {WebThread::UI}, task); +// base::PostTask(FROM_HERE, {WebThread::UI}, task); // // To obtain a TaskRunner for the UI thread (analogous for the IO thread): -// base::CreateSingleThreadTaskRunnerWithTraits({WebThread::UI}); +// base::CreateSingleThreadTaskRunner({WebThread::UI}); // // Tasks posted to the same WebThread with the same traits will be executed // in the order they were posted, regardless of the TaskRunners they were
diff --git a/ios/web/public/thread/web_thread.h b/ios/web/public/thread/web_thread.h index 46aacc8..caaee2ef 100644 --- a/ios/web/public/thread/web_thread.h +++ b/ios/web/public/thread/web_thread.h
@@ -57,7 +57,7 @@ IO, // NOTE: do not add new threads here. Instead you should just use - // base::Create*TaskRunnerWithTraits to run tasks on the ThreadPool. + // base::Create*TaskRunner to run tasks on the ThreadPool. // This identifier does not represent a thread. Instead it counts the // number of well-known threads. Insert new well-known threads before this @@ -68,7 +68,7 @@ // NOTE: Task posting APIs have moved to post_task.h. See web_task_traits.h. // TODO(crbug.com/878356): Consider replacing callsites of this with - // base::CreateTaskRunnerWithTraits({id})->DeleteSoon(..). + // base::CreateTaskRunner({id})->DeleteSoon(..). template <class T> static bool DeleteSoon(ID identifier, const base::Location& from_here,
diff --git a/ios/web/security/crw_cert_verification_controller.mm b/ios/web/security/crw_cert_verification_controller.mm index 58de6db..5ff2746 100644 --- a/ios/web/security/crw_cert_verification_controller.mm +++ b/ios/web/security/crw_cert_verification_controller.mm
@@ -133,11 +133,10 @@ DCHECK(cert); } DCHECK(cert->intermediate_buffers().empty()); - base::PostTaskWithTraits(FROM_HERE, {WebThread::IO}, base::BindOnce(^{ - _certPolicyCache->AllowCertForHost( - cert.get(), base::SysNSStringToUTF8(host), - status); - })); + base::PostTask(FROM_HERE, {WebThread::IO}, base::BindOnce(^{ + _certPolicyCache->AllowCertForHost( + cert.get(), base::SysNSStringToUTF8(host), status); + })); } #pragma mark - Private @@ -172,29 +171,29 @@ DCHECK_CURRENTLY_ON(WebThread::UI); DCHECK(handler); TaskTraits traits{WebThread::IO, TaskShutdownBehavior::BLOCK_SHUTDOWN}; - base::PostTaskWithTraits(FROM_HERE, traits, base::BindOnce(^{ - // |loadPolicyForRejectedTrustResult:certStatus:serverTrust:host:| - // can only be called on IO thread. - net::CertStatus certStatus = - [self certStatusFromTrustResult:trustResult - serverTrust:trust]; + base::PostTask(FROM_HERE, traits, base::BindOnce(^{ + // |loadPolicyForRejectedTrustResult:certStatus:serverTrust + // :host:| can only be called on IO thread. + net::CertStatus certStatus = + [self certStatusFromTrustResult:trustResult + serverTrust:trust]; - web::CertAcceptPolicy policy = [self - loadPolicyForRejectedTrustResult:trustResult - certStatus:certStatus - serverTrust:trust.get() - host:host]; + web::CertAcceptPolicy policy = + [self loadPolicyForRejectedTrustResult:trustResult + certStatus:certStatus + serverTrust:trust.get() + host:host]; - // TODO(crbug.com/872372): This should use - // PostTaskWithTraits to post to WebThread::UI with - // BLOCK_SHUTDOWN once shutdown behaviors are - // supported on the UI thread. BLOCK_SHUTDOWN is - // necessary because WKWebView throws an exception - // if the completion handler doesn't run. - dispatch_async(dispatch_get_main_queue(), ^{ - handler(policy, certStatus); - }); - })); + // TODO(crbug.com/872372): This should use + // PostTask to post to WebThread::UI with + // BLOCK_SHUTDOWN once shutdown behaviors are + // supported on the UI thread. BLOCK_SHUTDOWN is + // necessary because WKWebView throws an exception + // if the completion handler doesn't run. + dispatch_async(dispatch_get_main_queue(), ^{ + handler(policy, certStatus); + }); + })); } - (void)verifyTrust:(base::ScopedCFTypeRef<SecTrustRef>)trust @@ -203,13 +202,14 @@ DCHECK(completionHandler); // SecTrustEvaluate performs trust evaluation synchronously, possibly making // network requests. The UI thread should not be blocked by that operation. - base::PostTaskWithTraits( - FROM_HERE, {TaskShutdownBehavior::BLOCK_SHUTDOWN}, base::BindOnce(^{ + base::PostTask( + FROM_HERE, {base::ThreadPool(), TaskShutdownBehavior::BLOCK_SHUTDOWN}, + base::BindOnce(^{ SecTrustResultType trustResult = kSecTrustResultInvalid; if (SecTrustEvaluate(trust.get(), &trustResult) != errSecSuccess) { trustResult = kSecTrustResultInvalid; } - // TODO(crbug.com/872372): This should use PostTaskWithTraits to post to + // TODO(crbug.com/872372): This should use PostTask to post to // WebThread::UI with BLOCK_SHUTDOWN once shutdown behaviors are // supported on the UI thread. BLOCK_SHUTDOWN is necessary because // WKWebView throws an exception if the completion handler doesn't run.
diff --git a/ios/web/session/session_certificate_policy_cache_impl.mm b/ios/web/session/session_certificate_policy_cache_impl.mm index 3d3ce057..c04ebfd7 100644 --- a/ios/web/session/session_certificate_policy_cache_impl.mm +++ b/ios/web/session/session_certificate_policy_cache_impl.mm
@@ -57,13 +57,12 @@ DCHECK(cache.get()); NSSet* allowed_certs = [NSSet setWithSet:allowed_certs_]; const scoped_refptr<web::CertificatePolicyCache> cache_copy = cache; - base::PostTaskWithTraits( - FROM_HERE, {web::WebThread::IO}, base::BindOnce(^{ - for (CRWSessionCertificateStorage* cert in allowed_certs) { - cache_copy->AllowCertForHost(cert.certificate, cert.host, - cert.status); - } - })); + base::PostTask(FROM_HERE, {web::WebThread::IO}, base::BindOnce(^{ + for (CRWSessionCertificateStorage* cert in allowed_certs) { + cache_copy->AllowCertForHost(cert.certificate, cert.host, + cert.status); + } + })); } void SessionCertificatePolicyCacheImpl::RegisterAllowedCertificate(
diff --git a/ios/web/session/session_certificate_policy_cache_impl_unittest.mm b/ios/web/session/session_certificate_policy_cache_impl_unittest.mm index b3a6159..72c87e6 100644 --- a/ios/web/session/session_certificate_policy_cache_impl_unittest.mm +++ b/ios/web/session/session_certificate_policy_cache_impl_unittest.mm
@@ -37,11 +37,10 @@ __block web::CertPolicy::Judgment judgement = web::CertPolicy::Judgment::UNKNOWN; __block bool completed = false; - base::PostTaskWithTraits(FROM_HERE, {web::WebThread::IO}, base::BindOnce(^{ - completed = true; - judgement = - cache->QueryPolicy(cert.get(), host, status); - })); + base::PostTask(FROM_HERE, {web::WebThread::IO}, base::BindOnce(^{ + completed = true; + judgement = cache->QueryPolicy(cert.get(), host, status); + })); EXPECT_TRUE(WaitUntilConditionOrTimeout(1.0, ^{ return completed; }));
diff --git a/ios/web/shell/shell_browser_state.mm b/ios/web/shell/shell_browser_state.mm index 55b0135..f72c9987 100644 --- a/ios/web/shell/shell_browser_state.mm +++ b/ios/web/shell/shell_browser_state.mm
@@ -23,8 +23,7 @@ CHECK(base::PathService::Get(base::DIR_APP_DATA, &path_)); request_context_getter_ = new ShellURLRequestContextGetter( - GetStatePath(), - base::CreateSingleThreadTaskRunnerWithTraits({web::WebThread::IO})); + GetStatePath(), base::CreateSingleThreadTaskRunner({web::WebThread::IO})); } ShellBrowserState::~ShellBrowserState() {
diff --git a/ios/web/shell/shell_url_request_context_getter.mm b/ios/web/shell/shell_url_request_context_getter.mm index fe6d3f7..485ffd67 100644 --- a/ios/web/shell/shell_url_request_context_getter.mm +++ b/ios/web/shell/shell_url_request_context_getter.mm
@@ -78,8 +78,9 @@ scoped_refptr<net::CookieMonster::PersistentCookieStore> persistent_store = new net::SQLitePersistentCookieStore( cookie_path, network_task_runner_, - base::CreateSequencedTaskRunnerWithTraits( - {base::MayBlock(), base::TaskPriority::BEST_EFFORT}), + base::CreateSequencedTaskRunner({base::ThreadPool(), + base::MayBlock(), + base::TaskPriority::BEST_EFFORT}), true, nullptr); std::unique_ptr<net::CookieStoreIOS> cookie_store( new net::CookieStoreIOSPersistent(persistent_store.get(), @@ -108,8 +109,9 @@ transport_security_persister_ = std::make_unique<net::TransportSecurityPersister>( url_request_context_->transport_security_state(), base_path_, - base::CreateSequencedTaskRunnerWithTraits( - {base::MayBlock(), base::TaskPriority::BEST_EFFORT})); + base::CreateSequencedTaskRunner({base::ThreadPool(), + base::MayBlock(), + base::TaskPriority::BEST_EFFORT})); storage_->set_http_server_properties( std::make_unique<net::HttpServerProperties>());
diff --git a/ios/web/web_thread_impl.cc b/ios/web/web_thread_impl.cc index a8cc35a..fb55070 100644 --- a/ios/web/web_thread_impl.cc +++ b/ios/web/web_thread_impl.cc
@@ -36,15 +36,14 @@ bool PostDelayedTask(const base::Location& from_here, base::OnceClosure task, base::TimeDelta delay) override { - return base::PostDelayedTaskWithTraits(from_here, {id_}, std::move(task), - delay); + return base::PostDelayedTask(from_here, {id_}, std::move(task), delay); } bool PostNonNestableDelayedTask(const base::Location& from_here, base::OnceClosure task, base::TimeDelta delay) override { - return base::PostDelayedTaskWithTraits(from_here, {id_, NonNestable()}, - std::move(task), delay); + return base::PostDelayedTask(from_here, {id_, NonNestable()}, + std::move(task), delay); } bool RunsTasksInCurrentSequence() const override {
diff --git a/ios/web/web_thread_unittest.cc b/ios/web/web_thread_unittest.cc index f98df3b..c581a3c 100644 --- a/ios/web/web_thread_unittest.cc +++ b/ios/web/web_thread_unittest.cc
@@ -24,18 +24,18 @@ web::TestWebThreadBundle web_thread_bundle_; }; -TEST_F(WebThreadTest, PostTaskWithTraits) { +TEST_F(WebThreadTest, PostTask) { base::RunLoop run_loop; - EXPECT_TRUE(base::PostTaskWithTraits( + EXPECT_TRUE(base::PostTask( FROM_HERE, {WebThread::IO}, base::BindOnce(&BasicFunction, run_loop.QuitWhenIdleClosure(), WebThread::IO))); run_loop.Run(); } -TEST_F(WebThreadTest, PostTaskViaTaskRunnerWithTraits) { +TEST_F(WebThreadTest, PostTaskViaTaskRunner) { scoped_refptr<base::TaskRunner> task_runner = - base::CreateTaskRunnerWithTraits({WebThread::IO}); + base::CreateTaskRunner({WebThread::IO}); base::RunLoop run_loop; EXPECT_TRUE(task_runner->PostTask( FROM_HERE, base::BindOnce(&BasicFunction, run_loop.QuitWhenIdleClosure(), @@ -43,9 +43,9 @@ run_loop.Run(); } -TEST_F(WebThreadTest, PostTaskViaSequencedTaskRunnerWithTraits) { +TEST_F(WebThreadTest, PostTaskViaSequencedTaskRunner) { scoped_refptr<base::SequencedTaskRunner> task_runner = - base::CreateSequencedTaskRunnerWithTraits({WebThread::IO}); + base::CreateSequencedTaskRunner({WebThread::IO}); base::RunLoop run_loop; EXPECT_TRUE(task_runner->PostTask( FROM_HERE, base::BindOnce(&BasicFunction, run_loop.QuitWhenIdleClosure(), @@ -53,9 +53,9 @@ run_loop.Run(); } -TEST_F(WebThreadTest, PostTaskViaSingleThreadTaskRunnerWithTraits) { +TEST_F(WebThreadTest, PostTaskViaSingleThreadTaskRunner) { scoped_refptr<base::SingleThreadTaskRunner> task_runner = - base::CreateSingleThreadTaskRunnerWithTraits({WebThread::IO}); + base::CreateSingleThreadTaskRunner({WebThread::IO}); base::RunLoop run_loop; EXPECT_TRUE(task_runner->PostTask( FROM_HERE, base::BindOnce(&BasicFunction, run_loop.QuitWhenIdleClosure(),
diff --git a/ios/web/webui/url_data_manager_ios.cc b/ios/web/webui/url_data_manager_ios.cc index e430faa..32105a85 100644 --- a/ios/web/webui/url_data_manager_ios.cc +++ b/ios/web/webui/url_data_manager_ios.cc
@@ -67,7 +67,7 @@ void URLDataManagerIOS::AddDataSource(URLDataSourceIOSImpl* source) { DCHECK_CURRENTLY_ON(web::WebThread::UI); - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {web::WebThread::IO}, base::BindOnce(&AddDataSourceOnIOThread, base::Unretained(browser_state_), base::WrapRefCounted(source))); @@ -109,9 +109,8 @@ } if (schedule_delete) { // Schedule a task to delete the DataSource back on the UI thread. - base::PostTaskWithTraits( - FROM_HERE, {web::WebThread::UI}, - base::BindOnce(&URLDataManagerIOS::DeleteDataSources)); + base::PostTask(FROM_HERE, {web::WebThread::UI}, + base::BindOnce(&URLDataManagerIOS::DeleteDataSources)); } }
diff --git a/ios/web/webui/url_data_manager_ios_backend.mm b/ios/web/webui/url_data_manager_ios_backend.mm index 5cd1f108..17fb2d2 100644 --- a/ios/web/webui/url_data_manager_ios_backend.mm +++ b/ios/web/webui/url_data_manager_ios_backend.mm
@@ -376,10 +376,9 @@ const base::WeakPtr<URLRequestChromeJob>& job) { DCHECK_CURRENTLY_ON(WebThread::UI); std::string mime_type = source->source()->GetMimeType(path); - base::PostTaskWithTraits( - FROM_HERE, {WebThread::IO}, - base::BindOnce(&URLRequestChromeJob::MimeTypeAvailable, job, - base::RetainedRef(source), mime_type)); + base::PostTask(FROM_HERE, {WebThread::IO}, + base::BindOnce(&URLRequestChromeJob::MimeTypeAvailable, job, + base::RetainedRef(source), mime_type)); } } // namespace @@ -495,7 +494,7 @@ // message loop before request for data. And correspondingly their // replies are put on the IO thread in the same order. scoped_refptr<base::SingleThreadTaskRunner> target_runner = - base::CreateSingleThreadTaskRunnerWithTraits({web::WebThread::UI}); + base::CreateSingleThreadTaskRunner({web::WebThread::UI}); target_runner->PostTask( FROM_HERE, base::BindOnce(&GetMimeTypeOnUI, base::RetainedRef(source), path, job->weak_factory_.GetWeakPtr()));
diff --git a/ios/web/webui/url_data_source_ios_impl.cc b/ios/web/webui/url_data_source_ios_impl.cc index 8e9836ca..6ae4184 100644 --- a/ios/web/webui/url_data_source_ios_impl.cc +++ b/ios/web/webui/url_data_source_ios_impl.cc
@@ -42,10 +42,9 @@ // when the object is deleted. return; } - base::PostTaskWithTraits( - FROM_HERE, {web::WebThread::IO}, - base::BindOnce(&URLDataSourceIOSImpl::SendResponseOnIOThread, this, - request_id, std::move(bytes))); + base::PostTask(FROM_HERE, {web::WebThread::IO}, + base::BindOnce(&URLDataSourceIOSImpl::SendResponseOnIOThread, + this, request_id, std::move(bytes))); } void URLDataSourceIOSImpl::SendResponseOnIOThread(
diff --git a/ios/web_view/internal/autofill/cwv_autofill_data_manager.mm b/ios/web_view/internal/autofill/cwv_autofill_data_manager.mm index 64ef7ca..383e528 100644 --- a/ios/web_view/internal/autofill/cwv_autofill_data_manager.mm +++ b/ios/web_view/internal/autofill/cwv_autofill_data_manager.mm
@@ -114,9 +114,9 @@ // |personalDataDidChange| to be invoked. if (_personalDataManager->IsDataLoaded()) { NSArray<CWVAutofillProfile*>* profiles = [self profiles]; - base::PostTaskWithTraits(FROM_HERE, {web::WebThread::UI}, base::BindOnce(^{ - completionHandler(profiles); - })); + base::PostTask(FROM_HERE, {web::WebThread::UI}, base::BindOnce(^{ + completionHandler(profiles); + })); } else { [_fetchProfilesCompletionHandlers addObject:completionHandler]; } @@ -137,9 +137,9 @@ // |personalDataDidChange| to be invoked. if (_personalDataManager->IsDataLoaded()) { NSArray<CWVCreditCard*>* creditCards = [self creditCards]; - base::PostTaskWithTraits(FROM_HERE, {web::WebThread::UI}, base::BindOnce(^{ - completionHandler(creditCards); - })); + base::PostTask(FROM_HERE, {web::WebThread::UI}, base::BindOnce(^{ + completionHandler(creditCards); + })); } else { [_fetchCreditCardsCompletionHandlers addObject:completionHandler]; }
diff --git a/ios/web_view/internal/autofill/cwv_credit_card_verifier_unittest.mm b/ios/web_view/internal/autofill/cwv_credit_card_verifier_unittest.mm index 422982b..6c03464 100644 --- a/ios/web_view/internal/autofill/cwv_credit_card_verifier_unittest.mm +++ b/ios/web_view/internal/autofill/cwv_credit_card_verifier_unittest.mm
@@ -59,7 +59,7 @@ const UserProvidedUnmaskDetails& unmask_details) override { unmask_details_ = unmask_details; // Fake the actual verification and just respond with success. - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {web::WebThread::UI}, base::BindOnce(^{ autofill::AutofillClient::PaymentsRpcResult result = autofill::AutofillClient::SUCCESS;
diff --git a/ios/web_view/internal/cwv_download_task.mm b/ios/web_view/internal/cwv_download_task.mm index e6fad725..9bf70c44 100644 --- a/ios/web_view/internal/cwv_download_task.mm +++ b/ios/web_view/internal/cwv_download_task.mm
@@ -101,8 +101,8 @@ - (void)startDownloadToLocalFileAtPath:(NSString*)path { scoped_refptr<base::SequencedTaskRunner> taskRunner = - base::CreateSequencedTaskRunnerWithTraits( - {base::MayBlock(), base::TaskPriority::BEST_EFFORT}); + base::CreateSequencedTaskRunner({base::ThreadPool(), base::MayBlock(), + base::TaskPriority::BEST_EFFORT}); __block auto writer = std::make_unique<net::URLFetcherFileWriter>( taskRunner, base::FilePath(base::SysNSStringToUTF8(path)));
diff --git a/ios/web_view/internal/ios_global_state_web_view_configuration.mm b/ios/web_view/internal/ios_global_state_web_view_configuration.mm index fd4473b..0c62e1c 100644 --- a/ios/web_view/internal/ios_global_state_web_view_configuration.mm +++ b/ios/web_view/internal/ios_global_state_web_view_configuration.mm
@@ -22,7 +22,7 @@ dispatch_once(&once_token, ^{ ios_web_view::InitializeGlobalState(); }); - return base::CreateSingleThreadTaskRunnerWithTraits({web::WebThread::IO}); + return base::CreateSingleThreadTaskRunner({web::WebThread::IO}); } } // namespace ios_global_state
diff --git a/ios/web_view/internal/passwords/web_view_password_store_factory.mm b/ios/web_view/internal/passwords/web_view_password_store_factory.mm index c30070f..9651abd63 100644 --- a/ios/web_view/internal/passwords/web_view_password_store_factory.mm +++ b/ios/web_view/internal/passwords/web_view_password_store_factory.mm
@@ -90,8 +90,8 @@ // the passwords obtained through tasks on the background runner influence // what the user sees. scoped_refptr<base::SequencedTaskRunner> db_task_runner( - base::CreateSequencedTaskRunnerWithTraits( - {base::MayBlock(), base::TaskPriority::USER_VISIBLE})); + base::CreateSequencedTaskRunner({base::ThreadPool(), base::MayBlock(), + base::TaskPriority::USER_VISIBLE})); scoped_refptr<password_manager::PasswordStore> store = new password_manager::PasswordStoreDefault(std::move(login_db));
diff --git a/ios/web_view/internal/sync/web_view_gcm_profile_service_factory.mm b/ios/web_view/internal/sync/web_view_gcm_profile_service_factory.mm index de9f73a..a5cd7de4 100644 --- a/ios/web_view/internal/sync/web_view_gcm_profile_service_factory.mm +++ b/ios/web_view/internal/sync/web_view_gcm_profile_service_factory.mm
@@ -46,7 +46,7 @@ web::BrowserState* context, base::WeakPtr<gcm::GCMProfileService> service, network::mojom::ProxyResolvingSocketFactoryRequest request) { - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {web::WebThread::UI}, base::BindOnce(&RequestProxyResolvingSocketFactoryOnUIThread, context, std::move(service), std::move(request))); @@ -88,8 +88,9 @@ DCHECK(!context->IsOffTheRecord()); scoped_refptr<base::SequencedTaskRunner> blocking_task_runner( - base::CreateSequencedTaskRunnerWithTraits( - {base::MayBlock(), base::TaskPriority::BEST_EFFORT, + base::CreateSequencedTaskRunner( + {base::ThreadPool(), base::MayBlock(), + base::TaskPriority::BEST_EFFORT, base::TaskShutdownBehavior::SKIP_ON_SHUTDOWN})); WebViewBrowserState* browser_state = WebViewBrowserState::FromBrowserState(context); @@ -101,8 +102,8 @@ version_info::Channel::STABLE, GetProductCategoryForSubtypes(), WebViewIdentityManagerFactory::GetForBrowserState(browser_state), base::WrapUnique(new gcm::GCMClientFactory), - base::CreateSingleThreadTaskRunnerWithTraits({web::WebThread::UI}), - base::CreateSingleThreadTaskRunnerWithTraits({web::WebThread::IO}), + base::CreateSingleThreadTaskRunner({web::WebThread::UI}), + base::CreateSingleThreadTaskRunner({web::WebThread::IO}), blocking_task_runner); } } // namespace ios_web_view
diff --git a/ios/web_view/internal/sync/web_view_profile_invalidation_provider_factory.mm b/ios/web_view/internal/sync/web_view_profile_invalidation_provider_factory.mm index c974505..1a3bf87b 100644 --- a/ios/web_view/internal/sync/web_view_profile_invalidation_provider_factory.mm +++ b/ios/web_view/internal/sync/web_view_profile_invalidation_provider_factory.mm
@@ -53,7 +53,7 @@ WebViewBrowserState* browser_state, base::WeakPtr<TiclInvalidationService> service, network::mojom::ProxyResolvingSocketFactoryRequest request) { - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {web::WebThread::UI}, base::BindOnce(&RequestProxyResolvingSocketFactoryOnUIThread, browser_state, std::move(service), std::move(request))); @@ -103,7 +103,7 @@ WebViewGCMProfileServiceFactory::GetForBrowserState(browser_state) ->driver(), base::BindRepeating(&RequestProxyResolvingSocketFactory, browser_state), - base::CreateSingleThreadTaskRunnerWithTraits({web::WebThread::IO}), + base::CreateSingleThreadTaskRunner({web::WebThread::IO}), browser_state->GetSharedURLLoaderFactory(), ApplicationContext::GetInstance()->GetNetworkConnectionTracker())); service->Init(
diff --git a/ios/web_view/internal/sync/web_view_sync_client.mm b/ios/web_view/internal/sync/web_view_sync_client.mm index 63f6eae8..1336ae9f 100644 --- a/ios/web_view/internal/sync/web_view_sync_client.mm +++ b/ios/web_view/internal/sync/web_view_sync_client.mm
@@ -79,9 +79,8 @@ component_factory_.reset(new browser_sync::ProfileSyncComponentsFactoryImpl( this, version_info::Channel::STABLE, prefs::kSavingBrowserHistoryDisabled, - base::CreateSingleThreadTaskRunnerWithTraits({web::WebThread::UI}), - db_thread_, profile_web_data_service_, account_web_data_service_, - password_store_, + base::CreateSingleThreadTaskRunner({web::WebThread::UI}), db_thread_, + profile_web_data_service_, account_web_data_service_, password_store_, /*bookmark_sync_service=*/nullptr)); } @@ -212,7 +211,7 @@ return new syncer::SequencedModelWorker(db_thread_, syncer::GROUP_DB); case syncer::GROUP_UI: return new syncer::UIModelWorker( - base::CreateSingleThreadTaskRunnerWithTraits({web::WebThread::UI})); + base::CreateSingleThreadTaskRunner({web::WebThread::UI})); case syncer::GROUP_PASSIVE: return new syncer::PassiveModelWorker(); case syncer::GROUP_PASSWORD:
diff --git a/ios/web_view/internal/web_view_browser_state.mm b/ios/web_view/internal/web_view_browser_state.mm index 28cc0343..e3caa9d 100644 --- a/ios/web_view/internal/web_view_browser_state.mm +++ b/ios/web_view/internal/web_view_browser_state.mm
@@ -87,7 +87,7 @@ request_context_getter_ = new WebViewURLRequestContextGetter( GetStatePath(), ApplicationContext::GetInstance()->GetNetLog(), - base::CreateSingleThreadTaskRunnerWithTraits({web::WebThread::IO})); + base::CreateSingleThreadTaskRunner({web::WebThread::IO})); // Initialize prefs. scoped_refptr<user_prefs::PrefRegistrySyncable> pref_registry = @@ -123,10 +123,9 @@ ActiveStateManager::FromBrowserState(this)->SetActive(false); #endif // BUILDFLAG(IOS_WEB_VIEW_ENABLE_SYNC) - base::PostTaskWithTraits( - FROM_HERE, {web::WebThread::IO}, - base::BindOnce(&WebViewURLRequestContextGetter::ShutDown, - request_context_getter_)); + base::PostTask(FROM_HERE, {web::WebThread::IO}, + base::BindOnce(&WebViewURLRequestContextGetter::ShutDown, + request_context_getter_)); } PrefService* WebViewBrowserState::GetPrefs() {
diff --git a/ios/web_view/internal/web_view_url_request_context_getter.mm b/ios/web_view/internal/web_view_url_request_context_getter.mm index df2949c0e..b11f4ae 100644 --- a/ios/web_view/internal/web_view_url_request_context_getter.mm +++ b/ios/web_view/internal/web_view_url_request_context_getter.mm
@@ -83,8 +83,9 @@ scoped_refptr<net::CookieMonster::PersistentCookieStore> persistent_store = new net::SQLitePersistentCookieStore( cookie_path, network_task_runner_, - base::CreateSequencedTaskRunnerWithTraits( - {base::MayBlock(), base::TaskPriority::BEST_EFFORT}), + base::CreateSequencedTaskRunner({base::ThreadPool(), + base::MayBlock(), + base::TaskPriority::BEST_EFFORT}), true, nullptr); std::unique_ptr<net::CookieStoreIOS> cookie_store( new net::CookieStoreIOSPersistent(persistent_store.get(), net_log_)); @@ -115,8 +116,9 @@ transport_security_persister_ = std::make_unique<net::TransportSecurityPersister>( url_request_context_->transport_security_state(), base_path_, - base::CreateSequencedTaskRunnerWithTraits( - {base::MayBlock(), base::TaskPriority::BEST_EFFORT})); + base::CreateSequencedTaskRunner({base::ThreadPool(), + base::MayBlock(), + base::TaskPriority::BEST_EFFORT})); storage_->set_http_server_properties( std::make_unique<net::HttpServerProperties>());
diff --git a/ios/web_view/internal/webdata_services/web_view_web_data_service_wrapper_factory.mm b/ios/web_view/internal/webdata_services/web_view_web_data_service_wrapper_factory.mm index 19e7ccb..b1ece38 100644 --- a/ios/web_view/internal/webdata_services/web_view_web_data_service_wrapper_factory.mm +++ b/ios/web_view/internal/webdata_services/web_view_web_data_service_wrapper_factory.mm
@@ -89,7 +89,7 @@ return std::make_unique<WebDataServiceWrapper>( browser_state_path, ApplicationContext::GetInstance()->GetApplicationLocale(), - base::CreateSingleThreadTaskRunnerWithTraits({web::WebThread::UI}), + base::CreateSingleThreadTaskRunner({web::WebThread::UI}), base::DoNothing()); }
diff --git a/jingle/notifier/listener/push_client_unittest.cc b/jingle/notifier/listener/push_client_unittest.cc index f563028..2cccfc9 100644 --- a/jingle/notifier/listener/push_client_unittest.cc +++ b/jingle/notifier/listener/push_client_unittest.cc
@@ -10,8 +10,8 @@ #include "base/bind_helpers.h" #include "base/compiler_specific.h" #include "base/location.h" -#include "base/message_loop/message_loop.h" #include "base/single_thread_task_runner.h" +#include "base/test/scoped_task_environment.h" #include "base/threading/thread.h" #include "jingle/glue/network_service_config_test_util.h" #include "jingle/notifier/base/notifier_options.h" @@ -27,14 +27,15 @@ PushClientTest() : net_config_helper_( base::MakeRefCounted<net::TestURLRequestContextGetter>( - message_loop_.task_runner())) { + scoped_task_environment_.GetMainThreadTaskRunner())) { net_config_helper_.FillInNetworkConfig(¬ifier_options_.network_config); } ~PushClientTest() override {} // The sockets created by the XMPP code expect an IO loop. - base::MessageLoopForIO message_loop_; + base::test::ScopedTaskEnvironment scoped_task_environment_{ + base::test::ScopedTaskEnvironment::MainThreadType::IO}; jingle_glue::NetworkServiceConfigTestUtil net_config_helper_; NotifierOptions notifier_options_; };
diff --git a/jingle/notifier/listener/xmpp_push_client_unittest.cc b/jingle/notifier/listener/xmpp_push_client_unittest.cc index 58d99095..e66f5786 100644 --- a/jingle/notifier/listener/xmpp_push_client_unittest.cc +++ b/jingle/notifier/listener/xmpp_push_client_unittest.cc
@@ -7,8 +7,8 @@ #include <memory> #include "base/compiler_specific.h" -#include "base/message_loop/message_loop.h" #include "base/run_loop.h" +#include "base/test/scoped_task_environment.h" #include "jingle/glue/network_service_config_test_util.h" #include "jingle/notifier/base/fake_base_task.h" #include "jingle/notifier/base/notifier_options.h" @@ -38,7 +38,7 @@ XmppPushClientTest() : net_config_helper_( base::MakeRefCounted<net::TestURLRequestContextGetter>( - message_loop_.task_runner())) { + scoped_task_environment_.GetMainThreadTaskRunner())) { net_config_helper_.FillInNetworkConfig(¬ifier_options_.network_config); } @@ -57,7 +57,8 @@ } // The sockets created by the XMPP code expect an IO loop. - base::MessageLoopForIO message_loop_; + base::test::ScopedTaskEnvironment scoped_task_environment_{ + base::test::ScopedTaskEnvironment::MainThreadType::IO}; jingle_glue::NetworkServiceConfigTestUtil net_config_helper_; NotifierOptions notifier_options_;
diff --git a/media/filters/decrypting_demuxer_stream.cc b/media/filters/decrypting_demuxer_stream.cc index 54eea04..b27967c 100644 --- a/media/filters/decrypting_demuxer_stream.cc +++ b/media/filters/decrypting_demuxer_stream.cc
@@ -31,11 +31,7 @@ const WaitingCB& waiting_cb) : task_runner_(task_runner), media_log_(media_log), - state_(kUninitialized), - waiting_cb_(waiting_cb), - demuxer_stream_(NULL), - decryptor_(NULL), - key_added_while_decrypt_pending_(false) {} + waiting_cb_(waiting_cb) {} std::string DecryptingDemuxerStream::GetDisplayName() const { return "DecryptingDemuxerStream"; @@ -84,8 +80,8 @@ read_cb_ = BindToCurrentLoop(read_cb); state_ = kPendingDemuxerRead; - demuxer_stream_->Read( - base::Bind(&DecryptingDemuxerStream::DecryptBuffer, weak_this_)); + demuxer_stream_->Read(base::Bind( + &DecryptingDemuxerStream::OnBufferReadFromDemuxerStream, weak_this_)); } bool DecryptingDemuxerStream::IsReadPending() const { @@ -104,8 +100,8 @@ // Reset() cannot complete if the read callback is still pending. // Defer the resetting process in this case. The |reset_cb_| will be fired - // after the read callback is fired - see DoDecryptBuffer() and - // DoDeliverBuffer(). + // after the read callback is fired - see OnBufferReadFromDemuxerStream() and + // OnBufferDecrypted(). if (state_ == kPendingDemuxerRead || state_ == kPendingDecrypt) { DCHECK(read_cb_); return; @@ -114,8 +110,8 @@ if (state_ == kWaitingForKey) { CompleteWaitingForDecryptionKey(); DCHECK(read_cb_); - pending_buffer_to_decrypt_ = NULL; - std::move(read_cb_).Run(kAborted, NULL); + pending_buffer_to_decrypt_ = nullptr; + std::move(read_cb_).Run(kAborted, nullptr); } DCHECK(!read_cb_); @@ -166,30 +162,30 @@ if (decryptor_) { decryptor_->CancelDecrypt(GetDecryptorStreamType()); - decryptor_ = NULL; + decryptor_ = nullptr; } if (init_cb_) std::move(init_cb_).Run(PIPELINE_ERROR_ABORT); if (read_cb_) - std::move(read_cb_).Run(kAborted, NULL); + std::move(read_cb_).Run(kAborted, nullptr); if (reset_cb_) std::move(reset_cb_).Run(); - pending_buffer_to_decrypt_ = NULL; + pending_buffer_to_decrypt_ = nullptr; } -void DecryptingDemuxerStream::DecryptBuffer( +void DecryptingDemuxerStream::OnBufferReadFromDemuxerStream( DemuxerStream::Status status, scoped_refptr<DecoderBuffer> buffer) { DVLOG(3) << __func__ << ": status = " << status; DCHECK(task_runner_->BelongsToCurrentThread()); DCHECK_EQ(state_, kPendingDemuxerRead) << state_; DCHECK(read_cb_); - DCHECK_EQ(buffer.get() != NULL, status == kOk) << status; + DCHECK_EQ(buffer.get() != nullptr, status == kOk) << status; // Even when |reset_cb_|, we need to pass |kConfigChanged| back to // the caller so that the downstream decoder can be properly reinitialized. if (status == kConfigChanged) { - DVLOG(2) << "DoDecryptBuffer() - kConfigChanged."; + DVLOG(2) << __func__ << ": config change"; DCHECK_EQ(demuxer_stream_->type() == AUDIO, audio_config_.IsValidConfig()); DCHECK_EQ(demuxer_stream_->type() == VIDEO, video_config_.IsValidConfig()); @@ -198,14 +194,14 @@ InitializeDecoderConfig(); state_ = kIdle; - std::move(read_cb_).Run(kConfigChanged, NULL); + std::move(read_cb_).Run(kConfigChanged, nullptr); if (reset_cb_) DoReset(); return; } if (reset_cb_) { - std::move(read_cb_).Run(kAborted, NULL); + std::move(read_cb_).Run(kAborted, nullptr); DoReset(); return; } @@ -223,14 +219,14 @@ DCHECK_EQ(kOk, status); if (buffer->end_of_stream()) { - DVLOG(2) << "DoDecryptBuffer() - EOS buffer."; + DVLOG(2) << __func__ << ": EOS buffer"; state_ = kIdle; std::move(read_cb_).Run(kOk, std::move(buffer)); return; } if (!buffer->decrypt_config()) { - DVLOG(2) << "DoDecryptBuffer() - clear buffer."; + DVLOG(2) << __func__ << ": clear buffer"; state_ = kIdle; std::move(read_cb_).Run(kOk, std::move(buffer)); return; @@ -252,10 +248,10 @@ decryptor_->Decrypt( GetDecryptorStreamType(), pending_buffer_to_decrypt_, BindToCurrentLoop( - base::Bind(&DecryptingDemuxerStream::DeliverBuffer, weak_this_))); + base::Bind(&DecryptingDemuxerStream::OnBufferDecrypted, weak_this_))); } -void DecryptingDemuxerStream::DeliverBuffer( +void DecryptingDemuxerStream::OnBufferDecrypted( Decryptor::Status status, scoped_refptr<DecoderBuffer> decrypted_buffer) { DVLOG(3) << __func__ << " - status: " << status; @@ -269,19 +265,19 @@ key_added_while_decrypt_pending_ = false; if (reset_cb_) { - pending_buffer_to_decrypt_ = NULL; - std::move(read_cb_).Run(kAborted, NULL); + pending_buffer_to_decrypt_ = nullptr; + std::move(read_cb_).Run(kAborted, nullptr); DoReset(); return; } - DCHECK_EQ(status == Decryptor::kSuccess, decrypted_buffer.get() != NULL); + DCHECK_EQ(status == Decryptor::kSuccess, decrypted_buffer.get() != nullptr); if (status == Decryptor::kError || status == Decryptor::kNeedMoreData) { DVLOG(2) << __func__ << ": Error with status " << status; MEDIA_LOG(ERROR, media_log_) << GetDisplayName() << ": decrypt error " << status; - pending_buffer_to_decrypt_ = NULL; + pending_buffer_to_decrypt_ = nullptr; state_ = kIdle; std::move(read_cb_).Run(kError, nullptr); return; @@ -319,7 +315,7 @@ if (pending_buffer_to_decrypt_->is_key_frame()) decrypted_buffer->set_is_key_frame(true); - pending_buffer_to_decrypt_ = NULL; + pending_buffer_to_decrypt_ = nullptr; state_ = kIdle; std::move(read_cb_).Run(kOk, std::move(decrypted_buffer)); } @@ -332,13 +328,15 @@ return; } - if (state_ == kWaitingForKey) { - CompleteWaitingForDecryptionKey(); - MEDIA_LOG(INFO, media_log_) - << GetDisplayName() << ": key was added, resuming decrypt"; - state_ = kPendingDecrypt; - DecryptPendingBuffer(); - } + // Nothing to do. + if (state_ != kWaitingForKey) + return; + + CompleteWaitingForDecryptionKey(); + MEDIA_LOG(INFO, media_log_) + << GetDisplayName() << ": key was added, resuming decrypt"; + state_ = kPendingDecrypt; + DecryptPendingBuffer(); } void DecryptingDemuxerStream::DoReset() { @@ -347,7 +345,6 @@ DCHECK(!read_cb_); state_ = kIdle; - std::move(reset_cb_).Run(); }
diff --git a/media/filters/decrypting_demuxer_stream.h b/media/filters/decrypting_demuxer_stream.h index 3a13a887..085995bd 100644 --- a/media/filters/decrypting_demuxer_stream.h +++ b/media/filters/decrypting_demuxer_stream.h
@@ -116,14 +116,14 @@ }; // Callback for DemuxerStream::Read(). - void DecryptBuffer(DemuxerStream::Status status, - scoped_refptr<DecoderBuffer> buffer); + void OnBufferReadFromDemuxerStream(DemuxerStream::Status status, + scoped_refptr<DecoderBuffer> buffer); void DecryptPendingBuffer(); // Callback for Decryptor::Decrypt(). - void DeliverBuffer(Decryptor::Status status, - scoped_refptr<DecoderBuffer> decrypted_buffer); + void OnBufferDecrypted(Decryptor::Status status, + scoped_refptr<DecoderBuffer> decrypted_buffer); // Callback for the |decryptor_| to notify this object that a new key has been // added. @@ -144,23 +144,22 @@ void CompleteWaitingForDecryptionKey(); scoped_refptr<base::SingleThreadTaskRunner> task_runner_; + MediaLog* const media_log_; + WaitingCB waiting_cb_; - MediaLog* media_log_; - - State state_; + State state_ = kUninitialized; PipelineStatusCB init_cb_; ReadCB read_cb_; base::Closure reset_cb_; - WaitingCB waiting_cb_; // Pointer to the input demuxer stream that will feed us encrypted buffers. - DemuxerStream* demuxer_stream_; + DemuxerStream* demuxer_stream_ = nullptr; AudioDecoderConfig audio_config_; VideoDecoderConfig video_config_; - Decryptor* decryptor_; + Decryptor* decryptor_ = nullptr; // The buffer returned by the demuxer that needs to be decrypted. scoped_refptr<media::DecoderBuffer> pending_buffer_to_decrypt_; @@ -169,7 +168,7 @@ // (in other words, this variable can only be set in state kPendingDecrypt). // If this variable is true and kNoKey is returned then we need to try // decrypting again in case the newly added key is the correct decryption key. - bool key_added_while_decrypt_pending_; + bool key_added_while_decrypt_pending_ = false; base::WeakPtr<DecryptingDemuxerStream> weak_this_; base::WeakPtrFactory<DecryptingDemuxerStream> weak_factory_{this};
diff --git a/media/gpu/v4l2/BUILD.gn b/media/gpu/v4l2/BUILD.gn index f459fd33..8aa4cf9f 100644 --- a/media/gpu/v4l2/BUILD.gn +++ b/media/gpu/v4l2/BUILD.gn
@@ -35,6 +35,8 @@ "v4l2_device.h", "v4l2_h264_accelerator.cc", "v4l2_h264_accelerator.h", + "v4l2_h264_accelerator_legacy.cc", + "v4l2_h264_accelerator_legacy.h", "v4l2_image_processor.cc", "v4l2_image_processor.h", "v4l2_slice_video_decode_accelerator.cc",
diff --git a/media/gpu/v4l2/v4l2_device.cc b/media/gpu/v4l2/v4l2_device.cc index e557b88..474f5414 100644 --- a/media/gpu/v4l2/v4l2_device.cc +++ b/media/gpu/v4l2/v4l2_device.cc
@@ -1015,6 +1015,10 @@ // we map V4L2_PIX_FMT_MT21C to PIXEL_FORMAT_NV12 as their layout are the // same. case V4L2_PIX_FMT_MT21C: + // V4L2_PIX_FMT_MM21 is used for MT8183 hardware video decoder. It is + // similar to V4L2_PIX_FMT_MT21C but is not compressed ; thus it can also + // be mapped to PIXEL_FORMAT_NV12. + case V4L2_PIX_FMT_MM21: return PIXEL_FORMAT_NV12; case V4L2_PIX_FMT_YUV420: @@ -1519,8 +1523,8 @@ // static bool V4L2Device::IsMultiPlanarV4L2PixFmt(uint32_t pix_fmt) { constexpr uint32_t kMultiV4L2PixFmts[] = { - V4L2_PIX_FMT_NV12M, V4L2_PIX_FMT_MT21C, V4L2_PIX_FMT_YUV420M, - V4L2_PIX_FMT_YVU420M, V4L2_PIX_FMT_YUV422M, + V4L2_PIX_FMT_NV12M, V4L2_PIX_FMT_MT21C, V4L2_PIX_FMT_MM21, + V4L2_PIX_FMT_YUV420M, V4L2_PIX_FMT_YVU420M, V4L2_PIX_FMT_YUV422M, }; return std::find(std::cbegin(kMultiV4L2PixFmts), std::cend(kMultiV4L2PixFmts), pix_fmt) != std::cend(kMultiV4L2PixFmts);
diff --git a/media/gpu/v4l2/v4l2_device.h b/media/gpu/v4l2/v4l2_device.h index 0df7ff5..8ecdff38 100644 --- a/media/gpu/v4l2/v4l2_device.h +++ b/media/gpu/v4l2/v4l2_device.h
@@ -41,6 +41,12 @@ #define V4L2_CID_JPEG_CHROMA_QUANTIZATION (V4L2_CID_JPEG_CLASS_BASE + 6) #endif +// TODO(b/132589320): remove this once V4L2 header is updated. +#ifndef V4L2_PIX_FMT_MM21 +// MTK 8-bit block mode, two non-contiguous planes. +#define V4L2_PIX_FMT_MM21 v4l2_fourcc('M', 'M', '2', '1') +#endif + namespace media { class V4L2Queue;
diff --git a/media/gpu/v4l2/v4l2_h264_accelerator.cc b/media/gpu/v4l2/v4l2_h264_accelerator.cc index 54b89244..f64586f 100644 --- a/media/gpu/v4l2/v4l2_h264_accelerator.cc +++ b/media/gpu/v4l2/v4l2_h264_accelerator.cc
@@ -4,6 +4,12 @@ #include "media/gpu/v4l2/v4l2_h264_accelerator.h" +// TODO(987856): prevent legacy headers being included from videodev2.h until +// v4.14 +// support is deprecated. +#define _H264_CTRLS_LEGACY_H_ + +#include <linux/media/h264-ctrls.h> #include <linux/videodev2.h> #include <type_traits> @@ -23,8 +29,8 @@ // TODO(posciak): This should be queried from hardware once supported. static constexpr size_t kMaxSlices = 16; - struct v4l2_ctrl_h264_slice_param v4l2_slice_params[kMaxSlices]; - struct v4l2_ctrl_h264_decode_param v4l2_decode_param; + struct v4l2_ctrl_h264_slice_params v4l2_slice_params[kMaxSlices]; + struct v4l2_ctrl_h264_decode_params v4l2_decode_param; }; class V4L2H264Picture : public H264Picture { @@ -97,7 +103,7 @@ } struct v4l2_h264_dpb_entry& entry = priv_->v4l2_decode_param.dpb[i++]; - entry.buf_index = index; + entry.reference_ts = index; entry.frame_num = pic->frame_num; entry.pic_num = pic->pic_num; entry.top_field_order_cnt = pic->top_field_order_cnt; @@ -306,7 +312,7 @@ return Status::kFail; } - struct v4l2_ctrl_h264_slice_param& v4l2_slice_param = + struct v4l2_ctrl_h264_slice_params& v4l2_slice_param = priv_->v4l2_slice_params[num_slices_++]; memset(&v4l2_slice_param, 0, sizeof(v4l2_slice_param)); @@ -338,11 +344,12 @@ #define SET_V4L2_SPARM_FLAG_IF(cond, flag) \ v4l2_slice_param.flags |= ((slice_hdr->cond) ? (flag) : 0) - SET_V4L2_SPARM_FLAG_IF(field_pic_flag, V4L2_SLICE_FLAG_FIELD_PIC); - SET_V4L2_SPARM_FLAG_IF(bottom_field_flag, V4L2_SLICE_FLAG_BOTTOM_FIELD); + SET_V4L2_SPARM_FLAG_IF(field_pic_flag, V4L2_H264_SLICE_FLAG_FIELD_PIC); + SET_V4L2_SPARM_FLAG_IF(bottom_field_flag, V4L2_H264_SLICE_FLAG_BOTTOM_FIELD); SET_V4L2_SPARM_FLAG_IF(direct_spatial_mv_pred_flag, - V4L2_SLICE_FLAG_DIRECT_SPATIAL_MV_PRED); - SET_V4L2_SPARM_FLAG_IF(sp_for_switch_flag, V4L2_SLICE_FLAG_SP_FOR_SWITCH); + V4L2_H264_SLICE_FLAG_DIRECT_SPATIAL_MV_PRED); + SET_V4L2_SPARM_FLAG_IF(sp_for_switch_flag, + V4L2_H264_SLICE_FLAG_SP_FOR_SWITCH); #undef SET_V4L2_SPARM_FLAG_IF struct v4l2_h264_pred_weight_table* pred_weight_table = @@ -422,7 +429,9 @@ H264PictureToV4L2DecodeSurface(pic.get()); priv_->v4l2_decode_param.num_slices = num_slices_; - priv_->v4l2_decode_param.idr_pic_flag = pic->idr; + if (pic->idr) { + priv_->v4l2_decode_param.flags |= 1; + } priv_->v4l2_decode_param.top_field_order_cnt = pic->top_field_order_cnt; priv_->v4l2_decode_param.bottom_field_order_cnt = pic->bottom_field_order_cnt; @@ -430,13 +439,13 @@ std::vector<struct v4l2_ext_control> ctrls; memset(&ctrl, 0, sizeof(ctrl)); - ctrl.id = V4L2_CID_MPEG_VIDEO_H264_SLICE_PARAM; + ctrl.id = V4L2_CID_MPEG_VIDEO_H264_SLICE_PARAMS; ctrl.size = sizeof(priv_->v4l2_slice_params); ctrl.ptr = priv_->v4l2_slice_params; ctrls.push_back(ctrl); memset(&ctrl, 0, sizeof(ctrl)); - ctrl.id = V4L2_CID_MPEG_VIDEO_H264_DECODE_PARAM; + ctrl.id = V4L2_CID_MPEG_VIDEO_H264_DECODE_PARAMS; ctrl.size = sizeof(priv_->v4l2_decode_param); ctrl.ptr = &priv_->v4l2_decode_param; ctrls.push_back(ctrl);
diff --git a/media/gpu/v4l2/v4l2_h264_accelerator_legacy.cc b/media/gpu/v4l2/v4l2_h264_accelerator_legacy.cc new file mode 100644 index 0000000..d33b983 --- /dev/null +++ b/media/gpu/v4l2/v4l2_h264_accelerator_legacy.cc
@@ -0,0 +1,484 @@ +// Copyright 2019 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "media/gpu/v4l2/v4l2_h264_accelerator_legacy.h" + +#include <linux/media/h264-ctrls-legacy.h> +#include <linux/videodev2.h> +#include <type_traits> + +#include "base/logging.h" +#include "base/stl_util.h" +#include "media/gpu/macros.h" +#include "media/gpu/v4l2/v4l2_decode_surface.h" +#include "media/gpu/v4l2/v4l2_decode_surface_handler.h" +#include "media/gpu/v4l2/v4l2_device.h" + +namespace media { + +// This struct contains the kernel-specific parts of the H264 acceleration, +// that we don't want to expose in the .h file since they may differ from +// upstream. +struct V4L2LegacyH264AcceleratorPrivate { + // TODO(posciak): This should be queried from hardware once supported. + static constexpr size_t kMaxSlices = 16; + + struct v4l2_ctrl_h264_slice_param v4l2_slice_params[kMaxSlices]; + struct v4l2_ctrl_h264_decode_param v4l2_decode_param; +}; + +class V4L2H264Picture : public H264Picture { + public: + explicit V4L2H264Picture(const scoped_refptr<V4L2DecodeSurface>& dec_surface) + : dec_surface_(dec_surface) {} + + V4L2H264Picture* AsV4L2H264Picture() override { return this; } + scoped_refptr<V4L2DecodeSurface> dec_surface() { return dec_surface_; } + + private: + ~V4L2H264Picture() override {} + + scoped_refptr<V4L2DecodeSurface> dec_surface_; + + DISALLOW_COPY_AND_ASSIGN(V4L2H264Picture); +}; + +V4L2LegacyH264Accelerator::V4L2LegacyH264Accelerator( + V4L2DecodeSurfaceHandler* surface_handler, + V4L2Device* device) + : num_slices_(0), + surface_handler_(surface_handler), + device_(device), + priv_(std::make_unique<V4L2LegacyH264AcceleratorPrivate>()) { + DCHECK(surface_handler_); +} + +V4L2LegacyH264Accelerator::~V4L2LegacyH264Accelerator() {} + +scoped_refptr<H264Picture> V4L2LegacyH264Accelerator::CreateH264Picture() { + scoped_refptr<V4L2DecodeSurface> dec_surface = + surface_handler_->CreateSurface(); + if (!dec_surface) + return nullptr; + + return new V4L2H264Picture(dec_surface); +} + +void V4L2LegacyH264Accelerator::H264PictureListToDPBIndicesList( + const H264Picture::Vector& src_pic_list, + uint8_t dst_list[kDPBIndicesListSize]) { + size_t i; + for (i = 0; i < src_pic_list.size() && i < kDPBIndicesListSize; ++i) { + const scoped_refptr<H264Picture>& pic = src_pic_list[i]; + dst_list[i] = pic ? pic->dpb_position : VIDEO_MAX_FRAME; + } + + while (i < kDPBIndicesListSize) + dst_list[i++] = VIDEO_MAX_FRAME; +} + +void V4L2LegacyH264Accelerator::H264DPBToV4L2DPB( + const H264DPB& dpb, + std::vector<scoped_refptr<V4L2DecodeSurface>>* ref_surfaces) { + memset(priv_->v4l2_decode_param.dpb, 0, sizeof(priv_->v4l2_decode_param.dpb)); + size_t i = 0; + for (const auto& pic : dpb) { + if (i >= base::size(priv_->v4l2_decode_param.dpb)) { + VLOGF(1) << "Invalid DPB size"; + break; + } + + int index = VIDEO_MAX_FRAME; + if (!pic->nonexisting) { + scoped_refptr<V4L2DecodeSurface> dec_surface = + H264PictureToV4L2DecodeSurface(pic.get()); + index = dec_surface->GetReferenceID(); + ref_surfaces->push_back(dec_surface); + } + + struct v4l2_h264_dpb_entry& entry = priv_->v4l2_decode_param.dpb[i++]; + entry.buf_index = index; + entry.frame_num = pic->frame_num; + entry.pic_num = pic->pic_num; + entry.top_field_order_cnt = pic->top_field_order_cnt; + entry.bottom_field_order_cnt = pic->bottom_field_order_cnt; + entry.flags = (pic->ref ? V4L2_H264_DPB_ENTRY_FLAG_ACTIVE : 0) | + (pic->long_term ? V4L2_H264_DPB_ENTRY_FLAG_LONG_TERM : 0); + } +} + +H264Decoder::H264Accelerator::Status +V4L2LegacyH264Accelerator::SubmitFrameMetadata( + const H264SPS* sps, + const H264PPS* pps, + const H264DPB& dpb, + const H264Picture::Vector& ref_pic_listp0, + const H264Picture::Vector& ref_pic_listb0, + const H264Picture::Vector& ref_pic_listb1, + scoped_refptr<H264Picture> pic) { + struct v4l2_ext_control ctrl; + std::vector<struct v4l2_ext_control> ctrls; + + struct v4l2_ctrl_h264_sps v4l2_sps; + memset(&v4l2_sps, 0, sizeof(v4l2_sps)); + v4l2_sps.constraint_set_flags = + (sps->constraint_set0_flag ? V4L2_H264_SPS_CONSTRAINT_SET0_FLAG : 0) | + (sps->constraint_set1_flag ? V4L2_H264_SPS_CONSTRAINT_SET1_FLAG : 0) | + (sps->constraint_set2_flag ? V4L2_H264_SPS_CONSTRAINT_SET2_FLAG : 0) | + (sps->constraint_set3_flag ? V4L2_H264_SPS_CONSTRAINT_SET3_FLAG : 0) | + (sps->constraint_set4_flag ? V4L2_H264_SPS_CONSTRAINT_SET4_FLAG : 0) | + (sps->constraint_set5_flag ? V4L2_H264_SPS_CONSTRAINT_SET5_FLAG : 0); +#define SPS_TO_V4L2SPS(a) v4l2_sps.a = sps->a + SPS_TO_V4L2SPS(profile_idc); + SPS_TO_V4L2SPS(level_idc); + SPS_TO_V4L2SPS(seq_parameter_set_id); + SPS_TO_V4L2SPS(chroma_format_idc); + SPS_TO_V4L2SPS(bit_depth_luma_minus8); + SPS_TO_V4L2SPS(bit_depth_chroma_minus8); + SPS_TO_V4L2SPS(log2_max_frame_num_minus4); + SPS_TO_V4L2SPS(pic_order_cnt_type); + SPS_TO_V4L2SPS(log2_max_pic_order_cnt_lsb_minus4); + SPS_TO_V4L2SPS(offset_for_non_ref_pic); + SPS_TO_V4L2SPS(offset_for_top_to_bottom_field); + SPS_TO_V4L2SPS(num_ref_frames_in_pic_order_cnt_cycle); + + static_assert(std::extent<decltype(v4l2_sps.offset_for_ref_frame)>() == + std::extent<decltype(sps->offset_for_ref_frame)>(), + "offset_for_ref_frame arrays must be same size"); + for (size_t i = 0; i < base::size(v4l2_sps.offset_for_ref_frame); ++i) + v4l2_sps.offset_for_ref_frame[i] = sps->offset_for_ref_frame[i]; + SPS_TO_V4L2SPS(max_num_ref_frames); + SPS_TO_V4L2SPS(pic_width_in_mbs_minus1); + SPS_TO_V4L2SPS(pic_height_in_map_units_minus1); +#undef SPS_TO_V4L2SPS + +#define SET_V4L2_SPS_FLAG_IF(cond, flag) \ + v4l2_sps.flags |= ((sps->cond) ? (flag) : 0) + SET_V4L2_SPS_FLAG_IF(separate_colour_plane_flag, + V4L2_H264_SPS_FLAG_SEPARATE_COLOUR_PLANE); + SET_V4L2_SPS_FLAG_IF(qpprime_y_zero_transform_bypass_flag, + V4L2_H264_SPS_FLAG_QPPRIME_Y_ZERO_TRANSFORM_BYPASS); + SET_V4L2_SPS_FLAG_IF(delta_pic_order_always_zero_flag, + V4L2_H264_SPS_FLAG_DELTA_PIC_ORDER_ALWAYS_ZERO); + SET_V4L2_SPS_FLAG_IF(gaps_in_frame_num_value_allowed_flag, + V4L2_H264_SPS_FLAG_GAPS_IN_FRAME_NUM_VALUE_ALLOWED); + SET_V4L2_SPS_FLAG_IF(frame_mbs_only_flag, V4L2_H264_SPS_FLAG_FRAME_MBS_ONLY); + SET_V4L2_SPS_FLAG_IF(mb_adaptive_frame_field_flag, + V4L2_H264_SPS_FLAG_MB_ADAPTIVE_FRAME_FIELD); + SET_V4L2_SPS_FLAG_IF(direct_8x8_inference_flag, + V4L2_H264_SPS_FLAG_DIRECT_8X8_INFERENCE); +#undef SET_V4L2_SPS_FLAG_IF + memset(&ctrl, 0, sizeof(ctrl)); + ctrl.id = V4L2_CID_MPEG_VIDEO_H264_SPS; + ctrl.size = sizeof(v4l2_sps); + ctrl.ptr = &v4l2_sps; + ctrls.push_back(ctrl); + + struct v4l2_ctrl_h264_pps v4l2_pps; + memset(&v4l2_pps, 0, sizeof(v4l2_pps)); +#define PPS_TO_V4L2PPS(a) v4l2_pps.a = pps->a + PPS_TO_V4L2PPS(pic_parameter_set_id); + PPS_TO_V4L2PPS(seq_parameter_set_id); + PPS_TO_V4L2PPS(num_slice_groups_minus1); + PPS_TO_V4L2PPS(num_ref_idx_l0_default_active_minus1); + PPS_TO_V4L2PPS(num_ref_idx_l1_default_active_minus1); + PPS_TO_V4L2PPS(weighted_bipred_idc); + PPS_TO_V4L2PPS(pic_init_qp_minus26); + PPS_TO_V4L2PPS(pic_init_qs_minus26); + PPS_TO_V4L2PPS(chroma_qp_index_offset); + PPS_TO_V4L2PPS(second_chroma_qp_index_offset); +#undef PPS_TO_V4L2PPS + +#define SET_V4L2_PPS_FLAG_IF(cond, flag) \ + v4l2_pps.flags |= ((pps->cond) ? (flag) : 0) + SET_V4L2_PPS_FLAG_IF(entropy_coding_mode_flag, + V4L2_H264_PPS_FLAG_ENTROPY_CODING_MODE); + SET_V4L2_PPS_FLAG_IF( + bottom_field_pic_order_in_frame_present_flag, + V4L2_H264_PPS_FLAG_BOTTOM_FIELD_PIC_ORDER_IN_FRAME_PRESENT); + SET_V4L2_PPS_FLAG_IF(weighted_pred_flag, V4L2_H264_PPS_FLAG_WEIGHTED_PRED); + SET_V4L2_PPS_FLAG_IF(deblocking_filter_control_present_flag, + V4L2_H264_PPS_FLAG_DEBLOCKING_FILTER_CONTROL_PRESENT); + SET_V4L2_PPS_FLAG_IF(constrained_intra_pred_flag, + V4L2_H264_PPS_FLAG_CONSTRAINED_INTRA_PRED); + SET_V4L2_PPS_FLAG_IF(redundant_pic_cnt_present_flag, + V4L2_H264_PPS_FLAG_REDUNDANT_PIC_CNT_PRESENT); + SET_V4L2_PPS_FLAG_IF(transform_8x8_mode_flag, + V4L2_H264_PPS_FLAG_TRANSFORM_8X8_MODE); + SET_V4L2_PPS_FLAG_IF(pic_scaling_matrix_present_flag, + V4L2_H264_PPS_FLAG_PIC_SCALING_MATRIX_PRESENT); +#undef SET_V4L2_PPS_FLAG_IF + memset(&ctrl, 0, sizeof(ctrl)); + ctrl.id = V4L2_CID_MPEG_VIDEO_H264_PPS; + ctrl.size = sizeof(v4l2_pps); + ctrl.ptr = &v4l2_pps; + ctrls.push_back(ctrl); + + struct v4l2_ctrl_h264_scaling_matrix v4l2_scaling_matrix; + memset(&v4l2_scaling_matrix, 0, sizeof(v4l2_scaling_matrix)); + + static_assert( + std::extent<decltype(v4l2_scaling_matrix.scaling_list_4x4)>() <= + std::extent<decltype(pps->scaling_list4x4)>() && + std::extent<decltype(v4l2_scaling_matrix.scaling_list_4x4[0])>() <= + std::extent<decltype(pps->scaling_list4x4[0])>() && + std::extent<decltype(v4l2_scaling_matrix.scaling_list_8x8)>() <= + std::extent<decltype(pps->scaling_list8x8)>() && + std::extent<decltype(v4l2_scaling_matrix.scaling_list_8x8[0])>() <= + std::extent<decltype(pps->scaling_list8x8[0])>(), + "scaling_lists must be of correct size"); + static_assert( + std::extent<decltype(v4l2_scaling_matrix.scaling_list_4x4)>() <= + std::extent<decltype(sps->scaling_list4x4)>() && + std::extent<decltype(v4l2_scaling_matrix.scaling_list_4x4[0])>() <= + std::extent<decltype(sps->scaling_list4x4[0])>() && + std::extent<decltype(v4l2_scaling_matrix.scaling_list_8x8)>() <= + std::extent<decltype(sps->scaling_list8x8)>() && + std::extent<decltype(v4l2_scaling_matrix.scaling_list_8x8[0])>() <= + std::extent<decltype(sps->scaling_list8x8[0])>(), + "scaling_lists must be of correct size"); + + const auto* scaling_list4x4 = &sps->scaling_list4x4[0]; + const auto* scaling_list8x8 = &sps->scaling_list8x8[0]; + if (pps->pic_scaling_matrix_present_flag) { + scaling_list4x4 = &pps->scaling_list4x4[0]; + scaling_list8x8 = &pps->scaling_list8x8[0]; + } + + for (size_t i = 0; i < base::size(v4l2_scaling_matrix.scaling_list_4x4); + ++i) { + for (size_t j = 0; j < base::size(v4l2_scaling_matrix.scaling_list_4x4[i]); + ++j) { + v4l2_scaling_matrix.scaling_list_4x4[i][j] = scaling_list4x4[i][j]; + } + } + for (size_t i = 0; i < base::size(v4l2_scaling_matrix.scaling_list_8x8); + ++i) { + for (size_t j = 0; j < base::size(v4l2_scaling_matrix.scaling_list_8x8[i]); + ++j) { + v4l2_scaling_matrix.scaling_list_8x8[i][j] = scaling_list8x8[i][j]; + } + } + + memset(&ctrl, 0, sizeof(ctrl)); + ctrl.id = V4L2_CID_MPEG_VIDEO_H264_SCALING_MATRIX; + ctrl.size = sizeof(v4l2_scaling_matrix); + ctrl.ptr = &v4l2_scaling_matrix; + ctrls.push_back(ctrl); + + scoped_refptr<V4L2DecodeSurface> dec_surface = + H264PictureToV4L2DecodeSurface(pic.get()); + + struct v4l2_ext_controls ext_ctrls; + memset(&ext_ctrls, 0, sizeof(ext_ctrls)); + ext_ctrls.count = ctrls.size(); + ext_ctrls.controls = &ctrls[0]; + dec_surface->PrepareSetCtrls(&ext_ctrls); + if (device_->Ioctl(VIDIOC_S_EXT_CTRLS, &ext_ctrls) != 0) { + VPLOGF(1) << "ioctl() failed: VIDIOC_S_EXT_CTRLS"; + return Status::kFail; + } + + H264PictureListToDPBIndicesList(ref_pic_listp0, + priv_->v4l2_decode_param.ref_pic_list_p0); + H264PictureListToDPBIndicesList(ref_pic_listb0, + priv_->v4l2_decode_param.ref_pic_list_b0); + H264PictureListToDPBIndicesList(ref_pic_listb1, + priv_->v4l2_decode_param.ref_pic_list_b1); + + std::vector<scoped_refptr<V4L2DecodeSurface>> ref_surfaces; + H264DPBToV4L2DPB(dpb, &ref_surfaces); + dec_surface->SetReferenceSurfaces(ref_surfaces); + + return Status::kOk; +} + +H264Decoder::H264Accelerator::Status V4L2LegacyH264Accelerator::SubmitSlice( + const H264PPS* pps, + const H264SliceHeader* slice_hdr, + const H264Picture::Vector& ref_pic_list0, + const H264Picture::Vector& ref_pic_list1, + scoped_refptr<H264Picture> pic, + const uint8_t* data, + size_t size, + const std::vector<SubsampleEntry>& subsamples) { + if (num_slices_ == priv_->kMaxSlices) { + VLOGF(1) << "Over limit of supported slices per frame"; + return Status::kFail; + } + + struct v4l2_ctrl_h264_slice_param& v4l2_slice_param = + priv_->v4l2_slice_params[num_slices_++]; + memset(&v4l2_slice_param, 0, sizeof(v4l2_slice_param)); + + v4l2_slice_param.size = size; +#define SHDR_TO_V4L2SPARM(a) v4l2_slice_param.a = slice_hdr->a + SHDR_TO_V4L2SPARM(header_bit_size); + SHDR_TO_V4L2SPARM(first_mb_in_slice); + SHDR_TO_V4L2SPARM(slice_type); + SHDR_TO_V4L2SPARM(pic_parameter_set_id); + SHDR_TO_V4L2SPARM(colour_plane_id); + SHDR_TO_V4L2SPARM(frame_num); + SHDR_TO_V4L2SPARM(idr_pic_id); + SHDR_TO_V4L2SPARM(pic_order_cnt_lsb); + SHDR_TO_V4L2SPARM(delta_pic_order_cnt_bottom); + SHDR_TO_V4L2SPARM(delta_pic_order_cnt0); + SHDR_TO_V4L2SPARM(delta_pic_order_cnt1); + SHDR_TO_V4L2SPARM(redundant_pic_cnt); + SHDR_TO_V4L2SPARM(dec_ref_pic_marking_bit_size); + SHDR_TO_V4L2SPARM(cabac_init_idc); + SHDR_TO_V4L2SPARM(slice_qp_delta); + SHDR_TO_V4L2SPARM(slice_qs_delta); + SHDR_TO_V4L2SPARM(disable_deblocking_filter_idc); + SHDR_TO_V4L2SPARM(slice_alpha_c0_offset_div2); + SHDR_TO_V4L2SPARM(slice_beta_offset_div2); + SHDR_TO_V4L2SPARM(num_ref_idx_l0_active_minus1); + SHDR_TO_V4L2SPARM(num_ref_idx_l1_active_minus1); + SHDR_TO_V4L2SPARM(pic_order_cnt_bit_size); +#undef SHDR_TO_V4L2SPARM + +#define SET_V4L2_SPARM_FLAG_IF(cond, flag) \ + v4l2_slice_param.flags |= ((slice_hdr->cond) ? (flag) : 0) + SET_V4L2_SPARM_FLAG_IF(field_pic_flag, V4L2_SLICE_FLAG_FIELD_PIC); + SET_V4L2_SPARM_FLAG_IF(bottom_field_flag, V4L2_SLICE_FLAG_BOTTOM_FIELD); + SET_V4L2_SPARM_FLAG_IF(direct_spatial_mv_pred_flag, + V4L2_SLICE_FLAG_DIRECT_SPATIAL_MV_PRED); + SET_V4L2_SPARM_FLAG_IF(sp_for_switch_flag, V4L2_SLICE_FLAG_SP_FOR_SWITCH); +#undef SET_V4L2_SPARM_FLAG_IF + + struct v4l2_h264_pred_weight_table* pred_weight_table = + &v4l2_slice_param.pred_weight_table; + + if (((slice_hdr->IsPSlice() || slice_hdr->IsSPSlice()) && + pps->weighted_pred_flag) || + (slice_hdr->IsBSlice() && pps->weighted_bipred_idc == 1)) { + pred_weight_table->luma_log2_weight_denom = + slice_hdr->luma_log2_weight_denom; + pred_weight_table->chroma_log2_weight_denom = + slice_hdr->chroma_log2_weight_denom; + + struct v4l2_h264_weight_factors* factorsl0 = + &pred_weight_table->weight_factors[0]; + + for (int i = 0; i < 32; ++i) { + factorsl0->luma_weight[i] = + slice_hdr->pred_weight_table_l0.luma_weight[i]; + factorsl0->luma_offset[i] = + slice_hdr->pred_weight_table_l0.luma_offset[i]; + + for (int j = 0; j < 2; ++j) { + factorsl0->chroma_weight[i][j] = + slice_hdr->pred_weight_table_l0.chroma_weight[i][j]; + factorsl0->chroma_offset[i][j] = + slice_hdr->pred_weight_table_l0.chroma_offset[i][j]; + } + } + + if (slice_hdr->IsBSlice()) { + struct v4l2_h264_weight_factors* factorsl1 = + &pred_weight_table->weight_factors[1]; + + for (int i = 0; i < 32; ++i) { + factorsl1->luma_weight[i] = + slice_hdr->pred_weight_table_l1.luma_weight[i]; + factorsl1->luma_offset[i] = + slice_hdr->pred_weight_table_l1.luma_offset[i]; + + for (int j = 0; j < 2; ++j) { + factorsl1->chroma_weight[i][j] = + slice_hdr->pred_weight_table_l1.chroma_weight[i][j]; + factorsl1->chroma_offset[i][j] = + slice_hdr->pred_weight_table_l1.chroma_offset[i][j]; + } + } + } + } + + H264PictureListToDPBIndicesList(ref_pic_list0, + v4l2_slice_param.ref_pic_list0); + H264PictureListToDPBIndicesList(ref_pic_list1, + v4l2_slice_param.ref_pic_list1); + + scoped_refptr<V4L2DecodeSurface> dec_surface = + H264PictureToV4L2DecodeSurface(pic.get()); + + priv_->v4l2_decode_param.nal_ref_idc = slice_hdr->nal_ref_idc; + + // TODO(posciak): Don't add start code back here, but have it passed from + // the parser. + size_t data_copy_size = size + 3; + std::unique_ptr<uint8_t[]> data_copy(new uint8_t[data_copy_size]); + memset(data_copy.get(), 0, data_copy_size); + data_copy[2] = 0x01; + memcpy(data_copy.get() + 3, data, size); + return surface_handler_->SubmitSlice(dec_surface, data_copy.get(), + data_copy_size) + ? Status::kOk + : Status::kFail; +} + +H264Decoder::H264Accelerator::Status V4L2LegacyH264Accelerator::SubmitDecode( + scoped_refptr<H264Picture> pic) { + scoped_refptr<V4L2DecodeSurface> dec_surface = + H264PictureToV4L2DecodeSurface(pic.get()); + + priv_->v4l2_decode_param.num_slices = num_slices_; + priv_->v4l2_decode_param.idr_pic_flag = pic->idr; + priv_->v4l2_decode_param.top_field_order_cnt = pic->top_field_order_cnt; + priv_->v4l2_decode_param.bottom_field_order_cnt = pic->bottom_field_order_cnt; + + struct v4l2_ext_control ctrl; + std::vector<struct v4l2_ext_control> ctrls; + + memset(&ctrl, 0, sizeof(ctrl)); + ctrl.id = V4L2_CID_MPEG_VIDEO_H264_SLICE_PARAM; + ctrl.size = sizeof(priv_->v4l2_slice_params); + ctrl.ptr = priv_->v4l2_slice_params; + ctrls.push_back(ctrl); + + memset(&ctrl, 0, sizeof(ctrl)); + ctrl.id = V4L2_CID_MPEG_VIDEO_H264_DECODE_PARAM; + ctrl.size = sizeof(priv_->v4l2_decode_param); + ctrl.ptr = &priv_->v4l2_decode_param; + ctrls.push_back(ctrl); + + struct v4l2_ext_controls ext_ctrls; + memset(&ext_ctrls, 0, sizeof(ext_ctrls)); + ext_ctrls.count = ctrls.size(); + ext_ctrls.controls = &ctrls[0]; + dec_surface->PrepareSetCtrls(&ext_ctrls); + if (device_->Ioctl(VIDIOC_S_EXT_CTRLS, &ext_ctrls) != 0) { + VPLOGF(1) << "ioctl() failed: VIDIOC_S_EXT_CTRLS"; + return Status::kFail; + } + + Reset(); + + DVLOGF(4) << "Submitting decode for surface: " << dec_surface->ToString(); + surface_handler_->DecodeSurface(dec_surface); + return Status::kOk; +} + +bool V4L2LegacyH264Accelerator::OutputPicture(scoped_refptr<H264Picture> pic) { + // TODO(crbug.com/647725): Insert correct color space. + surface_handler_->SurfaceReady(H264PictureToV4L2DecodeSurface(pic.get()), + pic->bitstream_id(), pic->visible_rect(), + VideoColorSpace()); + return true; +} + +void V4L2LegacyH264Accelerator::Reset() { + num_slices_ = 0; + memset(&priv_->v4l2_decode_param, 0, sizeof(priv_->v4l2_decode_param)); + memset(&priv_->v4l2_slice_params, 0, sizeof(priv_->v4l2_slice_params)); +} + +scoped_refptr<V4L2DecodeSurface> +V4L2LegacyH264Accelerator::H264PictureToV4L2DecodeSurface(H264Picture* pic) { + V4L2H264Picture* v4l2_pic = pic->AsV4L2H264Picture(); + CHECK(v4l2_pic); + return v4l2_pic->dec_surface(); +} + +} // namespace media
diff --git a/media/gpu/v4l2/v4l2_h264_accelerator_legacy.h b/media/gpu/v4l2/v4l2_h264_accelerator_legacy.h new file mode 100644 index 0000000..8bad8864 --- /dev/null +++ b/media/gpu/v4l2/v4l2_h264_accelerator_legacy.h
@@ -0,0 +1,77 @@ +// Copyright 2019 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef MEDIA_GPU_V4L2_V4L2_H264_ACCELERATOR_LEGACY_H_ +#define MEDIA_GPU_V4L2_V4L2_H264_ACCELERATOR_LEGACY_H_ + +#include <memory> +#include <vector> + +#include "base/macros.h" +#include "base/memory/scoped_refptr.h" +#include "media/gpu/h264_decoder.h" +#include "media/gpu/h264_dpb.h" + +namespace media { + +class V4L2Device; +class V4L2DecodeSurface; +class V4L2DecodeSurfaceHandler; +struct V4L2LegacyH264AcceleratorPrivate; + +class V4L2LegacyH264Accelerator : public H264Decoder::H264Accelerator { + public: + using Status = H264Decoder::H264Accelerator::Status; + + explicit V4L2LegacyH264Accelerator(V4L2DecodeSurfaceHandler* surface_handler, + V4L2Device* device); + ~V4L2LegacyH264Accelerator() override; + + // H264Decoder::H264Accelerator implementation. + scoped_refptr<H264Picture> CreateH264Picture() override; + Status SubmitFrameMetadata(const H264SPS* sps, + const H264PPS* pps, + const H264DPB& dpb, + const H264Picture::Vector& ref_pic_listp0, + const H264Picture::Vector& ref_pic_listb0, + const H264Picture::Vector& ref_pic_listb1, + scoped_refptr<H264Picture> pic) override; + Status SubmitSlice(const H264PPS* pps, + const H264SliceHeader* slice_hdr, + const H264Picture::Vector& ref_pic_list0, + const H264Picture::Vector& ref_pic_list1, + scoped_refptr<H264Picture> pic, + const uint8_t* data, + size_t size, + const std::vector<SubsampleEntry>& subsamples) override; + Status SubmitDecode(scoped_refptr<H264Picture> pic) override; + bool OutputPicture(scoped_refptr<H264Picture> pic) override; + void Reset() override; + + private: + // Max size of reference list. + static constexpr size_t kDPBIndicesListSize = 32; + + void H264PictureListToDPBIndicesList(const H264Picture::Vector& src_pic_list, + uint8_t dst_list[kDPBIndicesListSize]); + void H264DPBToV4L2DPB( + const H264DPB& dpb, + std::vector<scoped_refptr<V4L2DecodeSurface>>* ref_surfaces); + scoped_refptr<V4L2DecodeSurface> H264PictureToV4L2DecodeSurface( + H264Picture* pic); + + size_t num_slices_; + V4L2DecodeSurfaceHandler* const surface_handler_; + V4L2Device* const device_; + + // Contains the kernel-specific structures that we don't want to expose + // outside of the compilation unit. + const std::unique_ptr<V4L2LegacyH264AcceleratorPrivate> priv_; + + DISALLOW_COPY_AND_ASSIGN(V4L2LegacyH264Accelerator); +}; + +} // namespace media + +#endif // MEDIA_GPU_V4L2_V4L2_H264_ACCELERATOR_LEGACY_H_
diff --git a/media/gpu/v4l2/v4l2_slice_video_decode_accelerator.cc b/media/gpu/v4l2/v4l2_slice_video_decode_accelerator.cc index cac4d8e6..f57bce3 100644 --- a/media/gpu/v4l2/v4l2_slice_video_decode_accelerator.cc +++ b/media/gpu/v4l2/v4l2_slice_video_decode_accelerator.cc
@@ -37,6 +37,7 @@ #include "media/gpu/macros.h" #include "media/gpu/v4l2/v4l2_decode_surface.h" #include "media/gpu/v4l2/v4l2_h264_accelerator.h" +#include "media/gpu/v4l2/v4l2_h264_accelerator_legacy.h" #include "media/gpu/v4l2/v4l2_vp8_accelerator.h" #include "media/gpu/v4l2/v4l2_vp9_accelerator.h" #include "ui/gl/gl_context.h" @@ -77,8 +78,7 @@ }; V4L2SliceVideoDecodeAccelerator::OutputRecord::OutputRecord() - : at_client(false), - num_times_sent_to_client(0), + : num_times_sent_to_client(0), picture_id(-1), texture_id(0), cleared(false) {} @@ -274,8 +274,13 @@ } if (video_profile_ >= H264PROFILE_MIN && video_profile_ <= H264PROFILE_MAX) { - decoder_.reset(new H264Decoder( - std::make_unique<V4L2H264Accelerator>(this, device_.get()))); + if (supports_requests_) { + decoder_.reset(new H264Decoder( + std::make_unique<V4L2H264Accelerator>(this, device_.get()))); + } else { + decoder_.reset(new H264Decoder( + std::make_unique<V4L2LegacyH264Accelerator>(this, device_.get()))); + } } else if (video_profile_ >= VP8PROFILE_MIN && video_profile_ <= VP8PROFILE_MAX) { decoder_.reset(new VP8Decoder( @@ -1173,14 +1178,6 @@ // This will prevent us from reusing old surfaces in case we have some // ReusePictureBuffer() pending on ChildThread already. It's ok to ignore // them, because we have already dismissed them (in DestroyOutputs()). - for (const auto& surface_at_display : surfaces_at_display_) { - size_t index = surface_at_display.second->output_record(); - DCHECK_LT(index, output_buffer_map_.size()); - OutputRecord& output_record = output_buffer_map_[index]; - DCHECK(output_record.at_client); - output_record.at_client = false; - output_record.num_times_sent_to_client = 0; - } surfaces_at_display_.clear(); DCHECK_EQ(output_queue_->FreeBuffersCount(), output_buffer_map_.size()); @@ -1568,7 +1565,7 @@ } OutputRecord& output_record = output_buffer_map_[it->second->output_record()]; - if (!output_record.at_client) { + if (!output_record.at_client()) { VLOGF(1) << "picture_buffer_id not reusable"; NOTIFY_ERROR(INVALID_ARGUMENT); return; @@ -1577,8 +1574,7 @@ --output_record.num_times_sent_to_client; // A output buffer might be sent multiple times. We only use the last fence. // When the last fence is signaled, all the previous fences must be executed. - if (output_record.num_times_sent_to_client == 0) { - output_record.at_client = false; + if (!output_record.at_client()) { // Take ownership of the EGL fence. surfaces_awaiting_fence_.push( std::make_pair(std::move(egl_fence), std::move(it->second))); @@ -1844,9 +1840,7 @@ OutputRecord& output_record = output_buffer_map_[dec_surface->output_record()]; - if (output_record.num_times_sent_to_client == 0) { - DCHECK(!output_record.at_client); - output_record.at_client = true; + if (!output_record.at_client()) { bool inserted = surfaces_at_display_ .insert(std::make_pair(output_record.picture_id, dec_surface)) @@ -1854,7 +1848,6 @@ DCHECK(inserted); } else { // The surface is already sent to client, and not returned back yet. - DCHECK(output_record.at_client); DCHECK(surfaces_at_display_.find(output_record.picture_id) != surfaces_at_display_.end()); CHECK(surfaces_at_display_[output_record.picture_id].get() == @@ -2050,7 +2043,7 @@ size_t V4L2SliceVideoDecodeAccelerator::GetNumOfOutputRecordsAtClient() const { DCHECK(decoder_thread_.task_runner()->BelongsToCurrentThread()); return std::count_if(output_buffer_map_.begin(), output_buffer_map_.end(), - [](const auto& r) { return r.at_client; }); + [](const auto& r) { return r.at_client(); }); } // base::trace_event::MemoryDumpProvider implementation.
diff --git a/media/gpu/v4l2/v4l2_slice_video_decode_accelerator.h b/media/gpu/v4l2/v4l2_slice_video_decode_accelerator.h index 70bee17..df7340e 100644 --- a/media/gpu/v4l2/v4l2_slice_video_decode_accelerator.h +++ b/media/gpu/v4l2/v4l2_slice_video_decode_accelerator.h
@@ -83,13 +83,14 @@ OutputRecord(); OutputRecord(OutputRecord&&); ~OutputRecord(); - bool at_client; size_t num_times_sent_to_client; int32_t picture_id; GLuint client_texture_id; GLuint texture_id; std::vector<base::ScopedFD> dmabuf_fds; bool cleared; + + bool at_client() const { return num_times_sent_to_client > 0; } }; // Decoder state enum.
diff --git a/media/gpu/v4l2/v4l2_vda_helpers.cc b/media/gpu/v4l2/v4l2_vda_helpers.cc index 8e23e9d..34dc2541 100644 --- a/media/gpu/v4l2/v4l2_vda_helpers.cc +++ b/media/gpu/v4l2/v4l2_vda_helpers.cc
@@ -19,23 +19,28 @@ // format and now is only used for MT8173 VDA output and its image processor // input, we set VideoFrameLayout for image processor's input with format // PIXEL_FORMAT_NV12 as NV12's layout is the same as MT21. - if (fourcc == V4L2_PIX_FMT_MT21C) { - size_t num_planes = 2; - return VideoFrameLayout::CreateMultiPlanar( - PIXEL_FORMAT_NV12, size, - std::vector<VideoFrameLayout::Plane>(num_planes)); - } else { - VideoPixelFormat pixel_format = - V4L2Device::V4L2PixFmtToVideoPixelFormat(fourcc); - if (pixel_format == PIXEL_FORMAT_UNKNOWN) - return base::nullopt; - size_t num_planes = VideoFrame::NumPlanes(pixel_format); - if (num_planes == 1) { - return VideoFrameLayout::Create(pixel_format, size); - } else { + size_t num_planes; + switch (fourcc) { + case V4L2_PIX_FMT_MT21C: + case V4L2_PIX_FMT_MM21: + num_planes = 2; return VideoFrameLayout::CreateMultiPlanar( - pixel_format, size, std::vector<VideoFrameLayout::Plane>(num_planes)); - } + PIXEL_FORMAT_NV12, size, + std::vector<VideoFrameLayout::Plane>(num_planes)); + + default: + VideoPixelFormat pixel_format = + V4L2Device::V4L2PixFmtToVideoPixelFormat(fourcc); + if (pixel_format == PIXEL_FORMAT_UNKNOWN) + return base::nullopt; + num_planes = VideoFrame::NumPlanes(pixel_format); + if (num_planes == 1) + return VideoFrameLayout::Create(pixel_format, size); + else + return VideoFrameLayout::CreateMultiPlanar( + pixel_format, size, + std::vector<VideoFrameLayout::Plane>(num_planes)); + break; } } } // namespace
diff --git a/remoting/host/chromeos/clipboard_aura_unittest.cc b/remoting/host/chromeos/clipboard_aura_unittest.cc index fa82caa4..d1616ae 100644 --- a/remoting/host/chromeos/clipboard_aura_unittest.cc +++ b/remoting/host/chromeos/clipboard_aura_unittest.cc
@@ -8,10 +8,10 @@ #include "base/bind_helpers.h" #include "base/macros.h" #include "base/memory/ptr_util.h" -#include "base/message_loop/message_loop.h" #include "base/run_loop.h" #include "base/single_thread_task_runner.h" #include "base/strings/utf_string_conversions.h" +#include "base/test/scoped_task_environment.h" #include "base/test/test_timeouts.h" #include "remoting/base/constants.h" #include "remoting/proto/event.pb.h" @@ -56,7 +56,8 @@ protected: void StopAndResetClipboard(); - base::MessageLoopForUI message_loop_; + base::test::ScopedTaskEnvironment scoped_task_environment_{ + base::test::ScopedTaskEnvironment::MainThreadType::UI}; ClientClipboard* client_clipboard_; std::unique_ptr<ClipboardAura> clipboard_; }; @@ -69,8 +70,6 @@ ui::Clipboard::SetAllowedThreads(allowed_clipboard_threads); // Setup the clipboard. - scoped_refptr<base::SingleThreadTaskRunner> task_runner = - message_loop_.task_runner(); client_clipboard_ = new ClientClipboard(); clipboard_.reset(new ClipboardAura()); @@ -120,13 +119,13 @@ Eq("Test data.")))).Times(1); base::RunLoop run_loop; - message_loop_.task_runner()->PostDelayedTask( + scoped_task_environment_.GetMainThreadTaskRunner()->PostDelayedTask( FROM_HERE, base::BindOnce(&ClipboardAuraTest_MonitorClipboardChanges_Test:: StopAndResetClipboard, base::Unretained(this)), TestTimeouts::tiny_timeout()); - message_loop_.task_runner()->PostDelayedTask( + scoped_task_environment_.GetMainThreadTaskRunner()->PostDelayedTask( FROM_HERE, run_loop.QuitClosure(), TestTimeouts::tiny_timeout()); run_loop.Run(); }
diff --git a/remoting/host/chromoting_host_context_unittest.cc b/remoting/host/chromoting_host_context_unittest.cc index b0aefa0..9f0bd83 100644 --- a/remoting/host/chromoting_host_context_unittest.cc +++ b/remoting/host/chromoting_host_context_unittest.cc
@@ -2,10 +2,11 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "base/message_loop/message_loop.h" -#include "base/run_loop.h" -#include "remoting/base/auto_thread_task_runner.h" #include "remoting/host/chromoting_host_context.h" + +#include "base/run_loop.h" +#include "base/test/scoped_task_environment.h" +#include "remoting/base/auto_thread_task_runner.h" #include "testing/gtest/include/gtest/gtest.h" namespace remoting { @@ -13,12 +14,14 @@ // A simple test that starts and stop the context. This tests the context // operates properly and all threads and message loops are valid. TEST(ChromotingHostContextTest, StartAndStop) { - base::MessageLoopForUI message_loop; + base::test::ScopedTaskEnvironment scoped_task_environment{ + base::test::ScopedTaskEnvironment::MainThreadType::UI}; base::RunLoop run_loop; std::unique_ptr<ChromotingHostContext> context = ChromotingHostContext::Create(new AutoThreadTaskRunner( - message_loop.task_runner(), run_loop.QuitClosure())); + scoped_task_environment.GetMainThreadTaskRunner(), + run_loop.QuitClosure())); EXPECT_TRUE(context); if (!context)
diff --git a/remoting/host/config_file_watcher_unittest.cc b/remoting/host/config_file_watcher_unittest.cc index b5d0a1d..b009aca5 100644 --- a/remoting/host/config_file_watcher_unittest.cc +++ b/remoting/host/config_file_watcher_unittest.cc
@@ -10,6 +10,7 @@ #include "base/message_loop/message_loop.h" #include "base/message_loop/message_pump_type.h" #include "base/run_loop.h" +#include "base/test/scoped_task_environment.h" #include "remoting/base/auto_thread.h" #include "remoting/base/auto_thread_task_runner.h" #include "testing/gmock/include/gmock/gmock.h" @@ -51,7 +52,8 @@ void StopWatcher(); protected: - base::MessageLoopForUI message_loop_; + base::test::ScopedTaskEnvironment scoped_task_environment_{ + base::test::ScopedTaskEnvironment::MainThreadType::UI}; base::RunLoop run_loop_; ConfigFileWatcherDelegate delegate_; @@ -76,7 +78,8 @@ // Arrange to run |message_loop_| until no components depend on it. scoped_refptr<AutoThreadTaskRunner> task_runner = new AutoThreadTaskRunner( - message_loop_.task_runner(), run_loop_.QuitClosure()); + scoped_task_environment_.GetMainThreadTaskRunner(), + run_loop_.QuitClosure()); scoped_refptr<AutoThreadTaskRunner> io_task_runner = AutoThread::CreateWithType("IPC thread", task_runner,
diff --git a/remoting/host/desktop_process_unittest.cc b/remoting/host/desktop_process_unittest.cc index be5f9b4d..f845e46 100644 --- a/remoting/host/desktop_process_unittest.cc +++ b/remoting/host/desktop_process_unittest.cc
@@ -17,6 +17,7 @@ #include "base/message_loop/message_pump_type.h" #include "base/run_loop.h" #include "base/single_thread_task_runner.h" +#include "base/test/scoped_task_environment.h" #include "build/build_config.h" #include "ipc/ipc_channel.h" #include "ipc/ipc_channel_proxy.h" @@ -152,7 +153,8 @@ MockDaemonListener daemon_listener_; // Runs the daemon's end of the channel. - base::MessageLoopForUI message_loop_; + base::test::ScopedTaskEnvironment scoped_task_environment_{ + base::test::ScopedTaskEnvironment::MainThreadType::UI}; scoped_refptr<AutoThreadTaskRunner> io_task_runner_; @@ -227,19 +229,19 @@ } void DesktopProcessTest::PostDisconnectChannels() { - message_loop_.task_runner()->PostTask( + scoped_task_environment_.GetMainThreadTaskRunner()->PostTask( FROM_HERE, base::BindOnce(&DesktopProcessTest::DisconnectChannels, base::Unretained(this))); } void DesktopProcessTest::RunDesktopProcess() { base::RunLoop run_loop; - base::Closure quit_ui_task_runner = base::Bind( - base::IgnoreResult(&base::SingleThreadTaskRunner::PostTask), - message_loop_.task_runner(), - FROM_HERE, run_loop.QuitClosure()); + base::Closure quit_ui_task_runner = + base::Bind(base::IgnoreResult(&base::SingleThreadTaskRunner::PostTask), + scoped_task_environment_.GetMainThreadTaskRunner(), FROM_HERE, + run_loop.QuitClosure()); scoped_refptr<AutoThreadTaskRunner> ui_task_runner = new AutoThreadTaskRunner( - message_loop_.task_runner(), quit_ui_task_runner); + scoped_task_environment_.GetMainThreadTaskRunner(), quit_ui_task_runner); io_task_runner_ = AutoThread::CreateWithType("IPC thread", ui_task_runner, base::MessagePumpType::IO);
diff --git a/remoting/host/host_power_save_blocker_unittest.cc b/remoting/host/host_power_save_blocker_unittest.cc index 22ea605..c95d4f1 100644 --- a/remoting/host/host_power_save_blocker_unittest.cc +++ b/remoting/host/host_power_save_blocker_unittest.cc
@@ -8,6 +8,7 @@ #include "base/logging.h" #include "base/message_loop/message_pump_type.h" +#include "base/test/scoped_task_environment.h" #include "base/threading/thread.h" #include "remoting/host/host_status_monitor.h" #include "testing/gtest/include/gtest/gtest.h" @@ -23,7 +24,8 @@ void SetUp() override; - base::MessageLoopForUI ui_message_loop_; + base::test::ScopedTaskEnvironment scoped_task_environment_{ + base::test::ScopedTaskEnvironment::MainThreadType::UI}; base::Thread blocking_thread_; scoped_refptr<HostStatusMonitor> monitor_; std::unique_ptr<HostPowerSaveBlocker> blocker_; @@ -36,9 +38,9 @@ ASSERT_TRUE(blocking_thread_.StartWithOptions( base::Thread::Options(base::MessagePumpType::IO, 0)) && blocking_thread_.WaitUntilThreadStarted()); - blocker_.reset(new HostPowerSaveBlocker(monitor_, - ui_message_loop_.task_runner(), - blocking_thread_.task_runner())); + blocker_.reset(new HostPowerSaveBlocker( + monitor_, scoped_task_environment_.GetMainThreadTaskRunner(), + blocking_thread_.task_runner())); } bool HostPowerSaveBlockerTest::is_activated() const {
diff --git a/remoting/host/ipc_desktop_environment_unittest.cc b/remoting/host/ipc_desktop_environment_unittest.cc index f1ce73a0..0f1cda3e 100644 --- a/remoting/host/ipc_desktop_environment_unittest.cc +++ b/remoting/host/ipc_desktop_environment_unittest.cc
@@ -14,12 +14,12 @@ #include "base/callback.h" #include "base/macros.h" #include "base/memory/ref_counted.h" -#include "base/message_loop/message_loop.h" #include "base/message_loop/message_pump_type.h" #include "base/process/process.h" #include "base/process/process_handle.h" #include "base/run_loop.h" #include "base/single_thread_task_runner.h" +#include "base/test/scoped_task_environment.h" #include "build/build_config.h" #include "ipc/ipc_channel.h" #include "ipc/ipc_channel_proxy.h" @@ -198,8 +198,8 @@ void RunMainLoopUntilDone(); - // The main message loop. - base::MessageLoopForUI message_loop_; + base::test::ScopedTaskEnvironment scoped_task_environment_{ + base::test::ScopedTaskEnvironment::MainThreadType::UI}; // Runs until |desktop_session_proxy_| is connected to the desktop. std::unique_ptr<base::RunLoop> setup_run_loop_; @@ -264,7 +264,8 @@ void IpcDesktopEnvironmentTest::SetUp() { // Arrange to run |message_loop_| until no components depend on it. task_runner_ = new AutoThreadTaskRunner( - message_loop_.task_runner(), main_run_loop_.QuitClosure()); + scoped_task_environment_.GetMainThreadTaskRunner(), + main_run_loop_.QuitClosure()); io_task_runner_ = AutoThread::CreateWithType("IPC thread", task_runner_, base::MessagePumpType::IO); @@ -370,8 +371,8 @@ .Times(AtMost(1)); // Let tests know that the remote desktop environment is created. - message_loop_.task_runner()->PostTask(FROM_HERE, - setup_run_loop_->QuitClosure()); + scoped_task_environment_.GetMainThreadTaskRunner()->PostTask( + FROM_HERE, setup_run_loop_->QuitClosure()); return desktop_environment; }
diff --git a/remoting/host/win/rdp_client_unittest.cc b/remoting/host/win/rdp_client_unittest.cc index 3167e155..33170f4 100644 --- a/remoting/host/win/rdp_client_unittest.cc +++ b/remoting/host/win/rdp_client_unittest.cc
@@ -2,6 +2,8 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +#include "remoting/host/win/rdp_client.h" + #include <cstdint> #include <string> @@ -9,14 +11,13 @@ #include "base/bind_helpers.h" #include "base/guid.h" #include "base/macros.h" -#include "base/message_loop/message_loop.h" #include "base/run_loop.h" #include "base/single_thread_task_runner.h" +#include "base/test/scoped_task_environment.h" #include "base/win/atl.h" #include "base/win/scoped_com_initializer.h" #include "remoting/base/auto_thread_task_runner.h" #include "remoting/host/screen_resolution.h" -#include "remoting/host/win/rdp_client.h" #include "remoting/host/win/wts_terminal_monitor.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gmock_mutant.h" @@ -52,11 +53,10 @@ // a14498c6-7f3b-4e42-9605-6c4a20d53c87 static GUID RdpClientModuleLibid = { - 0xa14498c6, - 0x7f3b, - 0x4e42, - { 0x96, 0x05, 0x6c, 0x4a, 0x20, 0xd5, 0x3c, 0x87 } -}; + 0xa14498c6, + 0x7f3b, + 0x4e42, + {0x96, 0x05, 0x6c, 0x4a, 0x20, 0xd5, 0x3c, 0x87}}; class RdpClientModule : public ATL::CAtlModuleT<RdpClientModule> { public: @@ -98,9 +98,10 @@ // The ATL module instance required by the ATL code. std::unique_ptr<RdpClientModule> module_; - // The UI message loop used by RdpClient. The loop is stopped once there is no - // more references to |task_runner_|. - base::MessageLoopForUI message_loop_; + // Used by RdpClient. The loop is stopped once there are no more references to + // |task_runner_|. + base::test::ScopedTaskEnvironment scoped_task_environment_{ + base::test::ScopedTaskEnvironment::MainThreadType::UI}; base::RunLoop run_loop_; scoped_refptr<AutoThreadTaskRunner> task_runner_; @@ -114,16 +115,15 @@ std::string terminal_id_; }; -RdpClientTest::RdpClientTest() { -} +RdpClientTest::RdpClientTest() {} -RdpClientTest::~RdpClientTest() { -} +RdpClientTest::~RdpClientTest() {} void RdpClientTest::SetUp() { - // Arrange to run |message_loop_| until no components depend on it. + // Arrange to run |run_loop_| until no components depend on it. task_runner_ = new AutoThreadTaskRunner( - message_loop_.task_runner(), run_loop_.QuitClosure()); + scoped_task_environment_.GetMainThreadTaskRunner(), + run_loop_.QuitClosure()); module_.reset(new RdpClientModule()); } @@ -141,7 +141,7 @@ EXPECT_TRUE(WtsTerminalMonitor::LookupTerminalId(session_id, &id)); EXPECT_EQ(id, terminal_id_); - message_loop_.task_runner()->PostTask( + scoped_task_environment_.GetMainThreadTaskRunner()->PostTask( FROM_HERE, base::BindOnce(&RdpClientTest::CloseRdpClient, base::Unretained(this))); }
diff --git a/services/BUILD.gn b/services/BUILD.gn index 25ad869..1450fd58 100644 --- a/services/BUILD.gn +++ b/services/BUILD.gn
@@ -56,6 +56,7 @@ if (is_android) { deps += [ + "//components/signin/public/identity_manager/android:java", "//services/data_decoder/public/cpp/android:safe_json_java", "//services/device:java", "//services/identity:java",
diff --git a/services/media_session/audio_focus_manager_unittest.cc b/services/media_session/audio_focus_manager_unittest.cc index 13bbbbd0..6095a4e5 100644 --- a/services/media_session/audio_focus_manager_unittest.cc +++ b/services/media_session/audio_focus_manager_unittest.cc
@@ -51,15 +51,17 @@ // Create an instance of the MediaSessionService. service_ = std::make_unique<MediaSessionService>( connector_factory_.RegisterInstance(mojom::kServiceName)); - connector_factory_.GetDefaultConnector()->BindInterface(mojom::kServiceName, - &audio_focus_ptr_); - connector_factory_.GetDefaultConnector()->BindInterface( - mojom::kServiceName, &audio_focus_debug_ptr_); - connector_factory_.GetDefaultConnector()->BindInterface( - mojom::kServiceName, &controller_manager_ptr_); + connector_factory_.GetDefaultConnector()->Connect( + mojom::kServiceName, audio_focus_remote_.BindNewPipeAndPassReceiver()); + connector_factory_.GetDefaultConnector()->Connect( + mojom::kServiceName, + audio_focus_debug_remote_.BindNewPipeAndPassReceiver()); + connector_factory_.GetDefaultConnector()->Connect( + mojom::kServiceName, + controller_manager_remote_.BindNewPipeAndPassReceiver()); - audio_focus_ptr_->SetEnforcementMode(GetParam()); - audio_focus_ptr_.FlushForTesting(); + audio_focus_remote_->SetEnforcementMode(GetParam()); + audio_focus_remote_.FlushForTesting(); } void TearDown() override { @@ -95,13 +97,13 @@ void AbandonAudioFocusNoReset(test::MockMediaSession* session) { session->audio_focus_request()->AbandonAudioFocus(); session->FlushForTesting(); - audio_focus_ptr_.FlushForTesting(); + audio_focus_remote_.FlushForTesting(); } AudioFocusManager::RequestId RequestAudioFocus( test::MockMediaSession* session, mojom::AudioFocusType audio_focus_type) { - return session->RequestAudioFocusFromService(audio_focus_ptr_, + return session->RequestAudioFocusFromService(audio_focus_remote_, audio_focus_type); } @@ -110,7 +112,7 @@ mojom::AudioFocusType audio_focus_type, const base::UnguessableToken& group_id) { return session->RequestGroupedAudioFocusFromService( - request_id, audio_focus_ptr_, audio_focus_type, group_id); + request_id, audio_focus_remote_, audio_focus_type, group_id); } mojom::MediaSessionDebugInfoPtr GetDebugInfo( @@ -126,8 +128,8 @@ GetDebugService()->GetDebugInfoForRequest(request_id, std::move(callback)); - audio_focus_ptr_.FlushForTesting(); - audio_focus_debug_ptr_.FlushForTesting(); + audio_focus_remote_.FlushForTesting(); + audio_focus_debug_remote_.FlushForTesting(); return result; } @@ -151,7 +153,7 @@ GetService()->AddObserver(observer->BindNewPipeAndPassRemote()); - audio_focus_ptr_.FlushForTesting(); + audio_focus_remote_.FlushForTesting(); return observer; } @@ -166,14 +168,14 @@ void SetSourceName(const std::string& name) { GetService()->SetSourceName(name); - audio_focus_ptr_.FlushForTesting(); + audio_focus_remote_.FlushForTesting(); } - mojom::AudioFocusManagerPtr CreateAudioFocusManagerPtr() { - mojom::AudioFocusManagerPtr ptr; - connector_factory_.GetDefaultConnector()->BindInterface( - mojom::kServiceName, mojo::MakeRequest(&ptr)); - return ptr; + mojo::Remote<mojom::AudioFocusManager> CreateAudioFocusManagerRemote() { + mojo::Remote<mojom::AudioFocusManager> remote; + connector_factory_.GetDefaultConnector()->Connect( + mojom::kServiceName, remote.BindNewPipeAndPassReceiver()); + return remote; } const std::string GetSourceNameForLastRequest() { @@ -210,8 +212,8 @@ base::PowerMonitorTestSource& GetTestPowerSource() { return *power_source_; } - mojom::MediaControllerManagerPtr& controller_manager() { - return controller_manager_ptr_; + mojo::Remote<mojom::MediaControllerManager>& controller_manager() { + return controller_manager_remote_; } private: @@ -235,23 +237,23 @@ }, &result)); - audio_focus_ptr_.FlushForTesting(); + audio_focus_remote_.FlushForTesting(); return result; } mojom::AudioFocusManager* GetService() const { - return audio_focus_ptr_.get(); + return audio_focus_remote_.get(); } mojom::AudioFocusManagerDebug* GetDebugService() const { - return audio_focus_debug_ptr_.get(); + return audio_focus_debug_remote_.get(); } void FlushForTestingIfEnabled() { if (!IsEnforcementEnabled()) return; - audio_focus_ptr_.FlushForTesting(); + audio_focus_remote_.FlushForTesting(); } base::test::ScopedTaskEnvironment task_environment_; @@ -260,9 +262,9 @@ service_manager::TestConnectorFactory connector_factory_; std::unique_ptr<MediaSessionService> service_; - mojom::AudioFocusManagerPtr audio_focus_ptr_; - mojom::AudioFocusManagerDebugPtr audio_focus_debug_ptr_; - mojom::MediaControllerManagerPtr controller_manager_ptr_; + mojo::Remote<mojom::AudioFocusManager> audio_focus_remote_; + mojo::Remote<mojom::AudioFocusManagerDebug> audio_focus_debug_remote_; + mojo::Remote<mojom::MediaControllerManager> controller_manager_remote_; base::PowerMonitorTestSource* power_source_; @@ -862,7 +864,8 @@ TEST_P(AudioFocusManagerTest, SourceName_AssociatedWithBinding) { SetSourceName(kExampleSourceName); - mojom::AudioFocusManagerPtr new_ptr = CreateAudioFocusManagerPtr(); + mojo::Remote<mojom::AudioFocusManager> new_ptr = + CreateAudioFocusManagerRemote(); new_ptr->SetSourceName(kExampleSourceName2); new_ptr.FlushForTesting(); @@ -1548,9 +1551,9 @@ GetStateFromParam(mojom::MediaSessionInfo::SessionState::kSuspended), GetState(&media_session_1)); - mojom::MediaControllerPtr controller; + mojo::Remote<mojom::MediaController> controller; controller_manager()->CreateMediaControllerForSession( - mojo::MakeRequest(&controller), media_session_1.request_id()); + controller.BindNewPipeAndPassReceiver(), media_session_1.request_id()); controller_manager().FlushForTesting(); controller->Suspend(); @@ -1578,9 +1581,9 @@ GetStateFromParam(mojom::MediaSessionInfo::SessionState::kSuspended), GetState(&media_session_1)); - mojom::MediaControllerPtr controller; + mojo::Remote<mojom::MediaController> controller; controller_manager()->CreateMediaControllerForSession( - mojo::MakeRequest(&controller), media_session_1.request_id()); + controller.BindNewPipeAndPassReceiver(), media_session_1.request_id()); controller_manager().FlushForTesting(); controller->Stop(); @@ -1611,9 +1614,9 @@ EXPECT_EQ(mojom::MediaSessionInfo::SessionState::kActive, GetState(&media_session_1)); - mojom::MediaControllerPtr controller; + mojo::Remote<mojom::MediaController> controller; controller_manager()->CreateMediaControllerForSession( - mojo::MakeRequest(&controller), media_session_1.request_id()); + controller.BindNewPipeAndPassReceiver(), media_session_1.request_id()); controller_manager().FlushForTesting(); controller->Suspend(); @@ -1657,9 +1660,9 @@ GetStateFromParam(mojom::MediaSessionInfo::SessionState::kSuspended), GetState(&media_session_1)); - mojom::MediaControllerPtr controller; + mojo::Remote<mojom::MediaController> controller; controller_manager()->CreateMediaControllerForSession( - mojo::MakeRequest(&controller), media_session_1.request_id()); + controller.BindNewPipeAndPassReceiver(), media_session_1.request_id()); controller_manager().FlushForTesting(); controller->Resume();
diff --git a/services/media_session/media_controller_unittest.cc b/services/media_session/media_controller_unittest.cc index d937247..9ca1c27a 100644 --- a/services/media_session/media_controller_unittest.cc +++ b/services/media_session/media_controller_unittest.cc
@@ -31,18 +31,19 @@ // Create an instance of the MediaSessionService and bind some interfaces. service_ = std::make_unique<MediaSessionService>( connector_factory_.RegisterInstance(mojom::kServiceName)); - connector_factory_.GetDefaultConnector()->BindInterface(mojom::kServiceName, - &audio_focus_ptr_); - connector_factory_.GetDefaultConnector()->BindInterface( - mojom::kServiceName, &controller_manager_ptr_); + connector_factory_.GetDefaultConnector()->Connect( + mojom::kServiceName, audio_focus_remote_.BindNewPipeAndPassReceiver()); + connector_factory_.GetDefaultConnector()->Connect( + mojom::kServiceName, + controller_manager_remote_.BindNewPipeAndPassReceiver()); - controller_manager_ptr_->CreateActiveMediaController( - mojo::MakeRequest(&media_controller_ptr_)); - controller_manager_ptr_.FlushForTesting(); + controller_manager_remote_->CreateActiveMediaController( + media_controller_remote_.BindNewPipeAndPassReceiver()); + controller_manager_remote_.FlushForTesting(); - audio_focus_ptr_->SetEnforcementMode( + audio_focus_remote_->SetEnforcementMode( mojom::EnforcementMode::kSingleSession); - audio_focus_ptr_.FlushForTesting(); + audio_focus_remote_.FlushForTesting(); } void TearDown() override { @@ -52,13 +53,15 @@ void RequestAudioFocus(test::MockMediaSession& session, mojom::AudioFocusType type) { - session.RequestAudioFocusFromService(audio_focus_ptr_, type); + session.RequestAudioFocusFromService(audio_focus_remote_, type); } - mojom::MediaControllerPtr& controller() { return media_controller_ptr_; } + mojo::Remote<mojom::MediaController>& controller() { + return media_controller_remote_; + } - mojom::MediaControllerManagerPtr& manager() { - return controller_manager_ptr_; + mojo::Remote<mojom::MediaControllerManager>& manager() { + return controller_manager_remote_; } static size_t GetImageObserverCount(const MediaController& controller) { @@ -69,9 +72,9 @@ base::test::ScopedTaskEnvironment task_environment_; service_manager::TestConnectorFactory connector_factory_; std::unique_ptr<MediaSessionService> service_; - mojom::AudioFocusManagerPtr audio_focus_ptr_; - mojom::MediaControllerPtr media_controller_ptr_; - mojom::MediaControllerManagerPtr controller_manager_ptr_; + mojo::Remote<mojom::AudioFocusManager> audio_focus_remote_; + mojo::Remote<mojom::MediaController> media_controller_remote_; + mojo::Remote<mojom::MediaControllerManager> controller_manager_remote_; DISALLOW_COPY_AND_ASSIGN(MediaControllerTest); }; @@ -715,9 +718,9 @@ observer.WaitForPlaybackState(mojom::MediaPlaybackState::kPlaying); } - mojom::MediaControllerPtr controller; - manager()->CreateMediaControllerForSession(mojo::MakeRequest(&controller), - media_session_1.request_id()); + mojo::Remote<mojom::MediaController> controller; + manager()->CreateMediaControllerForSession( + controller.BindNewPipeAndPassReceiver(), media_session_1.request_id()); manager().FlushForTesting(); EXPECT_EQ(0, media_session_1.next_track_count()); @@ -753,9 +756,10 @@ observer.WaitForPlaybackState(mojom::MediaPlaybackState::kPlaying); } - mojom::MediaControllerPtr controller; - manager()->CreateMediaControllerForSession(mojo::MakeRequest(&controller), - base::UnguessableToken::Create()); + mojo::Remote<mojom::MediaController> controller; + manager()->CreateMediaControllerForSession( + controller.BindNewPipeAndPassReceiver(), + base::UnguessableToken::Create()); manager().FlushForTesting(); EXPECT_EQ(0, media_session.next_track_count()); @@ -776,9 +780,9 @@ observer.WaitForPlaybackState(mojom::MediaPlaybackState::kPlaying); } - mojom::MediaControllerPtr controller; - manager()->CreateMediaControllerForSession(mojo::MakeRequest(&controller), - media_session.request_id()); + mojo::Remote<mojom::MediaController> controller; + manager()->CreateMediaControllerForSession( + controller.BindNewPipeAndPassReceiver(), media_session.request_id()); manager().FlushForTesting(); EXPECT_EQ(0, media_session.next_track_count()); @@ -1053,12 +1057,12 @@ TEST_F(MediaControllerTest, ClearImageObserverOnError) { MediaController controller; - mojom::MediaControllerPtr controller_ptr; - controller.BindToInterface(mojo::MakeRequest(&controller_ptr)); + mojo::Remote<mojom::MediaController> controller_remote; + controller.BindToInterface(controller_remote.BindNewPipeAndPassReceiver()); EXPECT_EQ(0u, GetImageObserverCount(controller)); { - test::TestMediaControllerImageObserver observer(controller_ptr, 0, 0); + test::TestMediaControllerImageObserver observer(controller_remote, 0, 0); EXPECT_EQ(1u, GetImageObserverCount(controller)); } @@ -1319,9 +1323,9 @@ observer.WaitForState(mojom::MediaSessionInfo::SessionState::kActive); } - mojom::MediaControllerPtr controller; - manager()->CreateMediaControllerForSession(mojo::MakeRequest(&controller), - media_session.request_id()); + mojo::Remote<mojom::MediaController> controller; + manager()->CreateMediaControllerForSession( + controller.BindNewPipeAndPassReceiver(), media_session.request_id()); manager().FlushForTesting(); {
diff --git a/services/media_session/public/cpp/test/mock_media_session.cc b/services/media_session/public/cpp/test/mock_media_session.cc index ed7c8285..4c06cc3 100644 --- a/services/media_session/public/cpp/test/mock_media_session.cc +++ b/services/media_session/public/cpp/test/mock_media_session.cc
@@ -317,7 +317,7 @@ } base::UnguessableToken MockMediaSession::RequestAudioFocusFromService( - mojom::AudioFocusManagerPtr& service, + mojo::Remote<mojom::AudioFocusManager>& service, mojom::AudioFocusType audio_focus_type) { if (afr_client_.is_bound()) { RequestAudioFocusFromClient(audio_focus_type); @@ -350,7 +350,7 @@ bool MockMediaSession::RequestGroupedAudioFocusFromService( const base::UnguessableToken& request_id, - mojom::AudioFocusManagerPtr& service, + mojo::Remote<mojom::AudioFocusManager>& service, mojom::AudioFocusType audio_focus_type, const base::UnguessableToken& group_id) { if (afr_client_.is_bound()) {
diff --git a/services/media_session/public/cpp/test/mock_media_session.h b/services/media_session/public/cpp/test/mock_media_session.h index 642ce237..82b4d10 100644 --- a/services/media_session/public/cpp/test/mock_media_session.h +++ b/services/media_session/public/cpp/test/mock_media_session.h
@@ -147,12 +147,12 @@ void AbandonAudioFocusFromClient(); base::UnguessableToken RequestAudioFocusFromService( - mojom::AudioFocusManagerPtr& service, + mojo::Remote<mojom::AudioFocusManager>& service, mojom::AudioFocusType audio_foucs_type); bool RequestGroupedAudioFocusFromService( const base::UnguessableToken& request_id, - mojom::AudioFocusManagerPtr& service, + mojo::Remote<mojom::AudioFocusManager>& service, mojom::AudioFocusType audio_focus_type, const base::UnguessableToken& group_id);
diff --git a/services/media_session/public/cpp/test/test_media_controller.cc b/services/media_session/public/cpp/test/test_media_controller.cc index 7d3fb8c..87e83644 100644 --- a/services/media_session/public/cpp/test/test_media_controller.cc +++ b/services/media_session/public/cpp/test/test_media_controller.cc
@@ -8,7 +8,7 @@ namespace test { TestMediaControllerImageObserver::TestMediaControllerImageObserver( - mojom::MediaControllerPtr& controller, + mojo::Remote<mojom::MediaController>& controller, int minimum_size_px, int desired_size_px) { controller->ObserveImages(mojom::MediaSessionImageType::kArtwork, @@ -49,7 +49,7 @@ } TestMediaControllerObserver::TestMediaControllerObserver( - mojom::MediaControllerPtr& media_controller) { + mojo::Remote<mojom::MediaController>& media_controller) { media_controller->AddObserver(receiver_.BindNewPipeAndPassRemote()); } @@ -214,10 +214,11 @@ TestMediaController::~TestMediaController() = default; -mojom::MediaControllerPtr TestMediaController::CreateMediaControllerPtr() { - mojom::MediaControllerPtr ptr; - binding_.Bind(mojo::MakeRequest(&ptr)); - return ptr; +mojo::Remote<mojom::MediaController> +TestMediaController::CreateMediaControllerRemote() { + mojo::Remote<mojom::MediaController> remote; + binding_.Bind(remote.BindNewPipeAndPassReceiver()); + return remote; } void TestMediaController::Suspend() {
diff --git a/services/media_session/public/cpp/test/test_media_controller.h b/services/media_session/public/cpp/test/test_media_controller.h index b4680b5..100f934 100644 --- a/services/media_session/public/cpp/test/test_media_controller.h +++ b/services/media_session/public/cpp/test/test_media_controller.h
@@ -25,9 +25,10 @@ TestMediaControllerImageObserver : public mojom::MediaControllerImageObserver { public: - TestMediaControllerImageObserver(mojom::MediaControllerPtr& controller, - int minimum_size_px, - int desired_size_px); + TestMediaControllerImageObserver( + mojo::Remote<mojom::MediaController>& controller, + int minimum_size_px, + int desired_size_px); ~TestMediaControllerImageObserver() override; // mojom::MediaControllerImageObserver overrides. @@ -54,7 +55,7 @@ TestMediaControllerObserver : public mojom::MediaControllerObserver { public: explicit TestMediaControllerObserver( - mojom::MediaControllerPtr& media_controller); + mojo::Remote<mojom::MediaController>& media_controller); ~TestMediaControllerObserver() override; @@ -135,7 +136,7 @@ TestMediaController(); ~TestMediaController() override; - mojom::MediaControllerPtr CreateMediaControllerPtr(); + mojo::Remote<mojom::MediaController> CreateMediaControllerRemote(); // mojom::MediaController: void Suspend() override;
diff --git a/services/media_session/public/cpp/util.cc b/services/media_session/public/cpp/util.cc index ab23a58..c07ffde 100644 --- a/services/media_session/public/cpp/util.cc +++ b/services/media_session/public/cpp/util.cc
@@ -17,28 +17,28 @@ void PerformMediaSessionAction( mojom::MediaSessionAction action, - const mojom::MediaControllerPtr& media_controller_ptr) { + const mojo::Remote<mojom::MediaController>& media_controller_remote) { switch (action) { case mojom::MediaSessionAction::kPreviousTrack: - media_controller_ptr->PreviousTrack(); + media_controller_remote->PreviousTrack(); break; case mojom::MediaSessionAction::kSeekBackward: - media_controller_ptr->Seek(kDefaultSeekTime * -1); + media_controller_remote->Seek(kDefaultSeekTime * -1); break; case mojom::MediaSessionAction::kPlay: - media_controller_ptr->Resume(); + media_controller_remote->Resume(); break; case mojom::MediaSessionAction::kPause: - media_controller_ptr->Suspend(); + media_controller_remote->Suspend(); break; case mojom::MediaSessionAction::kSeekForward: - media_controller_ptr->Seek(kDefaultSeekTime); + media_controller_remote->Seek(kDefaultSeekTime); break; case mojom::MediaSessionAction::kNextTrack: - media_controller_ptr->NextTrack(); + media_controller_remote->NextTrack(); break; case mojom::MediaSessionAction::kStop: - media_controller_ptr->Stop(); + media_controller_remote->Stop(); break; case mojom::MediaSessionAction::kSkipAd: case mojom::MediaSessionAction::kSeekTo:
diff --git a/services/media_session/public/cpp/util.h b/services/media_session/public/cpp/util.h index 47bfc1ff..3e2561e32 100644 --- a/services/media_session/public/cpp/util.h +++ b/services/media_session/public/cpp/util.h
@@ -6,6 +6,7 @@ #define SERVICES_MEDIA_SESSION_PUBLIC_CPP_UTIL_H_ #include "base/component_export.h" +#include "mojo/public/cpp/bindings/remote.h" #include "services/media_session/public/mojom/media_controller.mojom.h" namespace media_session { @@ -14,7 +15,7 @@ COMPONENT_EXPORT(MEDIA_SESSION_CPP) void PerformMediaSessionAction( mojom::MediaSessionAction action, - const mojom::MediaControllerPtr& media_controller_ptr); + const mojo::Remote<mojom::MediaController>& media_controller_remote); } // namespace media_session
diff --git a/services/tracing/public/cpp/perfetto/track_event_thread_local_event_sink.cc b/services/tracing/public/cpp/perfetto/track_event_thread_local_event_sink.cc index c5460bb..ed3ba88 100644 --- a/services/tracing/public/cpp/perfetto/track_event_thread_local_event_sink.cc +++ b/services/tracing/public/cpp/perfetto/track_event_thread_local_event_sink.cc
@@ -4,6 +4,8 @@ #include "services/tracing/public/cpp/perfetto/track_event_thread_local_event_sink.h" +#include <algorithm> + #include "base/stl_util.h" #include "base/strings/pattern.h" #include "base/strings/strcat.h" @@ -580,7 +582,8 @@ DCHECK(handle.event_index > 0 && handle.event_index < current_stack_depth_ && !base::trace_event::TraceLog::GetInstance()->IsEnabled()); - current_stack_depth_ = handle.event_index - 1; + current_stack_depth_ = std::min( + current_stack_depth_, static_cast<uint32_t>(handle.event_index - 1)); return; }
diff --git a/skia/config/SkUserConfig.h b/skia/config/SkUserConfig.h index 94e9588a..80c9462 100644 --- a/skia/config/SkUserConfig.h +++ b/skia/config/SkUserConfig.h
@@ -139,6 +139,12 @@ // converted to type3 when producing PDFs, and reduces build size. #define SK_PDF_DO_NOT_SUPPORT_TYPE_1_FONTS +// Please see: b/138674523. Turning on explicit resource allocation prevented +// reusing textures in some cases (esp. blur image filters using +// SkImage::makeWithFilter). Temporarily keep this bug (via this define) because +// the fix needs to be turned on atomically with some cc unit test rebaselines. +#define SK_CRIPPLE_TEXTURE_REUSE + #ifdef SK_DEBUG #define SK_REF_CNT_MIXIN_INCLUDE "skia/config/sk_ref_cnt_ext_debug.h" #else
diff --git a/testing/buildbot/filters/bfcache.browser_tests.filter b/testing/buildbot/filters/bfcache.browser_tests.filter index 9125216..9d1ba54 100644 --- a/testing/buildbot/filters/bfcache.browser_tests.filter +++ b/testing/buildbot/filters/bfcache.browser_tests.filter
@@ -1,45 +1,40 @@ # These tests currently fail when run with --enable-features=BackForwardCache --CaptivePortalBrowserTest.GoBackToTimeout + +# Expect a document to be deleted after being navigated away. It isn't deleted, +# because the BackForwardCache was used. -ChromeRenderProcessHostTest.ProcessOverflow -ChromeRenderProcessHostTest.ProcessPerTab -ChromeRenderProcessHostTestWithCommandLine.ProcessOverflowCommandLine + +# Rely on an unload handler to run. It doesn't run. -CredentialManagerBrowserTest.StoreInUnloadHandler_CrossSite_OnDemandMojoPipe -CredentialManagerBrowserTest.StoreInUnloadHandler_CrossSite_PreestablishedPipe --CustomTabBarViewBrowserTest.OutOfScopeUrlShouldBeClosable +-IsolatedAppTest.IsolatedAppProcessModel + +# Terminating renderer for bad IPC message, reason 205 +# RFH_ERROR_PROCESS_NON_ERROR_COMMIT +-CaptivePortalBrowserTest.GoBackToTimeout -DNSErrorPageTest.DNSError_DoSearch -DNSErrorPageTest.DNSError_GoBack2 -DNSErrorPageTest.DNSError_GoBack2AndForward -DNSErrorPageTest.DNSError_GoBack2Forward2 --ExtensionCrxInstallerTest.InstallDelayedUntilNextUpdate --ExtensionResourceRequestPolicyTest.WebAccessibleResources + +# A navigation holding a RenderFrameHost to be restored is canceled. The +# RenderFrameHost is deleted unexpectedly: Check failed: !is_active(). -IsolatedAppTest.CrossProcessClientRedirect --IsolatedAppTest.IsolatedAppProcessModel --LocalNTPTest.EmbeddedSearchAPIOnlyAvailableOnNTP --OmniboxPopupContentsViewTest.ClickOmnibox --PageInfoBubbleViewBrowserTest.FocusDoesNotReturnToContentsOnReloadPrompt --PageInfoBubbleViewBrowserTest.FocusReturnsToContentOnClose --PaymentRequestCreditCardEditorTest.CreateNewBillingAddress --PaymentRequestShippingAddressEditorTest.AddInternationalPhoneNumberFromOtherCountry --PaymentRequestShippingAddressEditorTest.AsyncData --PaymentRequestShippingAddressEditorTest.DefaultRegion_RegionCode --PaymentRequestShippingAddressEditorTest.DefaultRegion_RegionName --PaymentRequestShippingAddressEditorTest.FailToLoadRegionData --PaymentRequestShippingAddressEditorTest.NoCountryInvalidState --PaymentRequestShippingAddressEditorTest.NoCountryNoState --PaymentRequestShippingAddressEditorTest.NoCountryValidState_AsyncRegionLoad --PaymentRequestShippingAddressEditorTest.NoCountryValidState_SyncRegionLoad --PaymentRequestShippingAddressEditorTest.SyncData --PaymentRequestShippingAddressEditorTest.SyncDataInIncognito --PaymentRequestShippingAddressEditorTest.TimingOutRegionData + +# No focused view. +-PaymentRequestShippingAddressEditorTest.FocusFirstInvalidField_NotName + +# Test are using a custom NavigateToURL function waiting for the old +# RenderFrameHost to be deleted. This won't happen. -ProcessManagementTest.ExtensionProcessBalancing -ProcessManagerBrowserTest.HostedAppFilesAccess -ProcessManagerBrowserTest.NoBackgroundPage --SSLUITest.GoBackToMixedContent --SubresourceFilterBrowserTest.HistoryNavigationActivation --TabHoverCardBubbleViewBrowserTest.WidgetNotVisibleOnMousePressAfterTabFocus --TabHoverCardBubbleViewBrowserTest.WidgetVisibleOnKeyPressAfterTabFocus --TabHoverCardBubbleViewBrowserTest.WidgetVisibleOnTabCloseButtonFocusAfterTabFocus --TabHoverCardBubbleViewBrowserTest.WidgetVisibleOnTabFocus + +# Test goes back and forth in between a "preview" page and a "normal" page. +# When going back to the first page, it expected to be loaded as a "normal" page, +# but it isn't reloaded at all with the BackForwardCache. -URLLoaderImplementation/PreviewsLitePageServerBrowserTest.LitePagePreviewsNavigation/0 -URLLoaderImplementation/PreviewsLitePageServerBrowserTest.LitePagePreviewsNavigation/1
diff --git a/testing/buildbot/filters/bfcache.content_browsertests.filter b/testing/buildbot/filters/bfcache.content_browsertests.filter index 9c6ed58..2ad2b8ac6 100644 --- a/testing/buildbot/filters/bfcache.content_browsertests.filter +++ b/testing/buildbot/filters/bfcache.content_browsertests.filter
@@ -73,7 +73,6 @@ # Test expects the RenderFrameHost to be deleted after a navigation. It is now # stored into the BackForwardCache instead. It isn't deleted. -RenderFrameHostManagerTest.CleanupOnCrossProcessNavigation --RenderFrameHostManagerTest.LastCommittedOrigin -SitePerProcessBrowserTest.PendingDeletionCheckCompletedOnSubtree -SitePerProcessBrowserTest.SlowUnloadHandlerInIframe -WebContentsBindingSetBrowserTest.CloseOnFrameDeletion
diff --git a/testing/variations/fieldtrial_testing_config.json b/testing/variations/fieldtrial_testing_config.json index 69fbc99..bccedff 100644 --- a/testing/variations/fieldtrial_testing_config.json +++ b/testing/variations/fieldtrial_testing_config.json
@@ -1369,6 +1369,47 @@ ] } ], + "CacheStorageParallelOps": [ + { + "platforms": [ + "windows", + "mac", + "chromeos", + "linux", + "android" + ], + "experiments": [ + { + "name": "Enabled16_v1", + "params": { + "max_shares_ops": "16" + }, + "enable_features": [ + "CacheStorageParallelOps" + ] + } + ] + } + ], + "CacheStorageSequence": [ + { + "platforms": [ + "windows", + "mac", + "chromeos", + "linux", + "android" + ], + "experiments": [ + { + "name": "Enabled1", + "enable_features": [ + "CacheStorageSequence" + ] + } + ] + } + ], "CertDualVerificationTrial": [ { "platforms": [ @@ -1436,6 +1477,23 @@ ] } ], + "ClickToCall": [ + { + "platforms": [ + "linux", + "mac", + "windows" + ], + "experiments": [ + { + "name": "Enabled", + "enable_features": [ + "ClickToCallUI" + ] + } + ] + } + ], "ClipboardContentBehavior": [ { "platforms": [ @@ -2432,7 +2490,7 @@ "MaxAllocations": "70", "MaxMetadata": "255", "ProcessSamplingBoost2": "10", - "ProcessSamplingProbability": "0.1" + "ProcessSamplingProbability": "0.05" }, "enable_features": [ "GwpAsanMalloc",
diff --git a/third_party/blink/common/features.cc b/third_party/blink/common/features.cc index 290b3133..cbbc444 100644 --- a/third_party/blink/common/features.cc +++ b/third_party/blink/common/features.cc
@@ -108,11 +108,6 @@ "OffMainThreadDedicatedWorkerScriptFetch", base::FEATURE_DISABLED_BY_DEFAULT}; -// Enable off-the-main-thread service worker script fetch. -// (https://crbug.com/924043) -const base::Feature kOffMainThreadServiceWorkerScriptFetch{ - "OffMainThreadServiceWorkerScriptFetch", base::FEATURE_ENABLED_BY_DEFAULT}; - // Enable browser-initiated dedicated worker script loading // (PlzDedicatedWorker). https://crbug.com/906991 const base::Feature kPlzDedicatedWorker{"PlzDedicatedWorker",
diff --git a/third_party/blink/public/common/features.h b/third_party/blink/public/common/features.h index e52bcbe..3605f11 100644 --- a/third_party/blink/public/common/features.h +++ b/third_party/blink/public/common/features.h
@@ -37,8 +37,6 @@ BLINK_COMMON_EXPORT extern const base::Feature kNavigationPredictor; BLINK_COMMON_EXPORT extern const base::Feature kOffMainThreadDedicatedWorkerScriptFetch; -BLINK_COMMON_EXPORT extern const base::Feature - kOffMainThreadServiceWorkerScriptFetch; BLINK_COMMON_EXPORT extern const base::Feature kPlzDedicatedWorker; BLINK_COMMON_EXPORT extern const base::Feature kPortals; BLINK_COMMON_EXPORT extern const base::Feature
diff --git a/third_party/blink/public/default_100_percent/blink/broken_canvas.png b/third_party/blink/public/default_100_percent/blink/broken_canvas.png index d357c8b..e9185bf 100644 --- a/third_party/blink/public/default_100_percent/blink/broken_canvas.png +++ b/third_party/blink/public/default_100_percent/blink/broken_canvas.png Binary files differ
diff --git a/third_party/blink/public/default_200_percent/blink/broken_canvas.png b/third_party/blink/public/default_200_percent/blink/broken_canvas.png index 5cd9ec97..af387c7 100644 --- a/third_party/blink/public/default_200_percent/blink/broken_canvas.png +++ b/third_party/blink/public/default_200_percent/blink/broken_canvas.png Binary files differ
diff --git a/third_party/blink/public/platform/modules/service_worker/web_service_worker_network_provider.h b/third_party/blink/public/platform/modules/service_worker/web_service_worker_network_provider.h index f63aaf0..75b8a94 100644 --- a/third_party/blink/public/platform/modules/service_worker/web_service_worker_network_provider.h +++ b/third_party/blink/public/platform/modules/service_worker/web_service_worker_network_provider.h
@@ -48,11 +48,8 @@ // // It is owned by DocumentLoader and only used on the main thread. // -// Currently the Blink embedder has implementations for service worker clients -// (frames and shared workers), and service workers themselves. Note that for -// workers, the interface is only used for requests from the shadow page -// (WorkerShadowPage). For hooking into off-the-main-thread loading from -// workers, the embedder can implement WebWorkerFetchContext. +// Currently the Blink embedder has implementations for frames. For hooking +// into loading from workers, the embedder can implement WebWorkerFetchContext. class WebServiceWorkerNetworkProvider { public: virtual ~WebServiceWorkerNetworkProvider() = default;
diff --git a/third_party/blink/public/web/modules/service_worker/web_service_worker_context_client.h b/third_party/blink/public/web/modules/service_worker/web_service_worker_context_client.h index a4338de..dc05b6c 100644 --- a/third_party/blink/public/web/modules/service_worker/web_service_worker_context_client.h +++ b/third_party/blink/public/web/modules/service_worker/web_service_worker_context_client.h
@@ -50,7 +50,6 @@ namespace blink { class WebServiceWorkerContextProxy; -class WebServiceWorkerNetworkProvider; class WebString; // Used to pass the mojom struct blink.mojom.FetchEventPreloadHandle across the @@ -198,20 +197,6 @@ // timeout. virtual void RequestTermination(RequestTerminationCallback) {} - // On-main-thread start up: - // Creates a network provider for the main script fetch. - // This is called on the main thread. - virtual std::unique_ptr<WebServiceWorkerNetworkProvider> - CreateServiceWorkerNetworkProviderOnMainThread() = 0; - - // On-main-thread start up: - // Creates a WebWorkerFetchContext for subresource fetches on a service - // worker. This is called on the main thread. - virtual scoped_refptr<blink::WebWorkerFetchContext> - CreateWorkerFetchContextOnMainThreadLegacy(WebServiceWorkerNetworkProvider*) { - return nullptr; - } - // Off-main-thread start up: // Creates a WebWorkerFetchContext for subresource fetches on a service // worker. This is called on the main thread.
diff --git a/third_party/blink/public/web/web_shared_worker.h b/third_party/blink/public/web/web_shared_worker.h index 6a60d9e1..5163db6 100644 --- a/third_party/blink/public/web/web_shared_worker.h +++ b/third_party/blink/public/web/web_shared_worker.h
@@ -36,15 +36,10 @@ #include "base/unguessable_token.h" #include "mojo/public/cpp/system/message_pipe.h" #include "services/network/public/mojom/ip_address_space.mojom-shared.h" -#include "third_party/blink/public/common/privacy_preferences.h" #include "third_party/blink/public/mojom/csp/content_security_policy.mojom-shared.h" #include "third_party/blink/public/platform/task_type.h" #include "third_party/blink/public/platform/web_common.h" -namespace network { -class SharedURLLoaderFactory; -} - namespace blink { class MessagePortChannel; @@ -71,11 +66,10 @@ mojom::ContentSecurityPolicyType, network::mojom::IPAddressSpace, const base::UnguessableToken& devtools_worker_token, - PrivacyPreferences privacy_preferences, - scoped_refptr<network::SharedURLLoaderFactory> loader_factory, mojo::ScopedMessagePipeHandle content_settings_handle, mojo::ScopedMessagePipeHandle interface_provider, - mojo::ScopedMessagePipeHandle browser_interface_broker) = 0; + mojo::ScopedMessagePipeHandle browser_interface_broker, + bool pause_worker_context_on_start) = 0; // Sends a connect event to the SharedWorker context. virtual void Connect(MessagePortChannel) = 0; @@ -83,8 +77,6 @@ // Invoked to shutdown the worker when there are no more associated documents. // This eventually deletes this instance. virtual void TerminateWorkerContext() = 0; - - virtual void PauseWorkerContextOnStart() = 0; }; } // namespace blink
diff --git a/third_party/blink/renderer/bindings/core/v8/serialization/post_message_helper.cc b/third_party/blink/renderer/bindings/core/v8/serialization/post_message_helper.cc index 96fea5a..3332019 100644 --- a/third_party/blink/renderer/bindings/core/v8/serialization/post_message_helper.cc +++ b/third_party/blink/renderer/bindings/core/v8/serialization/post_message_helper.cc
@@ -71,7 +71,7 @@ if (exception_state.HadException()) return nullptr; - // Neuter the original array buffers on the sender context. + // Detach the original array buffers on the sender context. SerializedScriptValue::TransferArrayBufferContents( isolate, transferable_array_buffers, exception_state); if (exception_state.HadException())
diff --git a/third_party/blink/renderer/bindings/core/v8/serialization/serialized_script_value.cc b/third_party/blink/renderer/bindings/core/v8/serialization/serialized_script_value.cc index 87e2bf2..6a92607 100644 --- a/third_party/blink/renderer/bindings/core/v8/serialization/serialized_script_value.cc +++ b/third_party/blink/renderer/bindings/core/v8/serialization/serialized_script_value.cc
@@ -692,13 +692,13 @@ for (auto* it = array_buffers.begin(); it != array_buffers.end(); ++it) { DOMArrayBufferBase* array_buffer = *it; - if (array_buffer->IsNeutered()) { + if (array_buffer->IsDetached()) { wtf_size_t index = static_cast<wtf_size_t>(std::distance(array_buffers.begin(), it)); exception_state.ThrowDOMException(DOMExceptionCode::kDataCloneError, "ArrayBuffer at index " + String::Number(index) + - " is already neutered."); + " is already detached."); return ArrayBufferContentsArray(); } }
diff --git a/third_party/blink/renderer/bindings/core/v8/serialization/serialized_script_value_threaded_test.cc b/third_party/blink/renderer/bindings/core/v8/serialization/serialized_script_value_threaded_test.cc index f7726284..d3b4947c 100644 --- a/third_party/blink/renderer/bindings/core/v8/serialization/serialized_script_value_threaded_test.cc +++ b/third_party/blink/renderer/bindings/core/v8/serialization/serialized_script_value_threaded_test.cc
@@ -42,7 +42,7 @@ ToV8(array_buffer, scope.GetContext()->Global(), scope.GetIsolate()), options, ASSERT_NO_EXCEPTION); EXPECT_TRUE(serialized); - EXPECT_TRUE(array_buffer->IsNeutered()); + EXPECT_TRUE(array_buffer->IsDetached()); // Deserialize the serialized value on the worker. // Intentionally keep a reference on this thread while this occurs.
diff --git a/third_party/blink/renderer/bindings/core/v8/serialization/v8_script_value_serializer.cc b/third_party/blink/renderer/bindings/core/v8/serialization/v8_script_value_serializer.cc index e93bcaa..90821da 100644 --- a/third_party/blink/renderer/bindings/core/v8/serialization/v8_script_value_serializer.cc +++ b/third_party/blink/renderer/bindings/core/v8/serialization/v8_script_value_serializer.cc
@@ -108,7 +108,7 @@ } DCHECK(wrote_value); - // Finalize the transfer (e.g. neutering array buffers). + // Finalize the transfer (e.g. detaching array buffers). FinalizeTransfer(exception_state); if (exception_state.HadException()) return nullptr;
diff --git a/third_party/blink/renderer/bindings/core/v8/serialization/v8_script_value_serializer_test.cc b/third_party/blink/renderer/bindings/core/v8/serialization/v8_script_value_serializer_test.cc index 8eb4edf..de2d7f680 100644 --- a/third_party/blink/renderer/bindings/core/v8/serialization/v8_script_value_serializer_test.cc +++ b/third_party/blink/renderer/bindings/core/v8/serialization/v8_script_value_serializer_test.cc
@@ -211,7 +211,7 @@ EXPECT_FALSE(scope.GetExceptionState().HadException()); } -TEST(V8ScriptValueSerializerTest, NeuteringHappensAfterSerialization) { +TEST(V8ScriptValueSerializerTest, DetachHappensAfterSerialization) { // This object will throw an exception before the [[Transfer]] step. // As a result, the ArrayBuffer will not be transferred. V8TestingScope scope; @@ -220,7 +220,7 @@ "postMessage"); DOMArrayBuffer* array_buffer = DOMArrayBuffer::Create(1, 1); - ASSERT_FALSE(array_buffer->IsNeutered()); + ASSERT_FALSE(array_buffer->IsDetached()); v8::Local<v8::Value> object = Eval("({ get a() { throw 'party'; }})", scope); Transferables transferables; transferables.array_buffers.push_back(array_buffer); @@ -229,7 +229,7 @@ ASSERT_TRUE(exception_state.HadException()); EXPECT_FALSE(HadDOMExceptionInCoreTest( "DataCloneError", scope.GetScriptState(), exception_state)); - EXPECT_FALSE(array_buffer->IsNeutered()); + EXPECT_FALSE(array_buffer->IsDetached()); } TEST(V8ScriptValueSerializerTest, RoundTripDOMPoint) {
diff --git a/third_party/blink/renderer/bindings/modules/v8/v8_binding_for_modules.cc b/third_party/blink/renderer/bindings/modules/v8/v8_binding_for_modules.cc index ff1a21a..52ccbeed 100644 --- a/third_party/blink/renderer/bindings/modules/v8/v8_binding_for_modules.cc +++ b/third_party/blink/renderer/bindings/modules/v8/v8_binding_for_modules.cc
@@ -191,8 +191,8 @@ // https://w3c.github.io/IndexedDB/#convert-a-key-to-a-value if (value->IsArrayBuffer()) { DOMArrayBuffer* buffer = V8ArrayBuffer::ToImpl(value.As<v8::Object>()); - if (buffer->IsNeutered()) { - exception_state.ThrowTypeError("The ArrayBuffer is neutered."); + if (buffer->IsDetached()) { + exception_state.ThrowTypeError("The ArrayBuffer is detached."); return nullptr; } const char* start = static_cast<const char*>(buffer->Data()); @@ -202,8 +202,8 @@ if (value->IsArrayBufferView()) { DOMArrayBufferView* view = V8ArrayBufferView::ToImpl(value.As<v8::Object>()); - if (view->buffer()->IsNeutered()) { - exception_state.ThrowTypeError("The viewed ArrayBuffer is neutered."); + if (view->buffer()->IsDetached()) { + exception_state.ThrowTypeError("The viewed ArrayBuffer is detached."); return nullptr; } const char* start = static_cast<const char*>(view->BaseAddress());
diff --git a/third_party/blink/renderer/core/css/css_default_style_sheets.cc b/third_party/blink/renderer/core/css/css_default_style_sheets.cc index 81efb4960..fcab6adc 100644 --- a/third_party/blink/renderer/core/css/css_default_style_sheets.cc +++ b/third_party/blink/renderer/core/css/css_default_style_sheets.cc
@@ -30,6 +30,7 @@ #include "third_party/blink/renderer/core/css/css_default_style_sheets.h" +#include "third_party/blink/public/resources/grit/blink_resources.h" #include "third_party/blink/renderer/core/css/media_query_evaluator.h" #include "third_party/blink/renderer/core/css/rule_set.h" #include "third_party/blink/renderer/core/css/style_sheet_contents.h" @@ -85,13 +86,15 @@ CSSDefaultStyleSheets::CSSDefaultStyleSheets() : media_controls_style_sheet_loader_(nullptr) { // Strict-mode rules. - String default_rules = GetDataResourceAsASCIIString("html.css") + + String default_rules = UncompressResourceAsASCIIString(IDR_UASTYLE_HTML_CSS) + LayoutTheme::GetTheme().ExtraDefaultStyleSheet(); + default_style_sheet_ = ParseUASheet(default_rules); // Quirks-mode rules. - String quirks_rules = GetDataResourceAsASCIIString("quirks.css") + - LayoutTheme::GetTheme().ExtraQuirksStyleSheet(); + String quirks_rules = + UncompressResourceAsASCIIString(IDR_UASTYLE_QUIRKS_CSS) + + LayoutTheme::GetTheme().ExtraQuirksStyleSheet(); quirks_style_sheet_ = ParseUASheet(quirks_rules); InitializeDefaultStyles(); @@ -140,8 +143,8 @@ if (!default_view_source_style_) { default_view_source_style_ = MakeGarbageCollected<RuleSet>(); // Loaded stylesheet is leaked on purpose. - StyleSheetContents* stylesheet = - ParseUASheet(GetDataResourceAsASCIIString("view-source.css")); + StyleSheetContents* stylesheet = ParseUASheet( + UncompressResourceAsASCIIString(IDR_UASTYLE_VIEW_SOURCE_CSS)); default_view_source_style_->AddRulesFromSheet(stylesheet, ScreenEval()); } return default_view_source_style_; @@ -151,15 +154,15 @@ CSSDefaultStyleSheets::EnsureXHTMLMobileProfileStyleSheet() { if (!xhtml_mobile_profile_style_sheet_) { xhtml_mobile_profile_style_sheet_ = - ParseUASheet(GetDataResourceAsASCIIString("xhtmlmp.css")); + ParseUASheet(UncompressResourceAsASCIIString(IDR_UASTYLE_XHTMLMP_CSS)); } return xhtml_mobile_profile_style_sheet_; } StyleSheetContents* CSSDefaultStyleSheets::EnsureMobileViewportStyleSheet() { if (!mobile_viewport_style_sheet_) { - mobile_viewport_style_sheet_ = - ParseUASheet(GetDataResourceAsASCIIString("viewportAndroid.css")); + mobile_viewport_style_sheet_ = ParseUASheet( + UncompressResourceAsASCIIString(IDR_UASTYLE_VIEWPORT_ANDROID_CSS)); } return mobile_viewport_style_sheet_; } @@ -167,8 +170,8 @@ StyleSheetContents* CSSDefaultStyleSheets::EnsureTelevisionViewportStyleSheet() { if (!television_viewport_style_sheet_) { - television_viewport_style_sheet_ = - ParseUASheet(GetDataResourceAsASCIIString("viewportTelevision.css")); + television_viewport_style_sheet_ = ParseUASheet( + UncompressResourceAsASCIIString(IDR_UASTYLE_VIEWPORT_TELEVISION_CSS)); } return television_viewport_style_sheet_; } @@ -178,7 +181,8 @@ bool changed_default_style = false; // FIXME: We should assert that the sheet only styles SVG elements. if (element.IsSVGElement() && !svg_style_sheet_) { - svg_style_sheet_ = ParseUASheet(GetDataResourceAsASCIIString("svg.css")); + svg_style_sheet_ = + ParseUASheet(UncompressResourceAsASCIIString(IDR_UASTYLE_SVG_CSS)); default_style_->AddRulesFromSheet(SvgStyleSheet(), ScreenEval()); default_print_style_->AddRulesFromSheet(SvgStyleSheet(), PrintEval()); changed_default_style = true; @@ -188,7 +192,7 @@ if (element.namespaceURI() == mathml_names::kNamespaceURI && !mathml_style_sheet_) { mathml_style_sheet_ = - ParseUASheet(GetDataResourceAsASCIIString("mathml.css")); + ParseUASheet(UncompressResourceAsASCIIString(IDR_UASTYLE_MATHML_CSS)); default_style_->AddRulesFromSheet(MathmlStyleSheet(), ScreenEval()); default_print_style_->AddRulesFromSheet(MathmlStyleSheet(), PrintEval()); changed_default_style = true; @@ -219,8 +223,9 @@ if (fullscreen_style_sheet_) return; - String fullscreen_rules = GetDataResourceAsASCIIString("fullscreen.css") + - LayoutTheme::GetTheme().ExtraFullscreenStyleSheet(); + String fullscreen_rules = + UncompressResourceAsASCIIString(IDR_UASTYLE_FULLSCREEN_CSS) + + LayoutTheme::GetTheme().ExtraFullscreenStyleSheet(); fullscreen_style_sheet_ = ParseUASheet(fullscreen_rules); default_style_->AddRulesFromSheet(FullscreenStyleSheet(), ScreenEval()); default_quirks_style_->AddRulesFromSheet(FullscreenStyleSheet(),
diff --git a/third_party/blink/renderer/core/exported/prerendering_test.cc b/third_party/blink/renderer/core/exported/prerendering_test.cc index 40e3236..1c970dff 100644 --- a/third_party/blink/renderer/core/exported/prerendering_test.cc +++ b/third_party/blink/renderer/core/exported/prerendering_test.cc
@@ -35,6 +35,7 @@ #include "base/memory/ptr_util.h" #include "testing/gtest/include/gtest/gtest.h" #include "third_party/blink/public/common/prerender/prerender_rel_type.h" +#include "third_party/blink/public/platform/platform.h" #include "third_party/blink/public/platform/web_cache.h" #include "third_party/blink/public/platform/web_prerender.h" #include "third_party/blink/public/platform/web_prerendering_support.h" @@ -162,7 +163,9 @@ class PrerenderingTest : public testing::Test { public: ~PrerenderingTest() override { - url_test_helpers::UnregisterAllURLsAndClearMemoryCache(); + Platform::Current() + ->GetURLLoaderMockFactory() + ->UnregisterAllURLsAndClearMemoryCache(); } void Initialize(const char* base_url, const char* file_name) {
diff --git a/third_party/blink/renderer/core/exported/web_document_subresource_filter_test.cc b/third_party/blink/renderer/core/exported/web_document_subresource_filter_test.cc index 490682c5..bee856da 100644 --- a/third_party/blink/renderer/core/exported/web_document_subresource_filter_test.cc +++ b/third_party/blink/renderer/core/exported/web_document_subresource_filter_test.cc
@@ -6,6 +6,7 @@ #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" +#include "third_party/blink/public/platform/platform.h" #include "third_party/blink/public/platform/web_cache.h" #include "third_party/blink/public/platform/web_url_loader_mock_factory.h" #include "third_party/blink/public/web/web_document.h" @@ -130,7 +131,9 @@ // testing::Test: void TearDown() override { - url_test_helpers::UnregisterAllURLsAndClearMemoryCache(); + Platform::Current() + ->GetURLLoaderMockFactory() + ->UnregisterAllURLsAndClearMemoryCache(); } SubresourceFilteringWebFrameClient client_;
diff --git a/third_party/blink/renderer/core/exported/web_frame_serializer_sanitization_test.cc b/third_party/blink/renderer/core/exported/web_frame_serializer_sanitization_test.cc index 561442d..7dba928 100644 --- a/third_party/blink/renderer/core/exported/web_frame_serializer_sanitization_test.cc +++ b/third_party/blink/renderer/core/exported/web_frame_serializer_sanitization_test.cc
@@ -31,6 +31,7 @@ #include "third_party/blink/public/web/web_frame_serializer.h" #include "testing/gtest/include/gtest/gtest.h" +#include "third_party/blink/public/platform/platform.h" #include "third_party/blink/public/platform/web_string.h" #include "third_party/blink/public/platform/web_url.h" #include "third_party/blink/public/platform/web_url_loader_mock_factory.h" @@ -68,7 +69,9 @@ WebFrameSerializerSanitizationTest() { helper_.Initialize(); } ~WebFrameSerializerSanitizationTest() override { - url_test_helpers::UnregisterAllURLsAndClearMemoryCache(); + Platform::Current() + ->GetURLLoaderMockFactory() + ->UnregisterAllURLsAndClearMemoryCache(); } String GenerateMHTMLFromHtml(const String& url, const String& file_name) {
diff --git a/third_party/blink/renderer/core/exported/web_frame_serializer_test.cc b/third_party/blink/renderer/core/exported/web_frame_serializer_test.cc index b3b2b69..5acb60a 100644 --- a/third_party/blink/renderer/core/exported/web_frame_serializer_test.cc +++ b/third_party/blink/renderer/core/exported/web_frame_serializer_test.cc
@@ -31,6 +31,7 @@ #include "third_party/blink/public/web/web_frame_serializer.h" #include "testing/gtest/include/gtest/gtest.h" +#include "third_party/blink/public/platform/platform.h" #include "third_party/blink/public/platform/web_string.h" #include "third_party/blink/public/platform/web_url.h" #include "third_party/blink/public/platform/web_url_loader_mock_factory.h" @@ -68,7 +69,9 @@ WebFrameSerializerTest() { helper_.Initialize(); } ~WebFrameSerializerTest() override { - url_test_helpers::UnregisterAllURLsAndClearMemoryCache(); + Platform::Current() + ->GetURLLoaderMockFactory() + ->UnregisterAllURLsAndClearMemoryCache(); } void RegisterMockedImageURLLoad(const String& url) {
diff --git a/third_party/blink/renderer/core/exported/web_frame_test.cc b/third_party/blink/renderer/core/exported/web_frame_test.cc index 3b6b1be..68cc312 100644 --- a/third_party/blink/renderer/core/exported/web_frame_test.cc +++ b/third_party/blink/renderer/core/exported/web_frame_test.cc
@@ -48,6 +48,7 @@ #include "third_party/blink/public/common/page/launching_process_state.h" #include "third_party/blink/public/mojom/fetch/fetch_api_request.mojom-blink.h" #include "third_party/blink/public/mojom/frame/find_in_page.mojom-blink.h" +#include "third_party/blink/public/platform/platform.h" #include "third_party/blink/public/platform/web_cache.h" #include "third_party/blink/public/platform/web_coalesced_input_event.h" #include "third_party/blink/public/platform/web_float_rect.h" @@ -197,7 +198,9 @@ chrome_url_("chrome://") {} ~WebFrameTest() override { - url_test_helpers::UnregisterAllURLsAndClearMemoryCache(); + Platform::Current() + ->GetURLLoaderMockFactory() + ->UnregisterAllURLsAndClearMemoryCache(); } void DisableRendererSchedulerThrottling() { @@ -225,13 +228,6 @@ WebString::FromUTF8(file_name)); } - void RegisterMockedURLLoadWithCustomResponse(const WebURL& full_url, - const WebString& file_path, - WebURLResponse response) { - url_test_helpers::RegisterMockedURLLoadWithCustomResponse( - full_url, file_path, response); - } - void RegisterMockedHttpURLLoadWithCSP(const std::string& file_name, const std::string& csp, bool report_only = false) { @@ -242,7 +238,7 @@ : WebString("Content-Security-Policy"), WebString::FromUTF8(csp)); std::string full_string = base_url_ + file_name; - RegisterMockedURLLoadWithCustomResponse( + url_test_helpers::RegisterMockedURLLoadWithCustomResponse( ToKURL(full_string), test::CoreTestDataPath(WebString::FromUTF8(file_name)), response); } @@ -7002,13 +6998,13 @@ redirect_response.SetMimeType("text/html"); redirect_response.SetHttpStatusCode(302); redirect_response.SetHttpHeaderField("Location", redirect); - RegisterMockedURLLoadWithCustomResponse(test_url, file_path, - redirect_response); + Platform::Current()->GetURLLoaderMockFactory()->RegisterURL( + test_url, redirect_response, file_path); WebURLResponse final_response; final_response.SetMimeType("text/html"); - RegisterMockedURLLoadWithCustomResponse(redirect_url, file_path, - final_response); + Platform::Current()->GetURLLoaderMockFactory()->RegisterURL( + redirect_url, final_response, file_path); frame_test_helpers::WebViewHelper web_view_helper; web_view_helper.InitializeAndLoad(base_url_ + "first_party_redirect.html"); @@ -10934,10 +10930,10 @@ url_test_helpers::RegisterMockedURLLoad( ToKURL(url), test::CoreTestDataPath("not_an_image.ico"), "image/x-icon"); MultipleDataChunkDelegate delegate; - url_test_helpers::SetLoaderDelegate(&delegate); + Platform::Current()->GetURLLoaderMockFactory()->SetLoaderDelegate(&delegate); frame_test_helpers::WebViewHelper helper; helper.InitializeAndLoad(url); - url_test_helpers::SetLoaderDelegate(nullptr); + Platform::Current()->GetURLLoaderMockFactory()->SetLoaderDelegate(nullptr); Document* document = To<LocalFrame>(helper.GetWebView()->GetPage()->MainFrame()) @@ -12404,7 +12400,7 @@ // Because the child frame will have placeholder document loader, the main // frame will not finish loading, so // frame_test_helpers::PumpPendingRequestsForFrameToLoad doesn't work here. - url_test_helpers::ServeAsynchronousRequests(); + Platform::Current()->GetURLLoaderMockFactory()->ServeAsynchronousRequests(); // Overwrite the client-handled child frame navigation with about:blank. WebLocalFrame* child = main_frame->FirstChild()->ToWebLocalFrame();
diff --git a/third_party/blink/renderer/core/exported/web_layer_test.cc b/third_party/blink/renderer/core/exported/web_layer_test.cc index c2d2c56..ffbd4a4 100644 --- a/third_party/blink/renderer/core/exported/web_layer_test.cc +++ b/third_party/blink/renderer/core/exported/web_layer_test.cc
@@ -21,7 +21,6 @@ #include "third_party/blink/renderer/core/testing/sim/sim_test.h" #include "third_party/blink/renderer/platform/graphics/compositing/paint_artifact_compositor.h" #include "third_party/blink/renderer/platform/testing/paint_test_configurations.h" -#include "third_party/blink/renderer/platform/testing/testing_platform_support.h" namespace blink { @@ -33,7 +32,8 @@ } ~WebLayerListTest() override { - platform_->GetURLLoaderMockFactory() + Platform::Current() + ->GetURLLoaderMockFactory() ->UnregisterAllURLsAndClearMemoryCache(); } @@ -112,7 +112,6 @@ frame_test_helpers::TestWebWidgetClient web_widget_client_; std::unique_ptr<frame_test_helpers::WebViewHelper> web_view_helper_; - ScopedTestingPlatformSupport<TestingPlatformSupport> platform_; }; INSTANTIATE_LAYER_LIST_TEST_SUITE_P(WebLayerListTest);
diff --git a/third_party/blink/renderer/core/exported/web_plugin_container_test.cc b/third_party/blink/renderer/core/exported/web_plugin_container_test.cc index cb801633..ba31e537 100644 --- a/third_party/blink/renderer/core/exported/web_plugin_container_test.cc +++ b/third_party/blink/renderer/core/exported/web_plugin_container_test.cc
@@ -37,6 +37,7 @@ #include "cc/layers/layer.h" #include "testing/gtest/include/gtest/gtest.h" #include "third_party/blink/public/common/frame/frame_owner_element_type.h" +#include "third_party/blink/public/platform/platform.h" #include "third_party/blink/public/platform/web_coalesced_input_event.h" #include "third_party/blink/public/platform/web_mouse_wheel_event.h" #include "third_party/blink/public/platform/web_pointer_event.h" @@ -81,7 +82,9 @@ WebPluginContainerTest() : base_url_("http://www.test.com/") {} void TearDown() override { - url_test_helpers::UnregisterAllURLsAndClearMemoryCache(); + Platform::Current() + ->GetURLLoaderMockFactory() + ->UnregisterAllURLsAndClearMemoryCache(); } void CalculateGeometry(WebPluginContainerImpl* plugin_container_impl,
diff --git a/third_party/blink/renderer/core/exported/web_searchable_form_data_test.cc b/third_party/blink/renderer/core/exported/web_searchable_form_data_test.cc index 810e296d..170095ee 100644 --- a/third_party/blink/renderer/core/exported/web_searchable_form_data_test.cc +++ b/third_party/blink/renderer/core/exported/web_searchable_form_data_test.cc
@@ -34,6 +34,7 @@ #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" +#include "third_party/blink/public/platform/platform.h" #include "third_party/blink/public/platform/web_url_loader_mock_factory.h" #include "third_party/blink/public/web/web_document.h" #include "third_party/blink/public/web/web_frame.h" @@ -59,7 +60,9 @@ WebSearchableFormDataTest() = default; ~WebSearchableFormDataTest() override { - url_test_helpers::UnregisterAllURLsAndClearMemoryCache(); + Platform::Current() + ->GetURLLoaderMockFactory() + ->UnregisterAllURLsAndClearMemoryCache(); } frame_test_helpers::WebViewHelper web_view_helper_;
diff --git a/third_party/blink/renderer/core/exported/web_shared_worker_impl.cc b/third_party/blink/renderer/core/exported/web_shared_worker_impl.cc index cf34af7..7f474c0 100644 --- a/third_party/blink/renderer/core/exported/web_shared_worker_impl.cc +++ b/third_party/blink/renderer/core/exported/web_shared_worker_impl.cc
@@ -32,9 +32,11 @@ #include <memory> #include "mojo/public/cpp/bindings/interface_request.h" -#include "services/network/public/cpp/shared_url_loader_factory.h" +#include "services/service_manager/public/mojom/interface_provider.mojom-blink.h" +#include "third_party/blink/public/mojom/browser_interface_broker.mojom-blink.h" #include "third_party/blink/public/mojom/devtools/devtools_agent.mojom-blink.h" #include "third_party/blink/public/mojom/script/script_type.mojom-blink.h" +#include "third_party/blink/public/mojom/worker/worker_content_settings_proxy.mojom-blink.h" #include "third_party/blink/public/platform/modules/service_worker/web_service_worker_network_provider.h" #include "third_party/blink/public/platform/task_type.h" #include "third_party/blink/public/platform/web_content_settings_client.h" @@ -49,9 +51,6 @@ #include "third_party/blink/renderer/core/events/message_event.h" #include "third_party/blink/renderer/core/inspector/console_message.h" #include "third_party/blink/renderer/core/inspector/worker_devtools_params.h" -#include "third_party/blink/renderer/core/loader/document_loader.h" -#include "third_party/blink/renderer/core/loader/frame_load_request.h" -#include "third_party/blink/renderer/core/loader/frame_loader.h" #include "third_party/blink/renderer/core/script/script.h" #include "third_party/blink/renderer/core/workers/global_scope_creation_params.h" #include "third_party/blink/renderer/core/workers/parent_execution_context_task_runners.h" @@ -62,9 +61,6 @@ #include "third_party/blink/renderer/platform/heap/handle.h" #include "third_party/blink/renderer/platform/heap/persistent.h" #include "third_party/blink/renderer/platform/loader/fetch/fetch_client_settings_object_snapshot.h" -#include "third_party/blink/renderer/platform/loader/fetch/resource_fetcher.h" -#include "third_party/blink/renderer/platform/loader/fetch/resource_fetcher_properties.h" -#include "third_party/blink/renderer/platform/loader/fetch/resource_response.h" #include "third_party/blink/renderer/platform/network/content_security_policy_parsers.h" #include "third_party/blink/renderer/platform/weborigin/kurl.h" #include "third_party/blink/renderer/platform/weborigin/security_origin.h" @@ -78,7 +74,6 @@ WebSharedWorkerClient* client, const base::UnguessableToken& appcache_host_id) : client_(client), - creation_address_space_(network::mojom::IPAddressSpace::kPublic), appcache_host_(MakeGarbageCollected<ApplicationCacheHostForSharedWorker>( appcache_host_id, Thread::Current()->GetTaskRunner())) { @@ -108,11 +103,6 @@ // DidTerminateWorkerThread() will be called asynchronously. } -void WebSharedWorkerImpl::OnShadowPageInitialized() { - DCHECK(IsMainThread()); - ContinueStartWorkerContext(); -} - void WebSharedWorkerImpl::CountFeature(WebFeature feature) { DCHECK(IsMainThread()); client_->CountFeature(feature); @@ -182,47 +172,11 @@ mojom::ContentSecurityPolicyType policy_type, network::mojom::IPAddressSpace creation_address_space, const base::UnguessableToken& devtools_worker_token, - PrivacyPreferences privacy_preferences, - scoped_refptr<network::SharedURLLoaderFactory> loader_factory, mojo::ScopedMessagePipeHandle content_settings_handle, mojo::ScopedMessagePipeHandle interface_provider, - mojo::ScopedMessagePipeHandle browser_interface_broker) { + mojo::ScopedMessagePipeHandle browser_interface_broker, + bool pause_worker_context_on_start) { DCHECK(IsMainThread()); - script_request_url_ = script_request_url; - name_ = name; - user_agent_ = user_agent; - creation_address_space_ = creation_address_space; - // Chrome doesn't use interface versioning. - content_settings_info_ = mojom::blink::WorkerContentSettingsProxyPtrInfo( - std::move(content_settings_handle), 0u); - pending_interface_provider_.set_handle(std::move(interface_provider)); - - browser_interface_broker_ = - mojo::PendingRemote<mojom::blink::BrowserInterfaceBroker>( - std::move(browser_interface_broker), - mojom::blink::BrowserInterfaceBroker::Version_); - - devtools_worker_token_ = devtools_worker_token; - // |shadow_page_| must be created after |devtools_worker_token_| because it - // triggers creation of a InspectorNetworkAgent that tries to access the - // token. - shadow_page_ = std::make_unique<WorkerShadowPage>( - this, std::move(loader_factory), std::move(privacy_preferences)); - - // We'll continue in OnShadowPageInitialized(). - shadow_page_->Initialize(script_request_url_); -} - -void WebSharedWorkerImpl::OnAppCacheSelected() { - DCHECK(IsMainThread()); - DCHECK(GetWorkerThread()); - GetWorkerThread()->OnAppCacheSelected(); -} - -void WebSharedWorkerImpl::ContinueStartWorkerContext() { - DCHECK(IsMainThread()); - if (asked_to_terminate_) - return; // Creates 'outside settings' used in the "Processing model" algorithm in the // HTML spec: @@ -232,15 +186,15 @@ // correspond to the Document that called 'new SharedWorker()'. The browser // process should pass it up to here. scoped_refptr<const SecurityOrigin> starter_origin = - SecurityOrigin::Create(script_request_url_); + SecurityOrigin::Create(script_request_url); auto* outside_settings_object = MakeGarbageCollected<FetchClientSettingsObjectSnapshot>( - /*global_object_url=*/script_request_url_, - /*base_url=*/script_request_url_, starter_origin, + /*global_object_url=*/script_request_url, + /*base_url=*/script_request_url, starter_origin, network::mojom::ReferrerPolicy::kDefault, /*outgoing_referrer=*/String(), CalculateHttpsState(starter_origin.get()), - AllowedByNosniff::MimeTypeCheck::kLax, creation_address_space_, + AllowedByNosniff::MimeTypeCheck::kLax, creation_address_space, /*insecure_request_policy=*/kBlockAllMixedContent, FetchClientSettingsObject::InsecureNavigationsSet(), /*mixed_autoupgrade_opt_out=*/false); @@ -269,31 +223,27 @@ // GlobalScopeCreationParams are dummy values. They will be updated after // worker script fetch on the worker thread. auto creation_params = std::make_unique<GlobalScopeCreationParams>( - script_request_url_, script_type, - OffMainThreadWorkerScriptFetchOption::kEnabled, name_, user_agent_, + script_request_url, script_type, + OffMainThreadWorkerScriptFetchOption::kEnabled, name, user_agent, std::move(web_worker_fetch_context), Vector<CSPHeaderAndType>(), outside_settings_object->GetReferrerPolicy(), outside_settings_object->GetSecurityOrigin(), starter_secure_context, outside_settings_object->GetHttpsState(), CreateWorkerClients(), std::make_unique<SharedWorkerContentSettingsProxy>( - std::move(content_settings_info_)), + mojom::blink::WorkerContentSettingsProxyPtrInfo( + std::move(content_settings_handle), 0u)), base::nullopt /* response_address_space */, - nullptr /* origin_trial_tokens */, devtools_worker_token_, + nullptr /* origin_trial_tokens */, devtools_worker_token, std::move(worker_settings), kV8CacheOptionsDefault, nullptr /* worklet_module_response_map */, - std::move(pending_interface_provider_), - std::move(browser_interface_broker_), BeginFrameProviderParams(), - nullptr /* parent_feature_policy */, base::UnguessableToken()); - StartWorkerThread(std::move(creation_params), script_request_url_, - String() /* source_code */, *outside_settings_object); -} + service_manager::mojom::blink::InterfaceProviderPtrInfo( + std::move(interface_provider), 0u), + mojo::PendingRemote<mojom::blink::BrowserInterfaceBroker>( + std::move(browser_interface_broker), + mojom::blink::BrowserInterfaceBroker::Version_), + BeginFrameProviderParams(), nullptr /* parent_feature_policy */, + base::UnguessableToken()); -void WebSharedWorkerImpl::StartWorkerThread( - std::unique_ptr<GlobalScopeCreationParams> global_scope_creation_params, - const KURL& script_response_url, - const String& source_code, - const FetchClientSettingsObjectSnapshot& outside_settings_object) { - DCHECK(IsMainThread()); reporting_proxy_ = MakeGarbageCollected<SharedWorkerReportingProxy>( this, ParentExecutionContextTaskRunners::Create()); worker_thread_ = std::make_unique<SharedWorkerThread>(*reporting_proxy_); @@ -303,17 +253,17 @@ WorkerBackingThreadStartupData::AtomicsWaitMode::kAllow; auto devtools_params = std::make_unique<WorkerDevToolsParams>(); - devtools_params->devtools_worker_token = devtools_worker_token_; - devtools_params->wait_for_debugger = pause_worker_context_on_start_; + devtools_params->devtools_worker_token = devtools_worker_token; + devtools_params->wait_for_debugger = pause_worker_context_on_start; mojom::blink::DevToolsAgentPtrInfo devtools_agent_ptr_info; devtools_params->agent_request = mojo::MakeRequest(&devtools_agent_ptr_info); mojom::blink::DevToolsAgentHostRequest devtools_agent_host_request = mojo::MakeRequest(&devtools_params->agent_host_ptr_info); - GetWorkerThread()->Start(std::move(global_scope_creation_params), - thread_startup_data, std::move(devtools_params)); + GetWorkerThread()->Start(std::move(creation_params), thread_startup_data, + std::move(devtools_params)); GetWorkerThread()->FetchAndRunClassicScript( - script_request_url_, outside_settings_object.CopyData(), + script_request_url, outside_settings_object->CopyData(), nullptr /* outside_resource_timing_notifier */, v8_inspector::V8StackTraceId()); @@ -323,6 +273,12 @@ devtools_agent_host_request.PassMessagePipe()); } +void WebSharedWorkerImpl::OnAppCacheSelected() { + DCHECK(IsMainThread()); + DCHECK(GetWorkerThread()); + GetWorkerThread()->OnAppCacheSelected(); +} + WorkerClients* WebSharedWorkerImpl::CreateWorkerClients() { auto* worker_clients = MakeGarbageCollected<WorkerClients>(); CoreInitializer::GetInstance().ProvideLocalFileSystemToWorker( @@ -335,10 +291,6 @@ TerminateWorkerThread(); } -void WebSharedWorkerImpl::PauseWorkerContextOnStart() { - pause_worker_context_on_start_ = true; -} - std::unique_ptr<WebSharedWorker> WebSharedWorker::Create( WebSharedWorkerClient* client, const base::UnguessableToken& appcache_host_id) {
diff --git a/third_party/blink/renderer/core/exported/web_shared_worker_impl.h b/third_party/blink/renderer/core/exported/web_shared_worker_impl.h index 9c33996..46ed8a84 100644 --- a/third_party/blink/renderer/core/exported/web_shared_worker_impl.h +++ b/third_party/blink/renderer/core/exported/web_shared_worker_impl.h
@@ -38,26 +38,16 @@ #include "base/memory/scoped_refptr.h" #include "base/memory/weak_ptr.h" #include "services/network/public/mojom/ip_address_space.mojom-blink.h" -#include "services/service_manager/public/mojom/interface_provider.mojom-blink.h" -#include "third_party/blink/public/common/privacy_preferences.h" -#include "third_party/blink/public/mojom/browser_interface_broker.mojom-blink.h" #include "third_party/blink/public/mojom/csp/content_security_policy.mojom-blink.h" -#include "third_party/blink/public/mojom/worker/worker_content_settings_proxy.mojom-blink.h" #include "third_party/blink/public/web/web_shared_worker_client.h" #include "third_party/blink/renderer/core/core_export.h" -#include "third_party/blink/renderer/core/exported/worker_shadow_page.h" #include "third_party/blink/renderer/core/loader/appcache/application_cache_host_for_shared_worker.h" #include "third_party/blink/renderer/core/workers/shared_worker_reporting_proxy.h" #include "third_party/blink/renderer/core/workers/worker_clients.h" #include "third_party/blink/renderer/core/workers/worker_thread.h" -namespace network { -class SharedURLLoaderFactory; -} - namespace blink { -class FetchClientSettingsObjectSnapshot; class SharedWorkerThread; class WebSharedWorkerClient; class WebString; @@ -71,19 +61,12 @@ // Owned by WebSharedWorkerClient. Destroyed in TerminateWorkerThread() or // DidTerminateWorkerThread() via // WebSharedWorkerClient::WorkerContextDestroyed(). -class CORE_EXPORT WebSharedWorkerImpl final : public WebSharedWorker, - public WorkerShadowPage::Client { +class CORE_EXPORT WebSharedWorkerImpl final : public WebSharedWorker { public: WebSharedWorkerImpl(WebSharedWorkerClient*, const base::UnguessableToken& appcache_host_id); ~WebSharedWorkerImpl() override; - // WorkerShadowPage::Client overrides. - void OnShadowPageInitialized() override; - WebLocalFrameClient::AppCacheType GetAppCacheType() override { - return WebLocalFrameClient::AppCacheType::kAppCacheForSharedWorker; - } - // WebSharedWorker methods: void StartWorkerContext( const WebURL&, @@ -93,14 +76,12 @@ mojom::ContentSecurityPolicyType, network::mojom::IPAddressSpace, const base::UnguessableToken& devtools_worker_token, - PrivacyPreferences privacy_preferences, - scoped_refptr<network::SharedURLLoaderFactory> loader_factory, mojo::ScopedMessagePipeHandle content_settings_handle, mojo::ScopedMessagePipeHandle interface_provider, - mojo::ScopedMessagePipeHandle browser_interface_broker) override; + mojo::ScopedMessagePipeHandle browser_interface_broker, + bool pause_worker_context_on_start) override; void Connect(MessagePortChannel) override; void TerminateWorkerContext() override; - void PauseWorkerContextOnStart() override; // Callback methods for SharedWorkerReportingProxy. void CountFeature(WebFeature); @@ -118,42 +99,18 @@ void TerminateWorkerThread(); void OnAppCacheSelected(); - void ContinueStartWorkerContext(); - void StartWorkerThread( - std::unique_ptr<GlobalScopeCreationParams>, - const KURL& script_response_url, - const String& source_code, - const FetchClientSettingsObjectSnapshot& outside_settings_object); + WorkerClients* CreateWorkerClients(); void ConnectTaskOnWorkerThread(MessagePortChannel); - std::unique_ptr<WorkerShadowPage> shadow_page_; - // Unique worker token used by DevTools to attribute different instrumentation - // to the same worker. - base::UnguessableToken devtools_worker_token_; - Persistent<SharedWorkerReportingProxy> reporting_proxy_; std::unique_ptr<SharedWorkerThread> worker_thread_; - mojom::blink::WorkerContentSettingsProxyPtrInfo content_settings_info_; // |client_| owns |this|. WebSharedWorkerClient* client_; bool asked_to_terminate_ = false; - bool pause_worker_context_on_start_ = false; - - WebURL script_request_url_; - WebString name_; - WebString user_agent_; - network::mojom::IPAddressSpace creation_address_space_; - - // TODO(crbug.com/990845): remove when no longer used. - service_manager::mojom::blink::InterfaceProviderPtrInfo - pending_interface_provider_; - - mojo::PendingRemote<mojom::blink::BrowserInterfaceBroker> - browser_interface_broker_; Persistent<ApplicationCacheHostForSharedWorker> appcache_host_;
diff --git a/third_party/blink/renderer/core/exported/web_view_test.cc b/third_party/blink/renderer/core/exported/web_view_test.cc index ec3b77a63..143c6376 100644 --- a/third_party/blink/renderer/core/exported/web_view_test.cc +++ b/third_party/blink/renderer/core/exported/web_view_test.cc
@@ -46,6 +46,7 @@ #include "third_party/blink/public/common/frame/frame_owner_element_type.h" #include "third_party/blink/public/common/manifest/web_display_mode.h" #include "third_party/blink/public/mojom/frame/document_interface_broker.mojom-blink.h" +#include "third_party/blink/public/platform/platform.h" #include "third_party/blink/public/platform/web_coalesced_input_event.h" #include "third_party/blink/public/platform/web_cursor_info.h" #include "third_party/blink/public/platform/web_drag_data.h" @@ -244,7 +245,9 @@ void TearDown() override { EventTiming::SetTickClockForTesting(nullptr); - url_test_helpers::UnregisterAllURLsAndClearMemoryCache(); + Platform::Current() + ->GetURLLoaderMockFactory() + ->UnregisterAllURLsAndClearMemoryCache(); } protected:
diff --git a/third_party/blink/renderer/core/frame/visual_viewport_test.cc b/third_party/blink/renderer/core/frame/visual_viewport_test.cc index d82970c..ef25053 100644 --- a/third_party/blink/renderer/core/frame/visual_viewport_test.cc +++ b/third_party/blink/renderer/core/frame/visual_viewport_test.cc
@@ -10,6 +10,7 @@ #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" #include "third_party/blink/public/mojom/fetch/fetch_api_request.mojom-blink.h" +#include "third_party/blink/public/platform/platform.h" #include "third_party/blink/public/platform/web_coalesced_input_event.h" #include "third_party/blink/public/platform/web_input_event.h" #include "third_party/blink/public/platform/web_layer_tree_view.h" @@ -102,7 +103,9 @@ } ~VisualViewportTest() override { - url_test_helpers::UnregisterAllURLsAndClearMemoryCache(); + Platform::Current() + ->GetURLLoaderMockFactory() + ->UnregisterAllURLsAndClearMemoryCache(); } void NavigateTo(const std::string& url) {
diff --git a/third_party/blink/renderer/core/html/canvas/image_data.cc b/third_party/blink/renderer/core/html/canvas/image_data.cc index 900544d..c82e3c4 100644 --- a/third_party/blink/renderer/core/html/canvas/image_data.cc +++ b/third_party/blink/renderer/core/html/canvas/image_data.cc
@@ -550,7 +550,7 @@ EventTarget& event_target, base::Optional<IntRect> crop_rect, const ImageBitmapOptions* options) { - if (BufferBase()->IsNeutered()) { + if (BufferBase()->IsDetached()) { return ScriptPromise::RejectWithDOMException( script_state, MakeGarbageCollected<DOMException>( DOMExceptionCode::kInvalidStateError,
diff --git a/third_party/blink/renderer/core/html/forms/external_popup_menu_test.cc b/third_party/blink/renderer/core/html/forms/external_popup_menu_test.cc index 17dee47..b1fda914 100644 --- a/third_party/blink/renderer/core/html/forms/external_popup_menu_test.cc +++ b/third_party/blink/renderer/core/html/forms/external_popup_menu_test.cc
@@ -7,6 +7,7 @@ #include <memory> #include "testing/gtest/include/gtest/gtest.h" +#include "third_party/blink/public/platform/platform.h" #include "third_party/blink/public/platform/web_url_loader_mock_factory.h" #include "third_party/blink/public/web/web_external_popup_menu.h" #include "third_party/blink/public/web/web_popup_menu_info.h" @@ -102,7 +103,9 @@ WebView()->SetUseExternalPopupMenus(true); } void TearDown() override { - url_test_helpers::UnregisterAllURLsAndClearMemoryCache(); + Platform::Current() + ->GetURLLoaderMockFactory() + ->UnregisterAllURLsAndClearMemoryCache(); } void RegisterMockedURLLoad(const std::string& file_name) {
diff --git a/third_party/blink/renderer/core/html/parser/html_preload_scanner_test.cc b/third_party/blink/renderer/core/html/parser/html_preload_scanner_test.cc index 766bfc88..69e1fb5 100644 --- a/third_party/blink/renderer/core/html/parser/html_preload_scanner_test.cc +++ b/third_party/blink/renderer/core/html/parser/html_preload_scanner_test.cc
@@ -7,6 +7,7 @@ #include <memory> #include "base/strings/stringprintf.h" #include "testing/gtest/include/gtest/gtest.h" +#include "third_party/blink/public/platform/platform.h" #include "third_party/blink/public/platform/web_client_hints_type.h" #include "third_party/blink/public/platform/web_runtime_features.h" #include "third_party/blink/public/platform/web_url_loader_mock_factory.h" @@ -21,7 +22,6 @@ #include "third_party/blink/renderer/platform/exported/wrapped_resource_response.h" #include "third_party/blink/renderer/platform/loader/fetch/client_hints_preferences.h" #include "third_party/blink/renderer/platform/testing/runtime_enabled_features_test_helpers.h" -#include "third_party/blink/renderer/platform/testing/testing_platform_support.h" #include "third_party/blink/renderer/platform/weborigin/security_origin.h" namespace blink { @@ -218,8 +218,6 @@ kPreloadDisabled, }; - ScopedTestingPlatformSupport<TestingPlatformSupport> platform_; - MediaValuesCached::MediaValuesCachedData CreateMediaValuesData() { MediaValuesCached::MediaValuesCachedData data; data.viewport_width = 500; @@ -1154,7 +1152,7 @@ network::mojom::ReferrerPolicy::kAlways); KURL preload_url("http://example.test/sheet.css"); - platform_->GetURLLoaderMockFactory()->RegisterURL( + Platform::Current()->GetURLLoaderMockFactory()->RegisterURL( preload_url, WrappedResourceResponse(ResourceResponse()), ""); ReferrerPolicyTestCase test_case = {
diff --git a/third_party/blink/renderer/core/input/ime_on_focus_test.cc b/third_party/blink/renderer/core/input/ime_on_focus_test.cc index 5f3bfe5..69baae1 100644 --- a/third_party/blink/renderer/core/input/ime_on_focus_test.cc +++ b/third_party/blink/renderer/core/input/ime_on_focus_test.cc
@@ -3,6 +3,7 @@ // found in the LICENSE file. #include "testing/gtest/include/gtest/gtest.h" +#include "third_party/blink/public/platform/platform.h" #include "third_party/blink/public/platform/web_coalesced_input_event.h" #include "third_party/blink/public/platform/web_url_loader_mock_factory.h" #include "third_party/blink/public/web/web_document.h" @@ -45,7 +46,9 @@ ImeOnFocusTest() : base_url_("http://www.test.com/") {} void TearDown() override { - url_test_helpers::UnregisterAllURLsAndClearMemoryCache(); + Platform::Current() + ->GetURLLoaderMockFactory() + ->UnregisterAllURLsAndClearMemoryCache(); } protected:
diff --git a/third_party/blink/renderer/core/input/touch_action_test.cc b/third_party/blink/renderer/core/input/touch_action_test.cc index 2729be22..86780a2 100644 --- a/third_party/blink/renderer/core/input/touch_action_test.cc +++ b/third_party/blink/renderer/core/input/touch_action_test.cc
@@ -29,6 +29,7 @@ */ #include "testing/gtest/include/gtest/gtest.h" +#include "third_party/blink/public/platform/platform.h" #include "third_party/blink/public/platform/web_coalesced_input_event.h" #include "third_party/blink/public/platform/web_touch_event.h" #include "third_party/blink/public/platform/web_url_loader_mock_factory.h" @@ -104,7 +105,9 @@ } void TearDown() override { - url_test_helpers::UnregisterAllURLsAndClearMemoryCache(); + Platform::Current() + ->GetURLLoaderMockFactory() + ->UnregisterAllURLsAndClearMemoryCache(); } protected:
diff --git a/third_party/blink/renderer/core/inspector/browser_protocol.pdl b/third_party/blink/renderer/core/inspector/browser_protocol.pdl index 0638975..e63fe09b 100644 --- a/third_party/blink/renderer/core/inspector/browser_protocol.pdl +++ b/third_party/blink/renderer/core/inspector/browser_protocol.pdl
@@ -6198,6 +6198,12 @@ string tag boolean lastChance + command dispatchPeriodicSyncEvent + parameters + string origin + RegistrationID registrationId + string tag + command enable command inspectWorker
diff --git a/third_party/blink/renderer/core/layout/layout_geometry_map_test.cc b/third_party/blink/renderer/core/layout/layout_geometry_map_test.cc index e8b06493..079346f2 100644 --- a/third_party/blink/renderer/core/layout/layout_geometry_map_test.cc +++ b/third_party/blink/renderer/core/layout/layout_geometry_map_test.cc
@@ -32,6 +32,7 @@ #include "build/build_config.h" #include "testing/gtest/include/gtest/gtest.h" +#include "third_party/blink/public/platform/platform.h" #include "third_party/blink/public/platform/web_url_loader_mock_factory.h" #include "third_party/blink/public/web/web_local_frame_client.h" #include "third_party/blink/renderer/core/dom/document.h" @@ -42,7 +43,6 @@ #include "third_party/blink/renderer/core/layout/layout_view.h" #include "third_party/blink/renderer/core/paint/paint_layer.h" #include "third_party/blink/renderer/core/testing/core_unit_test_helper.h" -#include "third_party/blink/renderer/platform/testing/testing_platform_support.h" #include "third_party/blink/renderer/platform/testing/unit_test_helpers.h" #include "third_party/blink/renderer/platform/testing/url_test_helpers.h" @@ -53,7 +53,8 @@ LayoutGeometryMapTest() : base_url_("http://www.test.com/") {} void TearDown() override { - platform_->GetURLLoaderMockFactory() + Platform::Current() + ->GetURLLoaderMockFactory() ->UnregisterAllURLsAndClearMemoryCache(); } @@ -148,7 +149,6 @@ } const std::string base_url_; - ScopedTestingPlatformSupport<TestingPlatformSupport> platform_; }; TEST_F(LayoutGeometryMapTest, SimpleGeometryMapTest) {
diff --git a/third_party/blink/renderer/core/loader/link_loader_test.cc b/third_party/blink/renderer/core/loader/link_loader_test.cc index 040a580..a24e127 100644 --- a/third_party/blink/renderer/core/loader/link_loader_test.cc +++ b/third_party/blink/renderer/core/loader/link_loader_test.cc
@@ -10,6 +10,7 @@ #include "base/test/scoped_feature_list.h" #include "testing/gtest/include/gtest/gtest.h" #include "third_party/blink/public/common/features.h" +#include "third_party/blink/public/platform/platform.h" #include "third_party/blink/public/platform/web_prescient_networking.h" #include "third_party/blink/public/platform/web_url_loader_mock_factory.h" #include "third_party/blink/renderer/bindings/core/v8/v8_binding_for_core.h" @@ -125,7 +126,8 @@ } ~LinkLoaderPreloadTestBase() override { - platform_->GetURLLoaderMockFactory() + Platform::Current() + ->GetURLLoaderMockFactory() ->UnregisterAllURLsAndClearMemoryCache(); } @@ -161,7 +163,6 @@ } } std::unique_ptr<DummyPageHolder> dummy_page_holder_; - ScopedTestingPlatformSupport<TestingPlatformSupport> platform_; }; struct PreloadTestParams { @@ -669,7 +670,8 @@ resource->GetResourceRequest().GetReferrerPolicy()); } } - platform_->GetURLLoaderMockFactory() + Platform::Current() + ->GetURLLoaderMockFactory() ->UnregisterAllURLsAndClearMemoryCache(); } }
diff --git a/third_party/blink/renderer/core/loader/ping_loader_test.cc b/third_party/blink/renderer/core/loader/ping_loader_test.cc index e21c97c..f519b4d 100644 --- a/third_party/blink/renderer/core/loader/ping_loader_test.cc +++ b/third_party/blink/renderer/core/loader/ping_loader_test.cc
@@ -5,13 +5,13 @@ #include "third_party/blink/renderer/core/loader/ping_loader.h" #include "testing/gtest/include/gtest/gtest.h" +#include "third_party/blink/public/platform/platform.h" #include "third_party/blink/public/platform/web_url_loader_mock_factory.h" #include "third_party/blink/renderer/core/frame/local_frame.h" #include "third_party/blink/renderer/core/loader/empty_clients.h" #include "third_party/blink/renderer/core/loader/frame_loader.h" #include "third_party/blink/renderer/core/testing/page_test_base.h" #include "third_party/blink/renderer/platform/network/encoded_form_data.h" -#include "third_party/blink/renderer/platform/testing/testing_platform_support.h" #include "third_party/blink/renderer/platform/testing/unit_test_helpers.h" #include "third_party/blink/renderer/platform/testing/url_test_helpers.h" #include "third_party/blink/renderer/platform/weborigin/kurl.h" @@ -45,7 +45,8 @@ } void TearDown() override { - platform_->GetURLLoaderMockFactory() + Platform::Current() + ->GetURLLoaderMockFactory() ->UnregisterAllURLsAndClearMemoryCache(); } @@ -69,13 +70,12 @@ } // Serve the ping request, since it will otherwise bleed in to the next // test, and once begun there is no way to cancel it directly. - platform_->GetURLLoaderMockFactory()->ServeAsynchronousRequests(); + Platform::Current()->GetURLLoaderMockFactory()->ServeAsynchronousRequests(); return ping_request; } protected: Persistent<PingLocalFrameClient> client_; - ScopedTestingPlatformSupport<TestingPlatformSupport> platform_; }; TEST_F(PingLoaderTest, HTTPSToHTTPS) { @@ -113,7 +113,7 @@ url_test_helpers::RegisterMockedURLLoad( ping_url, test::CoreTestDataPath("bar.html"), "text/html"); PingLoader::SendLinkAuditPing(&GetFrame(), ping_url, destination_url); - platform_->GetURLLoaderMockFactory()->ServeAsynchronousRequests(); + Platform::Current()->GetURLLoaderMockFactory()->ServeAsynchronousRequests(); const ResourceRequest& request = client_->PingRequest(); ASSERT_FALSE(request.IsNull()); ASSERT_EQ(request.Url(), ping_url); @@ -128,7 +128,7 @@ ping_url, test::CoreTestDataPath("bar.html"), "text/html"); PingLoader::SendViolationReport(&GetFrame(), ping_url, EncodedFormData::Create()); - platform_->GetURLLoaderMockFactory()->ServeAsynchronousRequests(); + Platform::Current()->GetURLLoaderMockFactory()->ServeAsynchronousRequests(); const ResourceRequest& request = client_->PingRequest(); ASSERT_FALSE(request.IsNull()); ASSERT_EQ(request.Url(), ping_url); @@ -142,7 +142,7 @@ url_test_helpers::RegisterMockedURLLoad( ping_url, test::CoreTestDataPath("bar.html"), "text/html"); PingLoader::SendBeacon(&GetFrame(), ping_url, "hello"); - platform_->GetURLLoaderMockFactory()->ServeAsynchronousRequests(); + Platform::Current()->GetURLLoaderMockFactory()->ServeAsynchronousRequests(); const ResourceRequest& request = client_->PingRequest(); ASSERT_FALSE(request.IsNull()); ASSERT_EQ(request.Url(), ping_url);
diff --git a/third_party/blink/renderer/core/loader/programmatic_scroll_test.cc b/third_party/blink/renderer/core/loader/programmatic_scroll_test.cc index 342c45c..bdff8d67 100644 --- a/third_party/blink/renderer/core/loader/programmatic_scroll_test.cc +++ b/third_party/blink/renderer/core/loader/programmatic_scroll_test.cc
@@ -3,6 +3,7 @@ // found in the LICENSE file. #include "testing/gtest/include/gtest/gtest.h" +#include "third_party/blink/public/platform/platform.h" #include "third_party/blink/public/platform/web_input_event.h" #include "third_party/blink/public/platform/web_url_loader_mock_factory.h" #include "third_party/blink/public/web/web_frame.h" @@ -20,7 +21,6 @@ #include "third_party/blink/renderer/core/paint/paint_layer_scrollable_area.h" #include "third_party/blink/renderer/core/testing/sim/sim_request.h" #include "third_party/blink/renderer/core/testing/sim/sim_test.h" -#include "third_party/blink/renderer/platform/testing/testing_platform_support.h" #include "third_party/blink/renderer/platform/testing/unit_test_helpers.h" #include "third_party/blink/renderer/platform/testing/url_test_helpers.h" @@ -31,7 +31,8 @@ ProgrammaticScrollTest() : base_url_("http://www.test.com/") {} void TearDown() override { - platform_->GetURLLoaderMockFactory() + Platform::Current() + ->GetURLLoaderMockFactory() ->UnregisterAllURLsAndClearMemoryCache(); } @@ -42,7 +43,6 @@ } String base_url_; - ScopedTestingPlatformSupport<TestingPlatformSupport> platform_; }; TEST_F(ProgrammaticScrollTest, RestoreScrollPositionAndViewStateWithScale) {
diff --git a/third_party/blink/renderer/core/loader/resource/font_resource_test.cc b/third_party/blink/renderer/core/loader/resource/font_resource_test.cc index 376c8a93..887b0669 100644 --- a/third_party/blink/renderer/core/loader/resource/font_resource_test.cc +++ b/third_party/blink/renderer/core/loader/resource/font_resource_test.cc
@@ -8,6 +8,7 @@ #include "testing/gtest/include/gtest/gtest.h" #include "third_party/blink/public/common/features.h" #include "third_party/blink/public/mojom/fetch/fetch_api_request.mojom-blink.h" +#include "third_party/blink/public/platform/platform.h" #include "third_party/blink/public/platform/web_url_loader_mock_factory.h" #include "third_party/blink/renderer/core/css/css_font_face_src_value.h" #include "third_party/blink/renderer/core/loader/resource/mock_font_resource_client.h" @@ -25,7 +26,6 @@ #include "third_party/blink/renderer/platform/loader/testing/test_loader_factory.h" #include "third_party/blink/renderer/platform/loader/testing/test_resource_fetcher_properties.h" #include "third_party/blink/renderer/platform/runtime_enabled_features.h" -#include "third_party/blink/renderer/platform/testing/testing_platform_support.h" #include "third_party/blink/renderer/platform/weborigin/kurl.h" namespace blink { @@ -33,11 +33,10 @@ class FontResourceTest : public testing::Test { public: void TearDown() override { - platform_->GetURLLoaderMockFactory() + Platform::Current() + ->GetURLLoaderMockFactory() ->UnregisterAllURLsAndClearMemoryCache(); } - - ScopedTestingPlatformSupport<TestingPlatformSupport> platform_; }; class CacheAwareFontResourceTest : public FontResourceTest { @@ -60,7 +59,7 @@ ResourceResponse response(url); response.SetHttpStatusCode(200); response.SetHttpHeaderField(http_names::kETag, "1234567890"); - platform_->GetURLLoaderMockFactory()->RegisterURL( + Platform::Current()->GetURLLoaderMockFactory()->RegisterURL( url, WrappedResourceResponse(response), ""); MockFetchContext* context = MakeGarbageCollected<MockFetchContext>(); @@ -76,7 +75,7 @@ Resource* resource1 = FontResource::Fetch(fetch_params1, fetcher, nullptr); ASSERT_FALSE(resource1->ErrorOccurred()); fetcher->StartLoad(resource1); - platform_->GetURLLoaderMockFactory()->ServeAsynchronousRequests(); + Platform::Current()->GetURLLoaderMockFactory()->ServeAsynchronousRequests(); EXPECT_TRUE(resource1->IsLoaded()); EXPECT_FALSE(resource1->ErrorOccurred()); @@ -106,7 +105,7 @@ // StartLoad() can be called from any initiator. Here, call it from the // latter. fetcher->StartLoad(resource3); - platform_->GetURLLoaderMockFactory()->ServeAsynchronousRequests(); + Platform::Current()->GetURLLoaderMockFactory()->ServeAsynchronousRequests(); EXPECT_TRUE(resource3->IsLoaded()); EXPECT_FALSE(resource3->ErrorOccurred()); EXPECT_TRUE(resource2->IsLoaded()); @@ -120,7 +119,7 @@ KURL url("http://127.0.0.1:8000/font.woff"); ResourceResponse response(url); response.SetHttpStatusCode(200); - platform_->GetURLLoaderMockFactory()->RegisterURL( + Platform::Current()->GetURLLoaderMockFactory()->RegisterURL( url, WrappedResourceResponse(response), ""); auto dummy_page_holder = std::make_unique<DummyPageHolder>(IntSize(800, 600)); @@ -178,7 +177,7 @@ EXPECT_TRUE(client3->FontLoadShortLimitExceededCalled()); EXPECT_TRUE(client3->FontLoadLongLimitExceededCalled()); - platform_->GetURLLoaderMockFactory()->ServeAsynchronousRequests(); + Platform::Current()->GetURLLoaderMockFactory()->ServeAsynchronousRequests(); GetMemoryCache()->Remove(&resource); }
diff --git a/third_party/blink/renderer/core/loader/threadable_loader_test.cc b/third_party/blink/renderer/core/loader/threadable_loader_test.cc index c6f3b97..5d8fe7e 100644 --- a/third_party/blink/renderer/core/loader/threadable_loader_test.cc +++ b/third_party/blink/renderer/core/loader/threadable_loader_test.cc
@@ -10,6 +10,7 @@ #include "base/memory/scoped_refptr.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" +#include "third_party/blink/public/platform/platform.h" #include "third_party/blink/public/platform/task_type.h" #include "third_party/blink/public/platform/web_url_load_timing.h" #include "third_party/blink/public/platform/web_url_loader_mock_factory.h" @@ -30,7 +31,6 @@ #include "third_party/blink/renderer/platform/loader/fetch/resource_response.h" #include "third_party/blink/renderer/platform/loader/fetch/resource_timing_info.h" #include "third_party/blink/renderer/platform/loader/testing/web_url_loader_factory_with_mock.h" -#include "third_party/blink/renderer/platform/testing/testing_platform_support.h" #include "third_party/blink/renderer/platform/testing/unit_test_helpers.h" #include "third_party/blink/renderer/platform/testing/url_test_helpers.h" #include "third_party/blink/renderer/platform/weborigin/kurl.h" @@ -91,6 +91,16 @@ return KURL("http://example.com/loop").Copy(); } +void ServeAsynchronousRequests() { + Platform::Current()->GetURLLoaderMockFactory()->ServeAsynchronousRequests(); +} + +void UnregisterAllURLsAndClearMemoryCache() { + Platform::Current() + ->GetURLLoaderMockFactory() + ->UnregisterAllURLsAndClearMemoryCache(); +} + void SetUpSuccessURL() { url_test_helpers::RegisterMockedURLLoad( SuccessURL(), test::CoreTestDataPath(kFileName), "text/html"); @@ -176,17 +186,14 @@ void OnSetUp() { SetUpMockURLs(); } - void OnServeRequests() { - platform_->GetURLLoaderMockFactory()->ServeAsynchronousRequests(); - } + void OnServeRequests() { ServeAsynchronousRequests(); } void OnTearDown() { if (loader_) { loader_->Cancel(); loader_ = nullptr; } - platform_->GetURLLoaderMockFactory() - ->UnregisterAllURLsAndClearMemoryCache(); + UnregisterAllURLsAndClearMemoryCache(); } private: @@ -195,7 +202,6 @@ std::unique_ptr<DummyPageHolder> dummy_page_holder_; Checkpoint checkpoint_; Persistent<ThreadableLoader> loader_; - ScopedTestingPlatformSupport<TestingPlatformSupport> platform_; }; class ThreadableLoaderTest : public testing::Test {
diff --git a/third_party/blink/renderer/core/messaging/blink_transferable_message_mojom_traits_test.cc b/third_party/blink/renderer/core/messaging/blink_transferable_message_mojom_traits_test.cc index 30af6e2..8722987 100644 --- a/third_party/blink/renderer/core/messaging/blink_transferable_message_mojom_traits_test.cc +++ b/third_party/blink/renderer/core/messaging/blink_transferable_message_mojom_traits_test.cc
@@ -111,9 +111,9 @@ out.message->GetArrayBufferContentsArray()[0]; ASSERT_EQ(originalContentsData, deserialized_contents.Data()); - // The original ArrayBufferContents should be neutered. + // The original ArrayBufferContents should be detached. ASSERT_EQ(nullptr, v8_buffer->GetContents().Data()); - ASSERT_TRUE(original_array_buffer->IsNeutered()); + ASSERT_TRUE(original_array_buffer->IsDetached()); } ImageBitmap* CreateBitmap() {
diff --git a/third_party/blink/renderer/core/page/scrolling/main_thread_scrolling_reasons_test.cc b/third_party/blink/renderer/core/page/scrolling/main_thread_scrolling_reasons_test.cc index 98b9f8f..d78c20c 100644 --- a/third_party/blink/renderer/core/page/scrolling/main_thread_scrolling_reasons_test.cc +++ b/third_party/blink/renderer/core/page/scrolling/main_thread_scrolling_reasons_test.cc
@@ -51,7 +51,9 @@ } ~MainThreadScrollingReasonsTest() override { - url_test_helpers::UnregisterAllURLsAndClearMemoryCache(); + Platform::Current() + ->GetURLLoaderMockFactory() + ->UnregisterAllURLsAndClearMemoryCache(); } void NavigateTo(const String& url) {
diff --git a/third_party/blink/renderer/core/page/scrolling/root_scroller_test.cc b/third_party/blink/renderer/core/page/scrolling/root_scroller_test.cc index 07e310b..72d0e7b0 100644 --- a/third_party/blink/renderer/core/page/scrolling/root_scroller_test.cc +++ b/third_party/blink/renderer/core/page/scrolling/root_scroller_test.cc
@@ -3,6 +3,7 @@ // found in the LICENSE file. #include "testing/gtest/include/gtest/gtest.h" +#include "third_party/blink/public/platform/platform.h" #include "third_party/blink/public/platform/web_coalesced_input_event.h" #include "third_party/blink/public/platform/web_url_loader_mock_factory.h" #include "third_party/blink/public/web/web_console_message.h" @@ -63,7 +64,9 @@ ~RootScrollerTest() override { features_backup_.Restore(); - url_test_helpers::UnregisterAllURLsAndClearMemoryCache(); + Platform::Current() + ->GetURLLoaderMockFactory() + ->UnregisterAllURLsAndClearMemoryCache(); } void SetAndSelectRootScroller(Document& document, Element* element) {
diff --git a/third_party/blink/renderer/core/page/scrolling/scrolling_coordinator_test.cc b/third_party/blink/renderer/core/page/scrolling/scrolling_coordinator_test.cc index 1090575..866e423 100644 --- a/third_party/blink/renderer/core/page/scrolling/scrolling_coordinator_test.cc +++ b/third_party/blink/renderer/core/page/scrolling/scrolling_coordinator_test.cc
@@ -28,6 +28,7 @@ #include "cc/layers/layer_sticky_position_constraint.h" #include "cc/layers/picture_layer.h" #include "testing/gtest/include/gtest/gtest.h" +#include "third_party/blink/public/platform/platform.h" #include "third_party/blink/public/platform/web_cache.h" #include "third_party/blink/public/platform/web_layer_tree_view.h" #include "third_party/blink/public/platform/web_rect.h" @@ -109,7 +110,9 @@ } ~ScrollingCoordinatorTest() override { - url_test_helpers::UnregisterAllURLsAndClearMemoryCache(); + Platform::Current() + ->GetURLLoaderMockFactory() + ->UnregisterAllURLsAndClearMemoryCache(); } void NavigateTo(const std::string& url) {
diff --git a/third_party/blink/renderer/core/page/viewport_test.cc b/third_party/blink/renderer/core/page/viewport_test.cc index d759093..9d49455e 100644 --- a/third_party/blink/renderer/core/page/viewport_test.cc +++ b/third_party/blink/renderer/core/page/viewport_test.cc
@@ -29,6 +29,7 @@ */ #include "testing/gtest/include/gtest/gtest.h" +#include "third_party/blink/public/platform/platform.h" #include "third_party/blink/public/platform/web_url_loader_mock_factory.h" #include "third_party/blink/public/web/web_console_message.h" #include "third_party/blink/public/web/web_frame.h" @@ -52,7 +53,6 @@ #include "third_party/blink/renderer/platform/geometry/int_size.h" #include "third_party/blink/renderer/platform/geometry/length.h" #include "third_party/blink/renderer/platform/testing/histogram_tester.h" -#include "third_party/blink/renderer/platform/testing/testing_platform_support.h" #include "third_party/blink/renderer/platform/testing/unit_test_helpers.h" #include "third_party/blink/renderer/platform/testing/url_test_helpers.h" @@ -64,7 +64,8 @@ : base_url_("http://www.test.com/"), chrome_url_("chrome://") {} ~ViewportTest() override { - platform_->GetURLLoaderMockFactory() + Platform::Current() + ->GetURLLoaderMockFactory() ->UnregisterAllURLsAndClearMemoryCache(); } @@ -87,7 +88,6 @@ std::string base_url_; std::string chrome_url_; - ScopedTestingPlatformSupport<TestingPlatformSupport> platform_; }; static void SetViewportSettings(WebSettings* settings) {
diff --git a/third_party/blink/renderer/core/paint/link_highlight_impl_test.cc b/third_party/blink/renderer/core/paint/link_highlight_impl_test.cc index 67eb7d5..e4b7e0b8 100644 --- a/third_party/blink/renderer/core/paint/link_highlight_impl_test.cc +++ b/third_party/blink/renderer/core/paint/link_highlight_impl_test.cc
@@ -30,6 +30,7 @@ #include "cc/layers/picture_layer.h" #include "cc/trees/layer_tree_host.h" #include "testing/gtest/include/gtest/gtest.h" +#include "third_party/blink/public/platform/platform.h" #include "third_party/blink/public/platform/web_float_point.h" #include "third_party/blink/public/platform/web_input_event.h" #include "third_party/blink/public/platform/web_size.h" @@ -82,7 +83,9 @@ } void TearDown() override { - url_test_helpers::UnregisterAllURLsAndClearMemoryCache(); + Platform::Current() + ->GetURLLoaderMockFactory() + ->UnregisterAllURLsAndClearMemoryCache(); // Ensure we fully clean up while scoped settings are enabled. Without this, // garbage collection would occur after ScopedBlinkGenPropertyTreesForTest
diff --git a/third_party/blink/renderer/core/script/import_map.cc b/third_party/blink/renderer/core/script/import_map.cc index c78d79dd..33fa9b5 100644 --- a/third_party/blink/renderer/core/script/import_map.cc +++ b/third_party/blink/renderer/core/script/import_map.cc
@@ -39,41 +39,74 @@ "Ignored an import map value of \"" + key + "\": " + reason); } -// GetKey() and GetValue() returns null String/KURL if the given ParsedSpecifier -// is not valid as keys/values of import maps. -String GetKey(const String& key_string, - const KURL& base_url, - ConsoleLogger& logger) { +// <specdef +// href="https://wicg.github.io/import-maps/#normalize-a-specifier-key"> +String NormalizeSpecifierKey(const String& key_string, + const KURL& base_url, + ConsoleLogger& logger) { + // <spec step="1">If specifierKey is the empty string, then:</spec> + // + // TODO(hiroshige): Implement this step explicitly. Anyway currently empty + // strings are considered as invalid by ParsedSpecifier. + + // <spec step="2">Let url be the result of parsing a URL-like import + // specifier, given specifierKey and baseURL.</spec> ParsedSpecifier key = ParsedSpecifier::Create(key_string, base_url); + switch (key.GetType()) { case ParsedSpecifier::Type::kInvalid: + // TODO(hiroshige): According to the spec, this should be considered as a + // bare specifier. AddIgnoredKeyMessage(logger, key_string, "Invalid key (invalid URL)"); return String(); case ParsedSpecifier::Type::kBare: + // <spec step="4">Return specifierKey.</spec> return key.GetImportMapKeyString(); case ParsedSpecifier::Type::kURL: + // <spec + // href="https://wicg.github.io/import-maps/#parse-a-url-like-import-specifier" + // step="4">If url’s scheme is either a fetch scheme or "std", then return + // url.</spec> + // + // TODO(hiroshige): Perhaps we should move this into ParsedSpecifier. + // + // TODO(hiroshige): Allow "std" URLs as keys. if (!SchemeRegistry::IsFetchScheme(key.GetUrl().Protocol())) { AddIgnoredKeyMessage(logger, key_string, "Invalid key (non-fetch scheme)"); return String(); } + // <spec step="3">If url is not null, then return the serialization of + // url.</spec> return key.GetImportMapKeyString(); } } -KURL GetValue(const String& key, - const String& value_string, - const KURL& base_url, - ConsoleLogger& logger) { +// Step 3.3 of +// <specdef +// href="https://wicg.github.io/import-maps/#sort-and-normalize-a-specifier-map"> +KURL NormalizeValue(const String& key, + const String& value_string, + const KURL& base_url, + ConsoleLogger& logger) { + // <spec step="3.3.2">Let addressURL be the result of parsing a URL-like + // import specifier given potentialAddress and baseURL.</spec> ParsedSpecifier value = ParsedSpecifier::Create(value_string, base_url); + switch (value.GetType()) { case ParsedSpecifier::Type::kInvalid: + // <spec step="3.3.3">If addressURL is null, then:</spec> + // + // <spec step="3.3.3.1">Report a warning to the console that the address + // was invalid.</spec> AddIgnoredValueMessage(logger, key, "Invalid URL: " + value_string); + // <spec step="3.3.1.2">Continue.</spec> return NullURL(); case ParsedSpecifier::Type::kBare: + // TODO(hiroshige): Switch this into aliasing with std: URLs. if (value.GetImportMapKeyString().StartsWith("@std/")) return KURL("import:" + value.GetImportMapKeyString()); @@ -82,98 +115,177 @@ return NullURL(); case ParsedSpecifier::Type::kURL: + // <spec step="3.3.4">If specifierKey ends with U+002F (/), and the + // serialization of addressURL does not end with U+002F (/), then:</spec> + // + // TODO(hiroshige): Implement this. + + // <spec step="3.3.5">Append addressURL to + // validNormalizedAddresses.</spec> return value.GetUrl(); } } } // namespace -// Parse |text| as an import map. -// Errors (e.g. json parsing error, invalid keys/values, etc.) are basically -// ignored, except that they are reported to the console |logger|. +// <specdef +// href="https://wicg.github.io/import-maps/#parse-an-import-map-string"> +// +// Parse |text| as an import map. Errors (e.g. json parsing error, invalid +// keys/values, etc.) are basically ignored, except that they are reported to +// the console |logger|. // TODO(hiroshige): Handle errors in a spec-conformant way once specified. // https://github.com/WICG/import-maps/issues/100 ImportMap* ImportMap::Create(const Modulator& modulator_for_built_in_modules, - const String& text, + const String& input, const KURL& base_url, ConsoleLogger& logger) { - HashMap<String, Vector<KURL>> modules_map; + // <spec step="1">Let parsed be the result of parsing JSON into Infra values + // given input.</spec> + std::unique_ptr<JSONValue> parsed = ParseJSON(input); - std::unique_ptr<JSONValue> root = ParseJSON(text); - if (!root) { + if (!parsed) { logger.AddConsoleMessage(mojom::ConsoleMessageSource::kOther, mojom::ConsoleMessageLevel::kError, "Failed to parse import map: invalid JSON"); + // TODO(hiroshige): Return null. return MakeGarbageCollected<ImportMap>(modulator_for_built_in_modules, - modules_map); + SpecifierMap()); } - std::unique_ptr<JSONObject> root_object = JSONObject::From(std::move(root)); - if (!root_object) { + // <spec step="2">If parsed is not a map, then throw a TypeError indicating + // that the top-level value must be a JSON object.</spec> + std::unique_ptr<JSONObject> parsed_map = JSONObject::From(std::move(parsed)); + if (!parsed_map) { logger.AddConsoleMessage(mojom::ConsoleMessageSource::kOther, mojom::ConsoleMessageLevel::kError, "Failed to parse import map: not an object"); + // TODO(hiroshige): Return null. return MakeGarbageCollected<ImportMap>(modulator_for_built_in_modules, - modules_map); + SpecifierMap()); } - JSONObject* modules = root_object->GetJSONObject("imports"); - if (!modules) { + // <spec step="4">If parsed["imports"] exists, then:</spec> + // + // <spec step="4.1">If parsed["imports"] is not a map, then throw a TypeError + // indicating that the "imports" top-level key must be a JSON object.</spec> + // + // TODO(hiroshige): Handle the non-existing "imports" case separately. + JSONObject* imports = parsed_map->GetJSONObject("imports"); + if (!imports) { logger.AddConsoleMessage( mojom::ConsoleMessageSource::kOther, mojom::ConsoleMessageLevel::kError, "Failed to parse import map: no \"imports\" entry."); + // TODO(hiroshige): Return null. return MakeGarbageCollected<ImportMap>(modulator_for_built_in_modules, - modules_map); + SpecifierMap()); } - for (wtf_size_t i = 0; i < modules->size(); ++i) { - const JSONObject::Entry& entry = modules->at(i); + // <spec step="4.2">Set sortedAndNormalizedImports to the result of sorting + // and normalizing a specifier map given parsed["imports"] and baseURL.</spec> + SpecifierMap sorted_and_normalized_imports = + SortAndNormalizeSpecifierMap(imports, base_url, logger); - const String key = GetKey(entry.first, base_url, logger); - if (key.IsEmpty()) + // TODO(crbug.com/927181): Process "scopes" entry (Steps 5 and 6). + + // TODO(hiroshige): Implement Step 7. + + // <spec step="8">Return the import map whose imports are + // sortedAndNormalizedImports and whose scopes scopes are + // sortedAndNormalizedScopes.</spec> + return MakeGarbageCollected<ImportMap>(modulator_for_built_in_modules, + sorted_and_normalized_imports); +} + +// <specdef +// href="https://wicg.github.io/import-maps/#sort-and-normalize-a-specifier-map"> +ImportMap::SpecifierMap ImportMap::SortAndNormalizeSpecifierMap( + const JSONObject* imports, + const KURL& base_url, + ConsoleLogger& logger) { + // <spec step="1">Let normalized be an empty map.</spec> + SpecifierMap normalized; + + // <spec step="2">First, normalize all entries so that their values are lists. + // For each specifierKey → value of originalMap,</spec> + for (wtf_size_t i = 0; i < imports->size(); ++i) { + const JSONObject::Entry& entry = imports->at(i); + + // <spec step="2.1">Let normalizedSpecifierKey be the result of normalizing + // a specifier key given specifierKey and baseURL.</spec> + const String normalized_specifier_key = + NormalizeSpecifierKey(entry.first, base_url, logger); + + // <spec step="2.2">If normalizedSpecifierKey is null, then continue.</spec> + if (normalized_specifier_key.IsEmpty()) continue; Vector<KURL> values; switch (entry.second->GetType()) { case JSONValue::ValueType::kTypeNull: + // <spec step="2.4">Otherwise, if value is null, then set + // normalized[normalizedSpecifierKey] to a new empty list.</spec> break; case JSONValue::ValueType::kTypeBoolean: case JSONValue::ValueType::kTypeInteger: case JSONValue::ValueType::kTypeDouble: case JSONValue::ValueType::kTypeObject: + // <spec step="2.6">Otherwise, report a warning to the console that + // addresses must be strings, arrays, or null.</spec> AddIgnoredValueMessage(logger, entry.first, "Invalid value type."); + // TODO(hiroshige): Return here. Currently an empty list is set, while + // according to the spec no value should be set. break; case JSONValue::ValueType::kTypeString: { + // <spec step="2.3">If value is a string, then set + // normalized[normalizedSpecifierKey] to ≪value≫.</spec> String value_string; - if (!modules->GetString(entry.first, &value_string)) { + if (!imports->GetString(entry.first, &value_string)) { AddIgnoredValueMessage(logger, entry.first, "Internal error in GetString()."); break; } - KURL value = GetValue(entry.first, value_string, base_url, logger); + KURL value = + NormalizeValue(entry.first, value_string, base_url, logger); + + // <spec step="3.3.5">Append addressURL to + // validNormalizedAddresses.</spec> if (value.IsValid()) values.push_back(value); break; } case JSONValue::ValueType::kTypeArray: { - JSONArray* array = modules->GetArray(entry.first); + // <spec step="2.5">Otherwise, if value is a list, then set + // normalized[normalizedSpecifierKey] to value.</spec> + JSONArray* array = imports->GetArray(entry.first); if (!array) { AddIgnoredValueMessage(logger, entry.first, "Internal error in GetArray()."); break; } + // <spec step="3.3">For each potentialAddress of + // potentialAddresses,</spec> for (wtf_size_t j = 0; j < array->size(); ++j) { + // <spec step="3.3.1">If potentialAddress is not a string, + // then:</spec> String value_string; if (!array->at(j)->AsString(&value_string)) { + // <spec step="3.3.1.1">Report a warning to the console that the + // contents of address arrays must be strings.</spec> AddIgnoredValueMessage(logger, entry.first, "Non-string in the value."); + // <spec step="3.3.1.2">Continue.</spec> continue; } - KURL value = GetValue(entry.first, value_string, base_url, logger); + KURL value = + NormalizeValue(entry.first, value_string, base_url, logger); + + // <spec step="3.3.5">Append addressURL to + // validNormalizedAddresses.</spec> if (value.IsValid()) values.push_back(value); } @@ -181,6 +293,7 @@ } } + // TODO(hiroshige): Move these checks to resolution time. if (values.size() > 2) { AddIgnoredValueMessage(logger, entry.first, "An array of length > 2 is not yet supported."); @@ -192,31 +305,22 @@ logger, entry.first, "Fallback from a non-builtin URL is not yet supported."); values.clear(); - } else if (key != values[1]) { + } else if (normalized_specifier_key != values[1]) { AddIgnoredValueMessage(logger, entry.first, "Fallback URL should match the original URL."); values.clear(); } } - modules_map.Set(key, values); + // <spec step="3.4">Set normalized[specifierKey] to + // validNormalizedAddresses.</spec> + normalized.Set(normalized_specifier_key, values); } - // TODO(crbug.com/927181): Process "scopes" entry. - - return MakeGarbageCollected<ImportMap>(modulator_for_built_in_modules, - modules_map); + return normalized; } -base::Optional<ImportMap::MatchResult> ImportMap::MatchExact( - const ParsedSpecifier& parsed_specifier) const { - const String key = parsed_specifier.GetImportMapKeyString(); - MatchResult exact = imports_.find(key); - if (exact != imports_.end()) - return exact; - return base::nullopt; -} - +// <specdef href="https://wicg.github.io/import-maps/#resolve-an-imports-match"> base::Optional<ImportMap::MatchResult> ImportMap::MatchPrefix( const ParsedSpecifier& parsed_specifier) const { // Do not perform prefix match for non-bare specifiers. @@ -237,13 +341,19 @@ // https://github.com/WICG/import-maps/issues/102 base::Optional<MatchResult> best_match; + // <spec step="1">For each specifierKey → addresses of specifierMap,</spec> for (auto it = imports_.begin(); it != imports_.end(); ++it) { + // <spec step="1.2">If specifierKey ends with U+002F (/) and + // normalizedSpecifier starts with specifierKey, then:</spec> if (!it->key.EndsWith('/')) continue; if (!key.StartsWith(it->key)) continue; + // https://wicg.github.io/import-maps/#longer-or-code-unit-less-than + // We omit code unit comparison, because there can be at most one + // prefix-matching entry with the same length. if (best_match && it->key.length() < (*best_match)->key.length()) continue; @@ -252,46 +362,83 @@ return best_match; } -base::Optional<ImportMap::MatchResult> ImportMap::Match( - const ParsedSpecifier& parsed_specifier) const { - if (auto exact = MatchExact(parsed_specifier)) - return exact; - return MatchPrefix(parsed_specifier); -} - ImportMap::ImportMap(const Modulator& modulator_for_built_in_modules, const HashMap<String, Vector<KURL>>& imports) : imports_(imports), modulator_for_built_in_modules_(&modulator_for_built_in_modules) {} -base::Optional<KURL> ImportMap::Resolve(const ParsedSpecifier& parsed_specifier, - String* debug_message) const { +// <specdef href="https://wicg.github.io/import-maps/#resolve-an-imports-match"> +base::Optional<KURL> ImportMap::ResolveImportsMatch( + const ParsedSpecifier& parsed_specifier, + String* debug_message) const { DCHECK(debug_message); const String key = parsed_specifier.GetImportMapKeyString(); - base::Optional<MatchResult> maybe_matched = Match(parsed_specifier); - - if (!maybe_matched) { - *debug_message = "Import Map: \"" + key + - "\" matches with no entries and thus is not mapped."; - return base::nullopt; + // <spec step="1.1">If specifierKey is normalizedSpecifier, then:</spec> + MatchResult exact = imports_.find(key); + if (exact != imports_.end()) { + return ResolveImportsMatchInternal(key, exact, debug_message); } - MatchResult& matched = *maybe_matched; - const String postfix = key.Substring(matched->key.length()); + // Step 1.2. + if (auto prefix_match = MatchPrefix(parsed_specifier)) { + return ResolveImportsMatchInternal(key, *prefix_match, debug_message); + } + + // <spec step="2">Return null.</spec> + *debug_message = "Import Map: \"" + key + + "\" matches with no entries and thus is not mapped."; + return base::nullopt; +} + +// <specdef href="https://wicg.github.io/import-maps/#resolve-an-imports-match"> +base::Optional<KURL> ImportMap::ResolveImportsMatchInternal( + const String& key, + const MatchResult& matched, + String* debug_message) const { + // <spec step="1.2.2.1">Let afterPrefix be the portion of normalizedSpecifier + // after the initial specifierKey prefix.</spec> + // + // <spec step="1.2.3.1">Let afterPrefix be the portion of normalizedSpecifier + // after the initial specifierKey prefix.</spec> + const String after_prefix = key.Substring(matched->key.length()); + + // <spec step="1.1.3">If addresses’s size is 2, and addresses[0]'s scheme is + // "std", and addresses[1]'s scheme is not "std", then:</spec> + // + // <spec step="1.2.3">If addresses’s size is 2, and addresses[0]'s scheme is + // "std", and addresses[1]'s scheme is not "std", then:</spec> + // + // TODO(hiroshige): Add these checks here. Currently they are checked at + // parsing. for (const KURL& value : matched->value) { - const KURL complete_url = postfix.IsEmpty() ? value : KURL(value, postfix); - if (layered_api::ResolveFetchingURL(*modulator_for_built_in_modules_, - complete_url) + // <spec step="1.2.2.3">Let url be the result of parsing the concatenation + // of the serialization of addresses[0] with afterPrefix.</spec> + // + // <spec step="1.2.3.3">Let url0 be the result of parsing the concatenation + // of the serialization of addresses[0] with afterPrefix; similarly, let + // url1 be the result of parsing the concatenation of the serialization of + // addresses[1] with afterPrefix.</spec> + // + // TODO(hiroshige): Update this according to the spec. + const KURL url = after_prefix.IsEmpty() ? value : KURL(value, after_prefix); + + // <spec step="1.2.3.5">Return url0, if moduleMap[url0] exists; otherwise, + // return url1.</spec> + // + // Note: Here we filter out non-existing built-in modules in all cases. + if (layered_api::ResolveFetchingURL(*modulator_for_built_in_modules_, url) .IsValid()) { *debug_message = "Import Map: \"" + key + "\" matches with \"" + matched->key + "\" and is mapped to " + - complete_url.ElidedString(); - return complete_url; + url.ElidedString(); + return url; } } + // <spec step="1.1.1">If addresses’s size is 0, then throw a TypeError + // indicating that normalizedSpecifier was mapped to no addresses.</spec> *debug_message = "Import Map: \"" + key + "\" matches with \"" + matched->key + "\" but fails to be mapped (no viable URLs)"; return NullURL(); @@ -299,19 +446,27 @@ String ImportMap::ToString() const { StringBuilder builder; - builder.Append("{\n"); + builder.Append("{"); + bool is_first_key = true; for (const auto& it : imports_) { - builder.Append(" \""); + if (!is_first_key) + builder.Append(","); + is_first_key = false; + builder.Append("\n \""); builder.Append(it.key); - builder.Append("\": [\n"); + builder.Append("\": ["); + bool is_first_value = true; for (const auto& v : it.value) { - builder.Append(" \""); + if (!is_first_value) + builder.Append(","); + is_first_value = false; + builder.Append("\n \""); builder.Append(v.GetString()); - builder.Append("\",\n"); + builder.Append("\""); } - builder.Append(" ]\n"); + builder.Append("\n ]"); } - builder.Append("}\n"); + builder.Append("\n}\n"); return builder.ToString(); }
diff --git a/third_party/blink/renderer/core/script/import_map.h b/third_party/blink/renderer/core/script/import_map.h index b4f1d4e2..8129de0 100644 --- a/third_party/blink/renderer/core/script/import_map.h +++ b/third_party/blink/renderer/core/script/import_map.h
@@ -15,6 +15,7 @@ namespace blink { class ConsoleLogger; +class JSONObject; class Modulator; class ParsedSpecifier; @@ -30,23 +31,43 @@ ImportMap(const Modulator&, const HashMap<String, Vector<KURL>>& imports); + // https://wicg.github.io/import-maps/#resolve-an-imports-match // Returns nullopt when not mapped by |this| import map (i.e. the import map // doesn't have corresponding keys). // Returns a null URL when resolution fails. - base::Optional<KURL> Resolve(const ParsedSpecifier&, - String* debug_message) const; + base::Optional<KURL> ResolveImportsMatch(const ParsedSpecifier&, + String* debug_message) const; String ToString() const; void Trace(Visitor*); private: - using MatchResult = HashMap<String, Vector<KURL>>::const_iterator; - base::Optional<MatchResult> Match(const ParsedSpecifier&) const; - base::Optional<MatchResult> MatchExact(const ParsedSpecifier&) const; - base::Optional<MatchResult> MatchPrefix(const ParsedSpecifier&) const; + // <spec href="https://wicg.github.io/import-maps/#specifier-map">A specifier + // map is an ordered map from strings to lists of URLs.</spec> + // + // In Blink, we actually use an unordered map here, and related algorithms + // are implemented differently from the spec. + using SpecifierMap = HashMap<String, Vector<KURL>>; - HashMap<String, Vector<KURL>> imports_; + using MatchResult = SpecifierMap::const_iterator; + + base::Optional<MatchResult> MatchPrefix(const ParsedSpecifier&) const; + static SpecifierMap SortAndNormalizeSpecifierMap(const JSONObject* imports, + const KURL& base_url, + ConsoleLogger&); + + base::Optional<KURL> ResolveImportsMatchInternal( + const String& normalizedSpecifier, + const MatchResult&, + String* debug_message) const; + + // https://wicg.github.io/import-maps/#import-map-imports + SpecifierMap imports_; + + // TODO(crbug.com/927181): Implement + // https://wicg.github.io/import-maps/#import-map-scopes. + Member<const Modulator> modulator_for_built_in_modules_; };
diff --git a/third_party/blink/renderer/core/script/modulator_impl_base.cc b/third_party/blink/renderer/core/script/modulator_impl_base.cc index 0cac6b62..6efbf6a 100644 --- a/third_party/blink/renderer/core/script/modulator_impl_base.cc +++ b/third_party/blink/renderer/core/script/modulator_impl_base.cc
@@ -164,8 +164,8 @@ base::Optional<KURL> mapped_url; if (import_map_) { String import_map_debug_message; - mapped_url = - import_map_->Resolve(parsed_specifier, &import_map_debug_message); + mapped_url = import_map_->ResolveImportsMatch(parsed_specifier, + &import_map_debug_message); // Output the resolution log. This is too verbose to be always shown, but // will be helpful for Web developers (and also Chromium developers) for
diff --git a/third_party/blink/renderer/core/script/parsed_specifier.cc b/third_party/blink/renderer/core/script/parsed_specifier.cc index c5ab903..5c25f66d 100644 --- a/third_party/blink/renderer/core/script/parsed_specifier.cc +++ b/third_party/blink/renderer/core/script/parsed_specifier.cc
@@ -7,34 +7,63 @@ namespace blink { // <specdef href="https://html.spec.whatwg.org/#resolve-a-module-specifier"> +// <specdef label="import-specifier" +// href="https://wicg.github.io/import-maps/#parse-a-url-like-import-specifier"> +// This can return a kBare ParsedSpecifier for cases where the spec concepts +// listed above should return failure/null. The users of ParsedSpecifier should +// handle kBare cases properly, depending on contexts and whether import maps +// are enabled. ParsedSpecifier ParsedSpecifier::Create(const String& specifier, const KURL& base_url) { // <spec step="1">Apply the URL parser to specifier. If the result is not // failure, return the result.</spec> + // + // <spec label="import-specifier" step="2">Let url be the result of parsing + // specifier (with no base URL).</spec> KURL url(NullURL(), specifier); - if (url.IsValid()) + if (url.IsValid()) { + // <spec label="import-specifier" step="4">If url’s scheme is either a fetch + // scheme or "std", then return url.</spec> + // + // TODO(hiroshige): This check is done in the callers of ParsedSpecifier. return ParsedSpecifier(url); + } // <spec step="2">If specifier does not start with the character U+002F // SOLIDUS (/), the two-character sequence U+002E FULL STOP, U+002F SOLIDUS // (./), or the three-character sequence U+002E FULL STOP, U+002E FULL STOP, // U+002F SOLIDUS (../), return failure.</spec> + // + // <spec label="import-specifier" step="1">If specifier starts with "/", "./", + // or "../", then:</spec> if (!specifier.StartsWith("/") && !specifier.StartsWith("./") && !specifier.StartsWith("../")) { // Do not consider an empty specifier as a valid bare specifier. + // + // <spec + // href="https://wicg.github.io/import-maps/#normalize-a-specifier-key" + // step="1">If specifierKey is the empty string, then:</spec> if (specifier.IsEmpty()) return ParsedSpecifier(); + // <spec label="import-specifier" step="3">If url is failure, then return + // null.</spec> return ParsedSpecifier(specifier); } // <spec step="3">Return the result of applying the URL parser to specifier // with base URL as the base URL.</spec> + // + // <spec label="import-specifier" step="1.1">Let url be the result of parsing + // specifier with baseURL as the base URL.</spec> DCHECK(base_url.IsValid()); KURL absolute_url(base_url, specifier); + // <spec label="import-specifier" step="1.3">Return url.</spec> if (absolute_url.IsValid()) return ParsedSpecifier(absolute_url); + // <spec label="import-specifier" step="1.2">If url is failure, then return + // null.</spec> return ParsedSpecifier(); }
diff --git a/third_party/blink/renderer/core/testing/sim/sim_network.cc b/third_party/blink/renderer/core/testing/sim/sim_network.cc index 2004f9f9..637f3e9 100644 --- a/third_party/blink/renderer/core/testing/sim/sim_network.cc +++ b/third_party/blink/renderer/core/testing/sim/sim_network.cc
@@ -6,6 +6,7 @@ #include <memory> #include <utility> +#include "third_party/blink/public/platform/platform.h" #include "third_party/blink/public/platform/web_url_error.h" #include "third_party/blink/public/platform/web_url_loader.h" #include "third_party/blink/public/platform/web_url_loader_client.h" @@ -15,21 +16,22 @@ #include "third_party/blink/renderer/core/loader/document_loader.h" #include "third_party/blink/renderer/core/testing/sim/sim_request.h" #include "third_party/blink/renderer/platform/loader/static_data_navigation_body_loader.h" -#include "third_party/blink/renderer/platform/testing/url_test_helpers.h" namespace blink { static SimNetwork* g_network = nullptr; SimNetwork::SimNetwork() : current_request_(nullptr) { - url_test_helpers::SetLoaderDelegate(this); + Platform::Current()->GetURLLoaderMockFactory()->SetLoaderDelegate(this); DCHECK(!g_network); g_network = this; } SimNetwork::~SimNetwork() { - url_test_helpers::SetLoaderDelegate(nullptr); - url_test_helpers::UnregisterAllURLsAndClearMemoryCache(); + Platform::Current()->GetURLLoaderMockFactory()->SetLoaderDelegate(nullptr); + Platform::Current() + ->GetURLLoaderMockFactory() + ->UnregisterAllURLsAndClearMemoryCache(); g_network = nullptr; } @@ -39,7 +41,7 @@ } void SimNetwork::ServePendingRequests() { - url_test_helpers::ServeAsynchronousRequests(); + Platform::Current()->GetURLLoaderMockFactory()->ServeAsynchronousRequests(); } void SimNetwork::DidReceiveResponse(WebURLLoaderClient* client, @@ -104,13 +106,13 @@ for (const auto& http_header : request.response_http_headers_) response.AddHttpHeaderField(http_header.key, http_header.value); - url_test_helpers::RegisterMockedURLLoadWithCustomResponse(request.url_, "", - response); + Platform::Current()->GetURLLoaderMockFactory()->RegisterURL(request.url_, + response, ""); } void SimNetwork::RemoveRequest(SimRequestBase& request) { requests_.erase(request.url_); - url_test_helpers::RegisterMockedURLUnregister(request.url_); + Platform::Current()->GetURLLoaderMockFactory()->UnregisterURL(request.url_); } bool SimNetwork::FillNavigationParamsResponse(WebNavigationParams* params) {
diff --git a/third_party/blink/renderer/core/trustedtypes/trusted_type_policy_factory.cc b/third_party/blink/renderer/core/trustedtypes/trusted_type_policy_factory.cc index 2574683..46ff9d3a 100644 --- a/third_party/blink/renderer/core/trustedtypes/trusted_type_policy_factory.cc +++ b/third_party/blink/renderer/core/trustedtypes/trusted_type_policy_factory.cc
@@ -25,9 +25,15 @@ const TrustedTypePolicyOptions* policy_options, bool exposed, ExceptionState& exception_state) { + if (!GetExecutionContext()) { + exception_state.ThrowDOMException(DOMExceptionCode::kInvalidStateError, + "The document is detached."); + return nullptr; + } UseCounter::Count(GetExecutionContext(), WebFeature::kTrustedTypesCreatePolicy); if (RuntimeEnabledFeatures::TrustedDOMTypesEnabled(GetExecutionContext()) && + GetExecutionContext()->GetContentSecurityPolicy() && !GetExecutionContext() ->GetContentSecurityPolicy() ->AllowTrustedTypePolicy(policy_name)) {
diff --git a/third_party/blink/renderer/core/typed_arrays/dom_array_buffer.cc b/third_party/blink/renderer/core/typed_arrays/dom_array_buffer.cc index 247081e..11106ed3 100644 --- a/third_party/blink/renderer/core/typed_arrays/dom_array_buffer.cc +++ b/third_party/blink/renderer/core/typed_arrays/dom_array_buffer.cc
@@ -25,22 +25,22 @@ } } -bool DOMArrayBuffer::IsNeuterable(v8::Isolate* isolate) { +bool DOMArrayBuffer::IsDetachable(v8::Isolate* isolate) { Vector<v8::Local<v8::ArrayBuffer>, 4> buffer_handles; v8::HandleScope handle_scope(isolate); AccumulateArrayBuffersForAllWorlds(isolate, this, buffer_handles); - bool is_neuterable = true; + bool is_detachable = true; for (const auto& buffer_handle : buffer_handles) - is_neuterable &= buffer_handle->IsDetachable(); + is_detachable &= buffer_handle->IsDetachable(); - return is_neuterable; + return is_detachable; } bool DOMArrayBuffer::Transfer(v8::Isolate* isolate, WTF::ArrayBufferContents& result) { DOMArrayBuffer* to_transfer = this; - if (!IsNeuterable(isolate)) { + if (!IsDetachable(isolate)) { to_transfer = DOMArrayBuffer::Create(Buffer()->Data(), Buffer()->ByteLength()); }
diff --git a/third_party/blink/renderer/core/typed_arrays/dom_array_buffer.h b/third_party/blink/renderer/core/typed_arrays/dom_array_buffer.h index e4b0699b..296a4a3 100644 --- a/third_party/blink/renderer/core/typed_arrays/dom_array_buffer.h +++ b/third_party/blink/renderer/core/typed_arrays/dom_array_buffer.h
@@ -48,9 +48,9 @@ return Create(Buffer()->Slice(begin)); } - bool IsNeuterable(v8::Isolate*); + bool IsDetachable(v8::Isolate*); - // Transfer the ArrayBuffer if it is neuterable, otherwise make a copy and + // Transfer the ArrayBuffer if it is detachable, otherwise make a copy and // transfer that. bool Transfer(v8::Isolate*, WTF::ArrayBufferContents& result);
diff --git a/third_party/blink/renderer/core/typed_arrays/dom_array_buffer_base.h b/third_party/blink/renderer/core/typed_arrays/dom_array_buffer_base.h index 2e4d9ca..59ca6aa 100644 --- a/third_party/blink/renderer/core/typed_arrays/dom_array_buffer_base.h +++ b/third_party/blink/renderer/core/typed_arrays/dom_array_buffer_base.h
@@ -22,7 +22,7 @@ const void* Data() const { return Buffer()->Data(); } void* Data() { return Buffer()->Data(); } unsigned ByteLength() const { return Buffer()->ByteLength(); } - bool IsNeutered() const { return Buffer()->IsNeutered(); } + bool IsDetached() const { return Buffer()->IsDetached(); } bool IsShared() const { return Buffer()->IsShared(); } v8::Local<v8::Object> Wrap(v8::Isolate*,
diff --git a/third_party/blink/renderer/core/typed_arrays/dom_array_buffer_view.h b/third_party/blink/renderer/core/typed_arrays/dom_array_buffer_view.h index 310855cf..8058229 100644 --- a/third_party/blink/renderer/core/typed_arrays/dom_array_buffer_view.h +++ b/third_party/blink/renderer/core/typed_arrays/dom_array_buffer_view.h
@@ -64,7 +64,7 @@ unsigned byteOffset() const { return View()->ByteOffset(); } unsigned byteLength() const { return View()->ByteLength(); } unsigned TypeSize() const { return View()->TypeSize(); } - void SetNeuterable(bool flag) { return View()->SetNeuterable(flag); } + void SetDetachable(bool flag) { return View()->SetDetachable(flag); } bool IsShared() const { return View()->IsShared(); } void* BaseAddressMaybeShared() const {
diff --git a/third_party/blink/renderer/core/typed_arrays/dom_data_view.cc b/third_party/blink/renderer/core/typed_arrays/dom_data_view.cc index d74a335..448bbff 100644 --- a/third_party/blink/renderer/core/typed_arrays/dom_data_view.cc +++ b/third_party/blink/renderer/core/typed_arrays/dom_data_view.cc
@@ -29,8 +29,8 @@ unsigned TypeSize() const override { return 1; } protected: - void Neuter() override { - ArrayBufferView::Neuter(); + void Detach() override { + ArrayBufferView::Detach(); byte_length_ = 0; }
diff --git a/third_party/blink/renderer/devtools/front_end/resources/ServiceWorkersView.js b/third_party/blink/renderer/devtools/front_end/resources/ServiceWorkersView.js index 28361a6ea..eccad34 100644 --- a/third_party/blink/renderer/devtools/front_end/resources/ServiceWorkersView.js +++ b/third_party/blink/renderer/devtools/front_end/resources/ServiceWorkersView.js
@@ -319,6 +319,8 @@ this._pushNotificationDataSetting = Common.settings.createLocalSetting('pushData', Common.UIString('Test push message from DevTools.')); this._syncTagNameSetting = Common.settings.createLocalSetting('syncTagName', 'test-tag-from-devtools'); + this._periodicSyncTagNameSetting = + Common.settings.createLocalSetting('periodicSyncTagName', 'test-tag-from-devtools'); this._toolbar = section.createToolbar(); this._toolbar.renderAsLinks(); @@ -339,6 +341,11 @@ this._push.bind(this)); this._createSyncNotificationField( Common.UIString('Sync'), this._syncTagNameSetting.get(), Common.UIString('Sync tag'), this._sync.bind(this)); + if (Runtime.experiments.isEnabled('backgroundServicesPeriodicBackgroundSync')) { + this._createSyncNotificationField( + ls`Periodic Sync`, this._periodicSyncTagNameSetting.get(), ls`Periodic Sync tag`, + tag => this._periodicSync(tag)); + } this._linkifier = new Components.Linkifier(); /** @type {!Map<string, !Protocol.Target.TargetInfo>} */ @@ -560,6 +567,14 @@ } /** + * @param {string} tag + */ + _periodicSync(tag) { + this._periodicSyncTagNameSetting.set(tag); + this._manager.dispatchPeriodicSyncEvent(this._registration.id, tag); + } + + /** * @param {!Element} element * @param {?Protocol.Target.TargetInfo} targetInfo */
diff --git a/third_party/blink/renderer/devtools/front_end/resources/resources_strings.grdp b/third_party/blink/renderer/devtools/front_end/resources/resources_strings.grdp index 90b422f..99eaeb8b 100644 --- a/third_party/blink/renderer/devtools/front_end/resources/resources_strings.grdp +++ b/third_party/blink/renderer/devtools/front_end/resources/resources_strings.grdp
@@ -12,12 +12,18 @@ <message name="IDS_DEVTOOLS_09428a9282bbb3ffcf3caa7826f0bf83" desc="Message in Database Model of the Application panel"> An unexpected error <ph name="SQLERROR_CODE">$1s<ex>-197</ex></ph> occurred. </message> + <message name="IDS_DEVTOOLS_0ace6faf288026c1adc56a2a1e7bb6be" desc="Default tag for a periodicsync event in Service Workers View of the Application panel"> + Periodic Sync tag + </message> <message name="IDS_DEVTOOLS_0d6fa553290eb4bf9eabe203a43b01d9" desc="Text in Clear Storage View of the Application panel"> Application cache </message> <message name="IDS_DEVTOOLS_0f558243fbf45f1cd840fff01957f57b" desc="Text in Service Workers View of the Application panel"> Clients </message> + <message name="IDS_DEVTOOLS_10a77618ffc0466753fde85f9bec01fd" desc="Text for button in Service Workers View of the Application panel that dispatches a periodicsync event"> + Periodic Sync + </message> <message name="IDS_DEVTOOLS_1351a3eaa0f925dad980e83905bc1230" desc="Text of a DOM element in Service Workers View of the Application panel"> Worker: <ph name="TARGETINFO_URL">$1s<ex>example.com</ex></ph> </message>
diff --git a/third_party/blink/renderer/devtools/front_end/sdk/ServiceWorkerManager.js b/third_party/blink/renderer/devtools/front_end/sdk/ServiceWorkerManager.js index ddba7a72..a5914df 100644 --- a/third_party/blink/renderer/devtools/front_end/sdk/ServiceWorkerManager.js +++ b/third_party/blink/renderer/devtools/front_end/sdk/ServiceWorkerManager.js
@@ -151,6 +151,18 @@ } /** + * @param {string} registrationId + * @param {string} tag + */ + dispatchPeriodicSyncEvent(registrationId, tag) { + const registration = this._registrations.get(registrationId); + if (!registration) + return; + const origin = Common.ParsedURL.extractOrigin(registration.scopeURL); + this._agent.dispatchPeriodicSyncEvent(origin, registrationId, tag); + } + + /** * @param {string} scope */ _unregister(scope) {
diff --git a/third_party/blink/renderer/modules/accessibility/ax_object_cache_impl.cc b/third_party/blink/renderer/modules/accessibility/ax_object_cache_impl.cc index a32ec80..40bff6d1 100644 --- a/third_party/blink/renderer/modules/accessibility/ax_object_cache_impl.cc +++ b/third_party/blink/renderer/modules/accessibility/ax_object_cache_impl.cc
@@ -140,6 +140,8 @@ document->View()->UnregisterFromLifecycleNotifications(this); } + permission_observer_receiver_.reset(); + #if DCHECK_IS_ON() has_been_disposed_ = true; #endif
diff --git a/third_party/blink/renderer/modules/bluetooth/bluetooth_remote_gatt_characteristic.cc b/third_party/blink/renderer/modules/bluetooth/bluetooth_remote_gatt_characteristic.cc index 2901fd2..e73dc5f8 100644 --- a/third_party/blink/renderer/modules/bluetooth/bluetooth_remote_gatt_characteristic.cc +++ b/third_party/blink/renderer/modules/bluetooth/bluetooth_remote_gatt_characteristic.cc
@@ -176,7 +176,7 @@ script_state, CreateInvalidCharacteristicError()); } - if (value.IsNeutered()) { + if (value.IsDetached()) { return ScriptPromise::RejectWithDOMException( script_state, MakeGarbageCollected<DOMException>(DOMExceptionCode::kInvalidStateError,
diff --git a/third_party/blink/renderer/modules/bluetooth/bluetooth_remote_gatt_descriptor.cc b/third_party/blink/renderer/modules/bluetooth/bluetooth_remote_gatt_descriptor.cc index ae459e8..b3afb424d 100644 --- a/third_party/blink/renderer/modules/bluetooth/bluetooth_remote_gatt_descriptor.cc +++ b/third_party/blink/renderer/modules/bluetooth/bluetooth_remote_gatt_descriptor.cc
@@ -120,7 +120,7 @@ script_state, CreateInvalidDescriptorError()); } - if (value.IsNeutered()) { + if (value.IsDetached()) { return ScriptPromise::RejectWithDOMException( script_state, MakeGarbageCollected<DOMException>(DOMExceptionCode::kInvalidStateError,
diff --git a/third_party/blink/renderer/modules/canvas/canvas2d/base_rendering_context_2d.cc b/third_party/blink/renderer/modules/canvas/canvas2d/base_rendering_context_2d.cc index ca69ced..1122aa82 100644 --- a/third_party/blink/renderer/modules/canvas/canvas2d/base_rendering_context_2d.cc +++ b/third_party/blink/renderer/modules/canvas/canvas2d/base_rendering_context_2d.cc
@@ -1711,9 +1711,9 @@ usage_counters_.num_put_image_data_calls++; usage_counters_.area_put_image_data_calls += dirty_width * dirty_height; - if (data->BufferBase()->IsNeutered()) { + if (data->BufferBase()->IsDetached()) { exception_state.ThrowDOMException(DOMExceptionCode::kInvalidStateError, - "The source data has been neutered."); + "The source data has been detached."); return; }
diff --git a/third_party/blink/renderer/modules/exported/web_embedded_worker_impl.cc b/third_party/blink/renderer/modules/exported/web_embedded_worker_impl.cc index 16faff4..aa32463 100644 --- a/third_party/blink/renderer/modules/exported/web_embedded_worker_impl.cc +++ b/third_party/blink/renderer/modules/exported/web_embedded_worker_impl.cc
@@ -32,11 +32,9 @@ #include <memory> #include <utility> -#include "base/feature_list.h" #include "mojo/public/cpp/bindings/interface_request.h" #include "services/network/public/cpp/shared_url_loader_factory.h" #include "services/network/public/mojom/referrer_policy.mojom-blink.h" -#include "third_party/blink/public/common/features.h" #include "third_party/blink/public/mojom/service_worker/service_worker_installed_scripts_manager.mojom-blink.h" #include "third_party/blink/public/platform/modules/service_worker/web_service_worker_network_provider.h" #include "third_party/blink/public/platform/modules/service_worker/web_service_worker_provider.h" @@ -218,20 +216,8 @@ } void WebEmbeddedWorkerImpl::ResumeAfterDownload() { + // TODO(bashi): Remove this method. This does nothing anymore. DCHECK(!asked_to_terminate_); - - if (base::FeatureList::IsEnabled( - features::kOffMainThreadServiceWorkerScriptFetch)) { - // Do nothing. ServiceWorkerGlobalScope suspends worker execution - // until ReadyToEvaluateScript() is called. - // TODO(bashi): Don't call ResumeAfterDownload() in the browser side - // as we do nothing here. - return; - } - - DCHECK_EQ(pause_after_download_state_, kIsPausedAfterDownload); - pause_after_download_state_ = kDontPauseAfterDownload; - StartWorkerThread(); } void WebEmbeddedWorkerImpl::AddMessageToConsole( @@ -250,56 +236,7 @@ shadow_page_->GetDocument()->SetAddressSpace( worker_start_data_.address_space); - // When off-the-main-thread script fetch is enabled, we don't have to set - // network provider to the shadow page because we don't use shadow page's - // document loader for script fetch. - if (!base::FeatureList::IsEnabled( - features::kOffMainThreadServiceWorkerScriptFetch)) { - DCHECK(worker_context_client_); - shadow_page_->DocumentLoader()->SetServiceWorkerNetworkProvider( - worker_context_client_ - ->CreateServiceWorkerNetworkProviderOnMainThread()); - } - - // If this is an installed service worker, we can start the worker thread - // now. The script will be streamed in by the installed scripts manager in - // parallel. For non-installed scripts, the script must be loaded from network - // before the worker thread can be started. - if (installed_scripts_manager_ && - installed_scripts_manager_->IsScriptInstalled( - worker_start_data_.script_url)) { - DCHECK_EQ(pause_after_download_state_, kDontPauseAfterDownload); - StartWorkerThread(); - return; - } - - // If this is a module service worker, start the worker thread now. The worker - // thread will fetch the script. - if (worker_start_data_.script_type == mojom::ScriptType::kModule) { - StartWorkerThread(); - return; - } - - // Bypass main script loading on the main thread. - if (base::FeatureList::IsEnabled( - features::kOffMainThreadServiceWorkerScriptFetch)) { - StartWorkerThread(); - return; - } - - // Note: We only get here if this is a new (i.e., not installed) service - // worker. - DCHECK(!main_script_loader_); - main_script_loader_ = MakeGarbageCollected<WorkerClassicScriptLoader>(); - main_script_loader_->LoadTopLevelScriptAsynchronously( - *shadow_page_->GetDocument(), shadow_page_->GetDocument()->Fetcher(), - worker_start_data_.script_url, mojom::RequestContextType::SERVICE_WORKER, - network::mojom::RequestMode::kSameOrigin, - network::mojom::CredentialsMode::kSameOrigin, base::OnceClosure(), - Bind(&WebEmbeddedWorkerImpl::OnScriptLoaderFinished, - WTF::Unretained(this))); - // Do nothing here since OnScriptLoaderFinished() might have been already - // invoked and |this| might have been deleted at this point. + StartWorkerThread(); } void WebEmbeddedWorkerImpl::OnScriptLoaderFinished() { @@ -321,12 +258,6 @@ } void WebEmbeddedWorkerImpl::StartWorkerThread() { - // The mechanism of pause-after-download in this class isn't used when - // off-the-main-thread script fetch is enabled. The browser process delays - // initializing the global scope to pause the worker when needed. - DCHECK(base::FeatureList::IsEnabled( - features::kOffMainThreadServiceWorkerScriptFetch) || - pause_after_download_state_ == kDontPauseAfterDownload); DCHECK(!asked_to_terminate_); // For now we don't use global scope name for service workers. @@ -347,17 +278,8 @@ const HttpsState starter_https_state = CalculateHttpsState(starter_origin.get()); - scoped_refptr<WebWorkerFetchContext> web_worker_fetch_context; - if (base::FeatureList::IsEnabled( - features::kOffMainThreadServiceWorkerScriptFetch)) { - web_worker_fetch_context = - worker_context_client_->CreateWorkerFetchContextOnMainThread(); - } else { - // |web_worker_fetch_context| is null in some unit tests. - web_worker_fetch_context = - worker_context_client_->CreateWorkerFetchContextOnMainThreadLegacy( - shadow_page_->DocumentLoader()->GetServiceWorkerNetworkProvider()); - } + scoped_refptr<WebWorkerFetchContext> web_worker_fetch_context = + worker_context_client_->CreateWorkerFetchContextOnMainThread(); // Create WorkerSettings. Currently we block all mixed-content requests from // a ServiceWorker. @@ -379,16 +301,6 @@ installed_scripts_manager_->IsScriptInstalled( worker_start_data_.script_url); - // Loading the script from InstalledScriptsManager is considered as - // off-the-main-thread script fetch. - const OffMainThreadWorkerScriptFetchOption off_main_thread_fetch_option = - (base::FeatureList::IsEnabled( - features::kOffMainThreadServiceWorkerScriptFetch) || - is_script_installed || - worker_start_data_.script_type == mojom::ScriptType::kModule) - ? OffMainThreadWorkerScriptFetchOption::kEnabled - : OffMainThreadWorkerScriptFetchOption::kDisabled; - // |main_script_loader_| isn't created if the InstalledScriptsManager had the // script. if (main_script_loader_) { @@ -403,7 +315,7 @@ } global_scope_creation_params = std::make_unique<GlobalScopeCreationParams>( worker_start_data_.script_url, worker_start_data_.script_type, - off_main_thread_fetch_option, global_scope_name, + OffMainThreadWorkerScriptFetchOption::kEnabled, global_scope_name, worker_start_data_.user_agent, std::move(web_worker_fetch_context), content_security_policy ? content_security_policy->Headers() : Vector<CSPHeaderAndType>(), @@ -427,7 +339,7 @@ // served by the installed scripts manager on the worker thread. global_scope_creation_params = std::make_unique<GlobalScopeCreationParams>( worker_start_data_.script_url, worker_start_data_.script_type, - off_main_thread_fetch_option, global_scope_name, + OffMainThreadWorkerScriptFetchOption::kEnabled, global_scope_name, worker_start_data_.user_agent, std::move(web_worker_fetch_context), Vector<CSPHeaderAndType>(), network::mojom::ReferrerPolicy::kDefault, starter_origin.get(), starter_secure_context, starter_https_state, @@ -480,17 +392,6 @@ network::mojom::CredentialsMode::kOmit); break; } - // The legacy on-the-main-thread worker script loading: - // TODO(bashi): Remove this path after off-the-main-thread script fetch is - // enabled (https://crbug,com/924043). - } else if (off_main_thread_fetch_option == - OffMainThreadWorkerScriptFetchOption::kDisabled) { - DCHECK_EQ(worker_start_data_.script_type, mojom::ScriptType::kClassic); - // The worker script was already fetched on the main thread, so just ask - // to evaluate it on the worker thread. - worker_thread_->EvaluateClassicScript( - worker_start_data_.script_url, source_code, std::move(cached_meta_data), - v8_inspector::V8StackTraceId()); } else { std::unique_ptr<CrossThreadFetchClientSettingsObjectData> fetch_client_setting_object_data = CreateFetchClientSettingsObjectData(
diff --git a/third_party/blink/renderer/modules/exported/web_embedded_worker_impl.h b/third_party/blink/renderer/modules/exported/web_embedded_worker_impl.h index ace7262..ebbfaae4 100644 --- a/third_party/blink/renderer/modules/exported/web_embedded_worker_impl.h +++ b/third_party/blink/renderer/modules/exported/web_embedded_worker_impl.h
@@ -111,6 +111,7 @@ std::unique_ptr<ServiceWorkerContentSettingsProxy> content_settings_client_; // Kept around only while main script loading is ongoing. + // TODO(bashi): Remove. This is no longer used. Persistent<WorkerClassicScriptLoader> main_script_loader_; std::unique_ptr<ServiceWorkerThread> worker_thread_; @@ -119,6 +120,7 @@ bool asked_to_terminate_ = false; + // TODO(bashi): Remove. This is no longer used. enum { kDontPauseAfterDownload, kDoPauseAfterDownload,
diff --git a/third_party/blink/renderer/modules/mediarecorder/video_track_recorder.h b/third_party/blink/renderer/modules/mediarecorder/video_track_recorder.h index ab78e71..06eaab8 100644 --- a/third_party/blink/renderer/modules/mediarecorder/video_track_recorder.h +++ b/third_party/blink/renderer/modules/mediarecorder/video_track_recorder.h
@@ -59,13 +59,6 @@ static Type Copy(Type pointer) { return pointer; } }; -template <> -struct CrossThreadCopier<std::string> { - STATIC_ONLY(CrossThreadCopier); - using Type = std::string; - static Type Copy(Type&& value) { return std::move(value); } -}; - } // namespace WTF namespace blink {
diff --git a/third_party/blink/renderer/modules/mediastream/user_media_client_impl_test.cc b/third_party/blink/renderer/modules/mediastream/user_media_client_impl_test.cc index 6f72aef..b7b8d96 100644 --- a/third_party/blink/renderer/modules/mediastream/user_media_client_impl_test.cc +++ b/third_party/blink/renderer/modules/mediastream/user_media_client_impl_test.cc
@@ -354,7 +354,7 @@ blink::mojom::blink::MediaStreamRequestResult error_reason() const { return result_; } - blink::WebString constraint_name() const { return constraint_name_; } + String constraint_name() const { return constraint_name_; } // UserMediaProcessor overrides. std::unique_ptr<blink::MediaStreamVideoSource> CreateVideoSource( @@ -414,7 +414,7 @@ void GetUserMediaRequestFailed( blink::mojom::blink::MediaStreamRequestResult result, - const blink::WebString& constraint_name) override { + const String& constraint_name) override { last_generated_stream_.Reset(); *state_ = REQUEST_FAILED; result_ = result; @@ -436,7 +436,7 @@ blink::WebMediaStream last_generated_stream_; blink::mojom::blink::MediaStreamRequestResult result_ = blink::mojom::blink::MediaStreamRequestResult::NUM_MEDIA_REQUEST_RESULTS; - blink::WebString constraint_name_; + String constraint_name_; RequestState* state_; };
diff --git a/third_party/blink/renderer/modules/mediastream/user_media_processor.cc b/third_party/blink/renderer/modules/mediastream/user_media_processor.cc index 91f3527c..d38d1026 100644 --- a/third_party/blink/renderer/modules/mediastream/user_media_processor.cc +++ b/third_party/blink/renderer/modules/mediastream/user_media_processor.cc
@@ -249,7 +249,7 @@ using ResourcesReady = base::OnceCallback<void(RequestInfo* request_info, MediaStreamRequestResult result, - const blink::WebString& result_name)>; + const String& result_name)>; enum class State { NOT_SENT_FOR_GENERATION, SENT_FOR_GENERATION, @@ -270,7 +270,7 @@ // Called when a local audio source has finished (or failed) initializing. void OnAudioSourceStarted(blink::WebPlatformMediaStreamSource* source, MediaStreamRequestResult result, - const blink::WebString& result_name); + const String& result_name); UserMediaRequestInfo* request() { return request_.get(); } int request_id() const { return request_->request_id; } @@ -365,7 +365,7 @@ StreamControls stream_controls_; ResourcesReady ready_callback_; MediaStreamRequestResult request_result_ = MediaStreamRequestResult::OK; - blink::WebString request_result_name_; + String request_result_name_; // Sources used in this request. Vector<blink::WebMediaStreamSource> sources_; Vector<blink::WebPlatformMediaStreamSource*> sources_waiting_for_callback_; @@ -459,7 +459,7 @@ void UserMediaProcessor::RequestInfo::OnAudioSourceStarted( blink::WebPlatformMediaStreamSource* source, MediaStreamRequestResult result, - const blink::WebString& result_name) { + const String& result_name) { // Check if we're waiting to be notified of this source. If not, then we'll // ignore the notification. if (base::Contains(sources_waiting_for_callback_, source)) @@ -934,7 +934,7 @@ void UserMediaProcessor::NotifyCurrentRequestInfoOfAudioSourceStarted( blink::WebPlatformMediaStreamSource* source, MediaStreamRequestResult result, - const blink::WebString& result_name) { + const String& result_name) { // The only request possibly being processed is |current_request_info_|. if (current_request_info_) current_request_info_->OnAudioSourceStarted(source, result, result_name); @@ -1259,7 +1259,7 @@ const String& label, RequestInfo* request_info, MediaStreamRequestResult result, - const blink::WebString& constraint_name) { + const String& constraint_name) { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); if (result == MediaStreamRequestResult::OK) { GetUserMediaRequestSucceeded(*request_info->web_stream(), @@ -1315,7 +1315,7 @@ void UserMediaProcessor::GetUserMediaRequestFailed( MediaStreamRequestResult result, - const blink::WebString& constraint_name) { + const String& constraint_name) { DCHECK(current_request_info_); blink::WebRtcLogMessage( base::StringPrintf("UMCI::GetUserMediaRequestFailed. request_id=%d", @@ -1480,9 +1480,9 @@ source_extra_data, is_audio_source ? MediaStreamRequestResult::TRACK_START_FAILURE_AUDIO : MediaStreamRequestResult::TRACK_START_FAILURE_VIDEO, - blink::WebString::FromUTF8( - is_audio_source ? "Failed to access audio capture device" - : "Failed to access video capture device")); + String::FromUTF8(is_audio_source + ? "Failed to access audio capture device" + : "Failed to access video capture device")); pending_local_sources_.erase(device_it); return true; }
diff --git a/third_party/blink/renderer/modules/mediastream/user_media_processor.h b/third_party/blink/renderer/modules/mediastream/user_media_processor.h index f801a9d..89a05d6 100644 --- a/third_party/blink/renderer/modules/mediastream/user_media_processor.h +++ b/third_party/blink/renderer/modules/mediastream/user_media_processor.h
@@ -124,7 +124,7 @@ blink::WebUserMediaRequest web_request); virtual void GetUserMediaRequestFailed( blink::mojom::blink::MediaStreamRequestResult result, - const blink::WebString& constraint_name = blink::WebString()); + const String& constraint_name = String()); // Creates a MediaStreamAudioSource/MediaStreamVideoSource objects. // These are virtual for test purposes. @@ -202,7 +202,7 @@ const String& label, RequestInfo* request, blink::mojom::blink::MediaStreamRequestResult result, - const blink::WebString& result_name); + const String& result_name); void OnStreamGeneratedForCancelledRequest( const Vector<blink::MediaStreamDevice>& audio_devices, @@ -223,7 +223,7 @@ void NotifyCurrentRequestInfoOfAudioSourceStarted( blink::WebPlatformMediaStreamSource* source, blink::mojom::blink::MediaStreamRequestResult result, - const blink::WebString& result_name); + const String& result_name); void DeleteAllUserMediaRequests();
diff --git a/third_party/blink/renderer/modules/peerconnection/adapters/web_rtc_cross_thread_copier.h b/third_party/blink/renderer/modules/peerconnection/adapters/web_rtc_cross_thread_copier.h index ad0d976..5e60827 100644 --- a/third_party/blink/renderer/modules/peerconnection/adapters/web_rtc_cross_thread_copier.h +++ b/third_party/blink/renderer/modules/peerconnection/adapters/web_rtc_cross_thread_copier.h
@@ -40,12 +40,6 @@ namespace WTF { template <> -struct CrossThreadCopier<std::string> - : public CrossThreadCopierPassThrough<std::string> { - STATIC_ONLY(CrossThreadCopier); -}; - -template <> struct CrossThreadCopier<cricket::IceParameters> : public CrossThreadCopierPassThrough<cricket::IceParameters> { STATIC_ONLY(CrossThreadCopier);
diff --git a/third_party/blink/renderer/modules/service_worker/service_worker_global_scope.cc b/third_party/blink/renderer/modules/service_worker/service_worker_global_scope.cc index 49741f7..5f7850a1 100644 --- a/third_party/blink/renderer/modules/service_worker/service_worker_global_scope.cc +++ b/third_party/blink/renderer/modules/service_worker/service_worker_global_scope.cc
@@ -256,8 +256,6 @@ const FetchClientSettingsObjectSnapshot& outside_settings_object, WorkerResourceTimingNotifier& outside_resource_timing_notifier, const v8_inspector::V8StackTraceId& stack_id) { - DCHECK(base::FeatureList::IsEnabled( - features::kOffMainThreadServiceWorkerScriptFetch)); DCHECK(!IsContextPaused()); // Step 9. "Switching on job's worker type, run these substeps with the @@ -450,8 +448,6 @@ void ServiceWorkerGlobalScope::DidReceiveResponseForClassicScript( WorkerClassicScriptLoader* classic_script_loader) { DCHECK(IsContextThread()); - DCHECK(base::FeatureList::IsEnabled( - features::kOffMainThreadServiceWorkerScriptFetch)); probe::DidReceiveScriptResponse(this, classic_script_loader->Identifier()); } @@ -460,8 +456,6 @@ WorkerClassicScriptLoader* classic_script_loader, const v8_inspector::V8StackTraceId& stack_id) { DCHECK(IsContextThread()); - DCHECK(base::FeatureList::IsEnabled( - features::kOffMainThreadServiceWorkerScriptFetch)); // Step 9. "If the algorithm asynchronously completes with null, then:" if (classic_script_loader->Failed()) {
diff --git a/third_party/blink/renderer/modules/service_worker/web_embedded_worker_impl_test.cc b/third_party/blink/renderer/modules/service_worker/web_embedded_worker_impl_test.cc index 796c222..ba0e79b9 100644 --- a/third_party/blink/renderer/modules/service_worker/web_embedded_worker_impl_test.cc +++ b/third_party/blink/renderer/modules/service_worker/web_embedded_worker_impl_test.cc
@@ -202,17 +202,6 @@ script_evaluated_event_.Signal(); } - std::unique_ptr<WebServiceWorkerNetworkProvider> - CreateServiceWorkerNetworkProviderOnMainThread() override { - return std::make_unique<FakeServiceWorkerNetworkProvider>(); - } - - scoped_refptr<WebWorkerFetchContext> - CreateWorkerFetchContextOnMainThreadLegacy( - WebServiceWorkerNetworkProvider* network_provider) override { - return base::MakeRefCounted<FakeWebWorkerFetchContext>(); - } - scoped_refptr<WebWorkerFetchContext> CreateWorkerFetchContextOnMainThread() override { return base::MakeRefCounted<FakeWebWorkerFetchContext>();
diff --git a/third_party/blink/renderer/modules/shapedetection/shape_detector.cc b/third_party/blink/renderer/modules/shapedetection/shape_detector.cc index 37ff5273..d40750fcf 100644 --- a/third_party/blink/renderer/modules/shapedetection/shape_detector.cc +++ b/third_party/blink/renderer/modules/shapedetection/shape_detector.cc
@@ -112,7 +112,7 @@ return promise; } - if (image_data->BufferBase()->IsNeutered()) { + if (image_data->BufferBase()->IsDetached()) { resolver->Reject(MakeGarbageCollected<DOMException>( DOMExceptionCode::kInvalidStateError, "The image data has been detached."));
diff --git a/third_party/blink/renderer/modules/webaudio/audio_buffer.cc b/third_party/blink/renderer/modules/webaudio/audio_buffer.cc index 9bd9585..c2934d9 100644 --- a/third_party/blink/renderer/modules/webaudio/audio_buffer.cc +++ b/third_party/blink/renderer/modules/webaudio/audio_buffer.cc
@@ -180,7 +180,7 @@ if (!channel_data_array) return; - channel_data_array->SetNeuterable(false); + channel_data_array->SetDetachable(false); channels_.push_back(channel_data_array); } } @@ -198,7 +198,7 @@ if (!channel_data_array) return; - channel_data_array->SetNeuterable(false); + channel_data_array->SetDetachable(false); const float* src = bus->Channel(i)->Data(); float* dst = channel_data_array->Data(); memmove(dst, src, length_ * sizeof(*dst));
diff --git a/third_party/blink/renderer/modules/webaudio/base_audio_context.cc b/third_party/blink/renderer/modules/webaudio/base_audio_context.cc index a332555..34adef5 100644 --- a/third_party/blink/renderer/modules/webaudio/base_audio_context.cc +++ b/third_party/blink/renderer/modules/webaudio/base_audio_context.cc
@@ -323,7 +323,7 @@ WTF::ArrayBufferContents buffer_contents; // Detach the audio array buffer from the main thread and start // async decoding of the data. - if (audio_data->IsNeuterable(isolate) && + if (audio_data->IsDetachable(isolate) && audio_data->Transfer(isolate, buffer_contents)) { DOMArrayBuffer* audio = DOMArrayBuffer::Create(buffer_contents);
diff --git a/third_party/blink/renderer/modules/webgl/webgl_rendering_context_base.cc b/third_party/blink/renderer/modules/webgl/webgl_rendering_context_base.cc index 11e1bbb..35572cb 100644 --- a/third_party/blink/renderer/modules/webgl/webgl_rendering_context_base.cc +++ b/third_party/blink/renderer/modules/webgl/webgl_rendering_context_base.cc
@@ -5040,9 +5040,9 @@ if (isContextLost()) return; DCHECK(pixels); - if (pixels->data()->BufferBase()->IsNeutered()) { + if (pixels->data()->BufferBase()->IsDetached()) { SynthesizeGLError(GL_INVALID_VALUE, func_name, - "The source data has been neutered."); + "The source data has been detached."); return; } if (!ValidateTexImageBinding(func_name, function_id, target))
diff --git a/third_party/blink/renderer/modules/webgpu/gpu_buffer.cc b/third_party/blink/renderer/modules/webgpu/gpu_buffer.cc index 6dc2805..79a4656 100644 --- a/third_party/blink/renderer/modules/webgpu/gpu_buffer.cc +++ b/third_party/blink/renderer/modules/webgpu/gpu_buffer.cc
@@ -256,7 +256,7 @@ } v8::Isolate* isolate = script_state->GetIsolate(); DOMArrayBuffer* mapped_buffer = mapped_buffer_.Release(); - DCHECK(mapped_buffer->IsNeuterable(isolate)); + DCHECK(mapped_buffer->IsDetachable(isolate)); // Detach the array buffer by transferring the contents out and dropping them. WTF::ArrayBufferContents contents;
diff --git a/third_party/blink/renderer/modules/webusb/usb_device.cc b/third_party/blink/renderer/modules/webusb/usb_device.cc index 0f5a4fc..55e830d 100644 --- a/third_party/blink/renderer/modules/webusb/usb_device.cc +++ b/third_party/blink/renderer/modules/webusb/usb_device.cc
@@ -100,7 +100,7 @@ DCHECK(!buffer_source.IsNull()); if (buffer_source.IsArrayBuffer()) { ArrayBuffer* array_buffer = buffer_source.GetAsArrayBuffer()->Buffer(); - if (array_buffer->IsNeutered()) { + if (array_buffer->IsDetached()) { resolver->Reject(MakeGarbageCollected<DOMException>( DOMExceptionCode::kInvalidStateError, kDetachedBuffer)); return false; @@ -110,7 +110,7 @@ array_buffer->ByteLength()); } else { ArrayBufferView* view = buffer_source.GetAsArrayBufferView().View()->View(); - if (!view->Buffer() || view->Buffer()->IsNeutered()) { + if (!view->Buffer() || view->Buffer()->IsDetached()) { resolver->Reject(MakeGarbageCollected<DOMException>( DOMExceptionCode::kInvalidStateError, kDetachedBuffer)); return false;
diff --git a/third_party/blink/renderer/platform/data_resource_helper.cc b/third_party/blink/renderer/platform/data_resource_helper.cc index 0820c891..0ca2276 100644 --- a/third_party/blink/renderer/platform/data_resource_helper.cc +++ b/third_party/blink/renderer/platform/data_resource_helper.cc
@@ -35,6 +35,13 @@ return String::FromUTF8(uncompressed); } +String UncompressResourceAsASCIIString(int resource_id) { + ui::ResourceBundle& bundle = ui::ResourceBundle::GetSharedInstance(); + std::string uncompressed = bundle.DecompressDataResourceScaled( + resource_id, bundle.GetMaxScaleFactor()); + return String(uncompressed.c_str(), uncompressed.size()); +} + Vector<char> UncompressResourceAsBinary(int resource_id) { ui::ResourceBundle& bundle = ui::ResourceBundle::GetSharedInstance(); std::string uncompressed = bundle.DecompressDataResourceScaled(
diff --git a/third_party/blink/renderer/platform/data_resource_helper.h b/third_party/blink/renderer/platform/data_resource_helper.h index f6d84a8a..a7ba438 100644 --- a/third_party/blink/renderer/platform/data_resource_helper.h +++ b/third_party/blink/renderer/platform/data_resource_helper.h
@@ -21,6 +21,10 @@ // is specified by the resource id from Grit. PLATFORM_EXPORT String UncompressResourceAsString(int resource_id); +// Uncompresses a gzipped resource and returns it as an ascii string. The +// resource is specified by the resource id from Grit. +PLATFORM_EXPORT String UncompressResourceAsASCIIString(int resource_id); + // Uncompresses a gzipped resource and returns it as a vector of characters. // The resource is specified by the resource id from Grit. PLATFORM_EXPORT Vector<char> UncompressResourceAsBinary(int resource_id);
diff --git a/third_party/blink/renderer/platform/graphics/deferred_image_decoder_test_wo_platform.cc b/third_party/blink/renderer/platform/graphics/deferred_image_decoder_test_wo_platform.cc index 4d8522a..2283a63 100644 --- a/third_party/blink/renderer/platform/graphics/deferred_image_decoder_test_wo_platform.cc +++ b/third_party/blink/renderer/platform/graphics/deferred_image_decoder_test_wo_platform.cc
@@ -9,6 +9,7 @@ #include "testing/gtest/include/gtest/gtest.h" #include "third_party/blink/renderer/platform/image-decoders/image_decoder_test_helpers.h" #include "third_party/blink/renderer/platform/wtf/shared_buffer.h" +#include "third_party/blink/renderer/platform/wtf/vector.h" #include "third_party/skia/include/core/SkCanvas.h" #include "third_party/skia/include/core/SkImage.h" #include "third_party/skia/include/core/SkSurface.h" @@ -105,9 +106,9 @@ scoped_refptr<SharedBuffer> file_buffer = ReadFile(test_files[i]); ASSERT_NE(file_buffer, nullptr); // We need contiguous data, which SharedBuffer doesn't guarantee. - sk_sp<SkData> sk_data = file_buffer->GetAsSkData(); - EXPECT_EQ(sk_data->size(), file_buffer->size()); - const char* data = reinterpret_cast<const char*>(sk_data->bytes()); + Vector<char> contiguous = file_buffer->CopyAs<Vector<char>>(); + EXPECT_EQ(contiguous.size(), file_buffer->size()); + const char* data = contiguous.data(); // Truncated signature (only 1 byte). Decoder instantiation should fail. scoped_refptr<SharedBuffer> buffer = SharedBuffer::Create<size_t>(data, 1u); @@ -118,7 +119,7 @@ // Append the rest of the data. We should be able to sniff the signature // now, even if segmented. - buffer->Append<size_t>(data + 1, sk_data->size() - 1); + buffer->Append<size_t>(data + 1, contiguous.size() - 1); EXPECT_TRUE(ImageDecoder::HasSufficientDataToSniffImageType(*buffer)); std::unique_ptr<DeferredImageDecoder> decoder = DeferredImageDecoder::Create(buffer, false,
diff --git a/third_party/blink/renderer/platform/heap/heap.h b/third_party/blink/renderer/platform/heap/heap.h index 595456c7..58b2b928 100644 --- a/third_party/blink/renderer/platform/heap/heap.h +++ b/third_party/blink/renderer/platform/heap/heap.h
@@ -182,11 +182,6 @@ explicit ThreadHeap(ThreadState*); ~ThreadHeap(); - // Returns true for main thread's heap. - // TODO(keishi): Per-thread-heap will return false. - bool IsMainThreadHeap() { return this == ThreadHeap::MainThreadHeap(); } - static ThreadHeap* MainThreadHeap() { return main_thread_heap_; } - template <typename T> static inline bool IsHeapObjectAlive(const T* object) { static_assert(sizeof(T), "T must be fully defined");
diff --git a/third_party/blink/renderer/platform/heap/heap_allocator.h b/third_party/blink/renderer/platform/heap/heap_allocator.h index a1ac976..fce7b03 100644 --- a/third_party/blink/renderer/platform/heap/heap_allocator.h +++ b/third_party/blink/renderer/platform/heap/heap_allocator.h
@@ -473,6 +473,8 @@ DISALLOW_NEW(); static void CheckType() { + static_assert(std::is_trivially_destructible<HeapHashMap>::value, + "HeapHashMap must be trivially destructible."); static_assert( IsAllowedInContainer<KeyArg>::value, "Not allowed to directly nest type. Use Member<> indirection instead."); @@ -482,7 +484,7 @@ static_assert( WTF::IsTraceable<KeyArg>::value || WTF::IsTraceable<MappedArg>::value, "For hash maps without traceable elements, use HashMap<> " - "instead of HeapHashMap<>"); + "instead of HeapHashMap<>."); } public: @@ -504,12 +506,14 @@ DISALLOW_NEW(); static void CheckType() { + static_assert(std::is_trivially_destructible<HeapHashSet>::value, + "HeapHashSet must be trivially destructible."); static_assert( IsAllowedInContainer<ValueArg>::value, "Not allowed to directly nest type. Use Member<> indirection instead."); static_assert(WTF::IsTraceable<ValueArg>::value, "For hash sets without traceable elements, use HashSet<> " - "instead of HeapHashSet<>"); + "instead of HeapHashSet<>."); } public: @@ -538,7 +542,7 @@ "Not allowed to directly nest type. Use Member<> indirection instead."); static_assert(WTF::IsTraceable<ValueArg>::value, "For sets without traceable elements, use LinkedHashSet<> " - "instead of HeapLinkedHashSet<>"); + "instead of HeapLinkedHashSet<>."); } public: @@ -564,12 +568,14 @@ DISALLOW_NEW(); static void CheckType() { + static_assert(std::is_trivially_destructible<HeapListHashSet>::value, + "HeapListHashSet must be trivially destructible."); static_assert( IsAllowedInContainer<ValueArg>::value, "Not allowed to directly nest type. Use Member<> indirection instead."); static_assert(WTF::IsTraceable<ValueArg>::value, "For sets without traceable elements, use ListHashSet<> " - "instead of HeapListHashSet<>"); + "instead of HeapListHashSet<>."); } public: @@ -590,12 +596,14 @@ DISALLOW_NEW(); static void CheckType() { + static_assert(std::is_trivially_destructible<HeapHashCountedSet>::value, + "HeapHashCountedSet must be trivially destructible."); static_assert( IsAllowedInContainer<Value>::value, "Not allowed to directly nest type. Use Member<> indirection instead."); static_assert(WTF::IsTraceable<Value>::value, "For counted sets without traceable elements, use " - "HashCountedSet<> instead of HeapHashCountedSet<>"); + "HashCountedSet<> instead of HeapHashCountedSet<>."); } public: @@ -614,11 +622,14 @@ static void CheckType() { static_assert( + std::is_trivially_destructible<HeapVector>::value || inlineCapacity, + "HeapVector must be trivially destructible."); + static_assert( IsAllowedInContainer<T>::value, "Not allowed to directly nest type. Use Member<> indirection instead."); static_assert(WTF::IsTraceable<T>::value, "For vectors without traceable elements, use Vector<> " - "instead of HeapVector<>"); + "instead of HeapVector<>."); } public: @@ -662,6 +673,9 @@ static void CheckType() { static_assert( + std::is_trivially_destructible<HeapDeque>::value || inlineCapacity, + "HeapDeque must be trivially destructible."); + static_assert( IsAllowedInContainer<T>::value, "Not allowed to directly nest type. Use Member<> indirection instead."); static_assert(WTF::IsTraceable<T>::value,
diff --git a/third_party/blink/renderer/platform/heap/heap_test.cc b/third_party/blink/renderer/platform/heap/heap_test.cc index 67cca87..2be04be 100644 --- a/third_party/blink/renderer/platform/heap/heap_test.cc +++ b/third_party/blink/renderer/platform/heap/heap_test.cc
@@ -6013,86 +6013,6 @@ EXPECT_TRUE(string.Impl()->HasOneRef()); } -TEST_F(HeapTest, PromptlyFreeStackAllocatedHeapVector) { - NormalPageArena* normal_arena; - Address before; - { - HeapVector<Member<IntWrapper>> vector; - vector.push_back(MakeGarbageCollected<IntWrapper>(0)); - NormalPage* normal_page = - static_cast<NormalPage*>(PageFromObject(vector.data())); - normal_arena = normal_page->ArenaForNormalPage(); - CHECK(normal_arena); - before = normal_arena->CurrentAllocationPoint(); - } - Address after = normal_arena->CurrentAllocationPoint(); - // We check the allocation point to see if promptly freed - EXPECT_NE(after, before); -} - -TEST_F(HeapTest, PromptlyFreeStackAllocatedHeapDeque) { - NormalPageArena* normal_arena; - Address before; - { - HeapDeque<Member<IntWrapper>> deque; - deque.push_back(MakeGarbageCollected<IntWrapper>(0)); - NormalPage* normal_page = - static_cast<NormalPage*>(PageFromObject(&deque.front())); - normal_arena = normal_page->ArenaForNormalPage(); - CHECK(normal_arena); - before = normal_arena->CurrentAllocationPoint(); - } - Address after = normal_arena->CurrentAllocationPoint(); - // We check the allocation point to see if promptly freed - EXPECT_NE(after, before); -} - -TEST_F(HeapTest, PromptlyFreeStackAllocatedHeapHashSet) { - NormalPageArena* normal_arena = static_cast<NormalPageArena*>( - ThreadState::Current()->Heap().Arena(BlinkGC::kHashTableArenaIndex)); - CHECK(normal_arena); - Address before; - { - HeapHashSet<Member<IntWrapper>> hash_set; - hash_set.insert(MakeGarbageCollected<IntWrapper>(0)); - before = normal_arena->CurrentAllocationPoint(); - } - Address after = normal_arena->CurrentAllocationPoint(); - // We check the allocation point to see if promptly freed - EXPECT_NE(after, before); -} - -TEST_F(HeapTest, PromptlyFreeStackAllocatedHeapListHashSet) { - ClearOutOldGarbage(); - NormalPageArena* normal_arena = static_cast<NormalPageArena*>( - ThreadState::Current()->Heap().Arena(BlinkGC::kHashTableArenaIndex)); - CHECK(normal_arena); - Address before; - { - HeapListHashSet<Member<IntWrapper>> list_hash_set; - list_hash_set.insert(MakeGarbageCollected<IntWrapper>(0)); - before = normal_arena->CurrentAllocationPoint(); - } - Address after = normal_arena->CurrentAllocationPoint(); - // We check the allocation point to see if promptly freed - EXPECT_NE(after, before); -} - -TEST_F(HeapTest, PromptlyFreeStackAllocatedHeapLinkedHashSet) { - NormalPageArena* normal_arena = static_cast<NormalPageArena*>( - ThreadState::Current()->Heap().Arena(BlinkGC::kHashTableArenaIndex)); - CHECK(normal_arena); - Address before; - { - HeapLinkedHashSet<Member<IntWrapper>> linked_hash_set; - linked_hash_set.insert(MakeGarbageCollected<IntWrapper>(0)); - before = normal_arena->CurrentAllocationPoint(); - } - Address after = normal_arena->CurrentAllocationPoint(); - // We check the allocation point to see if promptly freed - EXPECT_NE(after, before); -} - TEST_F(HeapTest, ShrinkVector) { // Regression test: https://crbug.com/823289
diff --git a/third_party/blink/renderer/platform/heap/thread_state.h b/third_party/blink/renderer/platform/heap/thread_state.h index fce4eff..f1a6670 100644 --- a/third_party/blink/renderer/platform/heap/thread_state.h +++ b/third_party/blink/renderer/platform/heap/thread_state.h
@@ -54,7 +54,7 @@ namespace v8 { class EmbedderGraph; class Isolate; -} +} // namespace v8 namespace blink { @@ -68,57 +68,43 @@ class PersistentRegion; class ThreadHeap; class ThreadState; +template <ThreadAffinity affinity> +class ThreadStateFor; class UnifiedHeapController; class Visitor; -template <ThreadAffinity affinity> -class ThreadStateFor; - -// Declare that a class has a pre-finalizer. The pre-finalizer is called -// before any object gets swept, so it is safe to touch on-heap objects -// that may be collected in the same GC cycle. If you cannot avoid touching -// on-heap objects in a destructor (which is not allowed), you can consider -// using the pre-finalizer. The only restriction is that the pre-finalizer -// must not resurrect dead objects (e.g., store unmarked objects into -// Members etc). The pre-finalizer is called on the thread that registered -// the pre-finalizer. +// Declare that a class has a pre-finalizer which gets invoked before objects +// get swept. It is thus safe to touch on-heap objects that may be collected in +// the same GC cycle. This is useful when it's not possible to avoid touching +// on-heap objects in a destructor which is forbidden. // -// Since a pre-finalizer adds pressure on GC performance, you should use it -// only if necessary. -// -// A pre-finalizer is similar to the -// HeapHashMap<WeakMember<Foo>, std::unique_ptr<Disposer>> idiom. The -// difference between this and the idiom is that pre-finalizer function is -// called whenever an object is destructed with this feature. The -// HeapHashMap<WeakMember<Foo>, std::unique_ptr<Disposer>> idiom requires an -// assumption that the HeapHashMap outlives objects pointed by WeakMembers. -// FIXME: Replace all of the -// HeapHashMap<WeakMember<Foo>, std::unique_ptr<Disposer>> idiom usages with the -// pre-finalizer if the replacement won't cause performance regressions. +// Note that: +// (a) Pre-finalizers *must* not resurrect dead objects. +// (b) Run on the same thread they are registered. +// (c) Decrease GC performance which means that they should only be used if +// absolute necessary. // // Usage: -// -// class Foo : GarbageCollected<Foo> { -// USING_PRE_FINALIZER(Foo, dispose); -// private: -// void dispose() -// { -// bar_->...; // It is safe to touch other on-heap objects. +// class Foo : GarbageCollected<Foo> { +// USING_PRE_FINALIZER(Foo, Dispose); +// private: +// void Dispose() { +// bar_->...; // It is safe to touch other on-heap objects. // } // Member<Bar> bar_; -// }; -#define USING_PRE_FINALIZER(Class, preFinalizer) \ - public: \ - static bool InvokePreFinalizer(void* object) { \ - Class* self = reinterpret_cast<Class*>(object); \ - if (ThreadHeap::IsHeapObjectAlive(self)) \ - return false; \ - self->Class::preFinalizer(); \ - return true; \ - } \ - \ - private: \ - ThreadState::PrefinalizerRegistration<Class> prefinalizer_dummy_ = this; \ +// }; +#define USING_PRE_FINALIZER(Class, preFinalizer) \ + public: \ + static bool InvokePreFinalizer(void* object) { \ + Class* self = reinterpret_cast<Class*>(object); \ + if (ThreadHeap::IsHeapObjectAlive(self)) \ + return false; \ + self->Class::preFinalizer(); \ + return true; \ + } \ + \ + private: \ + ThreadState::PrefinalizerRegistration<Class> prefinalizer_dummy_{this}; \ using UsingPreFinalizerMacroNeedsTrailingSemiColon = char class PLATFORM_EXPORT BlinkGCObserver { @@ -153,6 +139,30 @@ USING_FAST_MALLOC(ThreadState); public: + // Register the pre-finalizer for the |self| object. The class T be using + // USING_PRE_FINALIZER() macro. + template <typename T> + class PrefinalizerRegistration final { + DISALLOW_NEW(); + + public: + PrefinalizerRegistration(T* self) { + static_assert(sizeof(&T::InvokePreFinalizer) > 0, + "USING_PRE_FINALIZER(T) must be defined."); + ThreadState* state = + ThreadStateFor<ThreadingTrait<T>::kAffinity>::GetState(); +#if DCHECK_IS_ON() + DCHECK(state->CheckThread()); +#endif + DCHECK(!state->SweepForbidden()); + DCHECK(std::find(state->ordered_pre_finalizers_.begin(), + state->ordered_pre_finalizers_.end(), + PreFinalizer(self, T::InvokePreFinalizer)) == + state->ordered_pre_finalizers_.end()); + state->ordered_pre_finalizers_.emplace_back(self, T::InvokePreFinalizer); + } + }; + // See setGCState() for possible state transitions. enum GCState { kNoGCScheduled, @@ -209,6 +219,14 @@ // Disassociate attached ThreadState from the current thread. The thread // can no longer use the garbage collected heap after this call. + // + // When ThreadState is detaching from non-main thread its heap is expected to + // be empty (because it is going away). Perform registered cleanup tasks and + // garbage collection to sweep away any objects that are left on this heap. + // + // This method asserts that no objects remain after this cleanup. If assertion + // does not hold we crash as we are potentially in the dangling pointer + // situation. static void DetachCurrentThread(); static ThreadState* Current() { return **thread_specific_; } @@ -236,26 +254,15 @@ void DetachFromIsolate(); // Returns an |UnifiedHeapController| if ThreadState is attached to a V8 - // isolate (see |AttachToIsolate|), nullptr otherwise. + // isolate (see |AttachToIsolate|) and nullptr otherwise. UnifiedHeapController* unified_heap_controller() const { DCHECK(isolate_); return unified_heap_controller_.get(); } - // When ThreadState is detaching from non-main thread its - // heap is expected to be empty (because it is going away). - // Perform registered cleanup tasks and garbage collection - // to sweep away any objects that are left on this heap. - // We assert that nothing must remain after this cleanup. - // If assertion does not hold we crash as we are potentially - // in the dangling pointer situation. - void RunTerminationGC(); - void PerformIdleLazySweep(base::TimeTicks deadline); void PerformConcurrentSweep(); - void ScheduleIdleLazySweep(); - void ScheduleConcurrentAndLazySweep(); void SchedulePreciseGC(); void ScheduleIncrementalGC(BlinkGC::GCReason); void ScheduleV8FollowupGCIfNeeded(BlinkGC::V8GCType); @@ -266,8 +273,11 @@ void SetGCState(GCState); GCState GetGCState() const { return gc_state_; } void SetGCPhase(GCPhase); + + // Returns true if marking is in progress. bool IsMarkingInProgress() const { return gc_phase_ == GCPhase::kMarking; } - bool IsSweepingInProgress() const { return gc_phase_ == GCPhase::kSweeping; } + + // Returns true if unified heap marking is in progress. bool IsUnifiedGCMarkingInProgress() const { return IsMarkingInProgress() && (current_gc_data_.reason == BlinkGC::GCReason::kUnifiedHeapGC || @@ -275,11 +285,16 @@ BlinkGC::GCReason::kUnifiedHeapForMemoryReductionGC); } - void EnableCompactionForNextGCForTesting(); + // Returns true if sweeping is in progress. + bool IsSweepingInProgress() const { return gc_phase_ == GCPhase::kSweeping; } - // Incremental GC. - void ScheduleIncrementalMarkingStep(); - void ScheduleIncrementalMarkingFinalize(); + // Returns true if the current GC is a memory reducing GC. + bool IsMemoryReducingGC() const { + return current_gc_data_.reason == + BlinkGC::GCReason::kUnifiedHeapForMemoryReductionGC; + } + + void EnableCompactionForNextGCForTesting(); void IncrementalMarkingStart(BlinkGC::GCReason); void IncrementalMarkingStep(BlinkGC::StackState); @@ -368,30 +383,6 @@ BlinkGC::StackState stack_state = BlinkGC::StackState::kNoHeapPointersOnStack); - // Register the pre-finalizer for the |self| object. The class T must have - // USING_PRE_FINALIZER(). - template <typename T> - class PrefinalizerRegistration final { - DISALLOW_NEW(); - - public: - PrefinalizerRegistration(T* self) { - static_assert(sizeof(&T::InvokePreFinalizer) > 0, - "USING_PRE_FINALIZER(T) must be defined."); - ThreadState* state = - ThreadStateFor<ThreadingTrait<T>::kAffinity>::GetState(); -#if DCHECK_IS_ON() - DCHECK(state->CheckThread()); -#endif - DCHECK(!state->SweepForbidden()); - DCHECK(std::find(state->ordered_pre_finalizers_.begin(), - state->ordered_pre_finalizers_.end(), - PreFinalizer(self, T::InvokePreFinalizer)) == - state->ordered_pre_finalizers_.end()); - state->ordered_pre_finalizers_.emplace_back(self, T::InvokePreFinalizer); - } - }; - // Returns |true| if |object| resides on this thread's heap. // It is well-defined to call this method on any heap allocated // reference, provided its associated heap hasn't been detached @@ -410,12 +401,6 @@ bool VerifyMarkingEnabled() const; - // Returns true if the current GC is a memory reducing GC. - bool IsMemoryReducingGC() { - return current_gc_data_.reason == - BlinkGC::GCReason::kUnifiedHeapForMemoryReductionGC; - } - private: // Stores whether some ThreadState is currently in incremental marking. static AtomicEntryFlag incremental_marking_flag_; @@ -517,6 +502,15 @@ // Visit all DOM wrappers allocatd on this thread. void VisitDOMWrappers(Visitor*); + // Schedule helpers. + void ScheduleIncrementalMarkingStep(); + void ScheduleIncrementalMarkingFinalize(); + void ScheduleIdleLazySweep(); + void ScheduleConcurrentAndLazySweep(); + + // See |DetachCurrentThread|. + void RunTerminationGC(); + // ShouldForceConservativeGC // implements the heuristics that are used to determine when to collect // garbage.
diff --git a/third_party/blink/renderer/platform/image-decoders/segment_reader.cc b/third_party/blink/renderer/platform/image-decoders/segment_reader.cc index 1b5131f..5b457f0f 100644 --- a/third_party/blink/renderer/platform/image-decoders/segment_reader.cc +++ b/third_party/blink/renderer/platform/image-decoders/segment_reader.cc
@@ -4,6 +4,7 @@ #include "third_party/blink/renderer/platform/image-decoders/segment_reader.h" +#include "base/containers/span.h" #include "base/macros.h" #include "base/memory/scoped_refptr.h" #include "third_party/blink/renderer/platform/wtf/assertions.h" @@ -49,7 +50,15 @@ } sk_sp<SkData> SharedBufferSegmentReader::GetAsSkData() const { - return shared_buffer_->GetAsSkData(); + sk_sp<SkData> data = SkData::MakeUninitialized(shared_buffer_->size()); + char* buffer = static_cast<char*>(data->writable_data()); + size_t offset = 0; + for (const auto& span : *shared_buffer_) { + memcpy(buffer + offset, span.data(), span.size()); + offset += span.size(); + } + + return data; } // DataSegmentReader -----------------------------------------------------------
diff --git a/third_party/blink/renderer/platform/image-decoders/segment_reader.h b/third_party/blink/renderer/platform/image-decoders/segment_reader.h index f367523..c986ad8 100644 --- a/third_party/blink/renderer/platform/image-decoders/segment_reader.h +++ b/third_party/blink/renderer/platform/image-decoders/segment_reader.h
@@ -13,6 +13,8 @@ class SkData; class SkROBuffer; +template <typename T> +class sk_sp; namespace blink {
diff --git a/third_party/blink/renderer/platform/testing/url_test_helpers.cc b/third_party/blink/renderer/platform/testing/url_test_helpers.cc index 653acd53..ff8c9dd 100644 --- a/third_party/blink/renderer/platform/testing/url_test_helpers.cc +++ b/third_party/blink/renderer/platform/testing/url_test_helpers.cc
@@ -102,19 +102,5 @@ Platform::Current()->GetURLLoaderMockFactory()->UnregisterURL(url); } -void UnregisterAllURLsAndClearMemoryCache() { - Platform::Current() - ->GetURLLoaderMockFactory() - ->UnregisterAllURLsAndClearMemoryCache(); -} - -void SetLoaderDelegate(WebURLLoaderTestDelegate* delegate) { - Platform::Current()->GetURLLoaderMockFactory()->SetLoaderDelegate(delegate); -} - -void ServeAsynchronousRequests() { - Platform::Current()->GetURLLoaderMockFactory()->ServeAsynchronousRequests(); -} - } // namespace url_test_helpers } // namespace blink
diff --git a/third_party/blink/renderer/platform/testing/url_test_helpers.h b/third_party/blink/renderer/platform/testing/url_test_helpers.h index 2edd24f..aaf7c51 100644 --- a/third_party/blink/renderer/platform/testing/url_test_helpers.h +++ b/third_party/blink/renderer/platform/testing/url_test_helpers.h
@@ -33,7 +33,6 @@ #include "third_party/blink/public/platform/web_string.h" #include "third_party/blink/public/platform/web_url.h" -#include "third_party/blink/public/platform/web_url_loader_mock_factory.h" #include "third_party/blink/public/platform/web_url_response.h" #include "third_party/blink/renderer/platform/weborigin/kurl.h" @@ -86,12 +85,6 @@ // Registers a mock URL that returns a 404 error. void RegisterMockedErrorURLLoad(const WebURL& full_url); -void UnregisterAllURLsAndClearMemoryCache(); - -void SetLoaderDelegate(WebURLLoaderTestDelegate* delegate); - -void ServeAsynchronousRequests(); - } // namespace url_test_helpers } // namespace blink
diff --git a/third_party/blink/renderer/platform/wtf/BUILD.gn b/third_party/blink/renderer/platform/wtf/BUILD.gn index eb9e761..fe08bf3 100644 --- a/third_party/blink/renderer/platform/wtf/BUILD.gn +++ b/third_party/blink/renderer/platform/wtf/BUILD.gn
@@ -238,7 +238,6 @@ public_deps = [ "//base", - "//skia", "//third_party/icu", ]
diff --git a/third_party/blink/renderer/platform/wtf/DEPS b/third_party/blink/renderer/platform/wtf/DEPS index 257797f9..7ef4a10 100644 --- a/third_party/blink/renderer/platform/wtf/DEPS +++ b/third_party/blink/renderer/platform/wtf/DEPS
@@ -25,7 +25,6 @@ "+base/threading", "+base/time/time.h", "+base/tuple.h", - "+third_party/skia", # To avoid recursive dependency, we impose a blanket ban on using other # platform files. Think carefully if you want to relax this restriction. "-third_party/blink/renderer/platform",
diff --git a/third_party/blink/renderer/platform/wtf/cross_thread_copier.h b/third_party/blink/renderer/platform/wtf/cross_thread_copier.h index 75ddf96..6a40228 100644 --- a/third_party/blink/renderer/platform/wtf/cross_thread_copier.h +++ b/third_party/blink/renderer/platform/wtf/cross_thread_copier.h
@@ -32,6 +32,7 @@ #define THIRD_PARTY_BLINK_RENDERER_PLATFORM_WTF_CROSS_THREAD_COPIER_H_ #include <memory> +#include <string> #include <vector> #include "base/memory/scoped_refptr.h" #include "base/memory/weak_ptr.h" @@ -175,6 +176,15 @@ static Type Copy(Type value) { return value; } }; +template <class CharT, class Traits, class Allocator> +struct CrossThreadCopier<std::basic_string<CharT, Traits, Allocator>> { + STATIC_ONLY(CrossThreadCopier); + using Type = std::basic_string<CharT, Traits, Allocator>; + static Type Copy(Type string) { + return string; // This is in fact a move. + } +}; + template <typename T, wtf_size_t inlineCapacity, typename Allocator> struct CrossThreadCopier<Vector<T, inlineCapacity, Allocator>> { STATIC_ONLY(CrossThreadCopier);
diff --git a/third_party/blink/renderer/platform/wtf/deque.h b/third_party/blink/renderer/platform/wtf/deque.h index 80c92ec..4a98ffb 100644 --- a/third_party/blink/renderer/platform/wtf/deque.h +++ b/third_party/blink/renderer/platform/wtf/deque.h
@@ -52,7 +52,9 @@ template <typename T, wtf_size_t inlineCapacity = 0, typename Allocator = PartitionAllocator> -class Deque { +class Deque : public ConditionalDestructor<Deque<T, INLINE_CAPACITY, Allocator>, + (INLINE_CAPACITY == 0) && + Allocator::kIsGarbageCollected> { USE_ALLOCATOR(Deque, Allocator); public: @@ -66,9 +68,8 @@ Deque& operator=(const Deque&); Deque(Deque&&); Deque& operator=(Deque&&); - ~Deque(); - void FinalizeGarbageCollectedObject() { NOTREACHED(); } + void Finalize(); void Swap(Deque&); @@ -374,16 +375,18 @@ // For design of the destructor, please refer to // [here](https://docs.google.com/document/d/1AoGTvb3tNLx2tD1hNqAfLRLmyM59GM0O-7rCHTT_7_U/) template <typename T, wtf_size_t inlineCapacity, typename Allocator> -inline Deque<T, inlineCapacity, Allocator>::~Deque() { +inline void Deque<T, inlineCapacity, Allocator>::Finalize() { + static_assert(!Allocator::kIsGarbageCollected || INLINE_CAPACITY, + "GarbageCollected collections without inline capacity cannot " + "be finalized."); if ((!INLINE_CAPACITY && !buffer_.Buffer())) return; if (!IsEmpty() && !(Allocator::kIsGarbageCollected && buffer_.HasOutOfLineBuffer())) DestroyAll(); - // If this is called during sweeping, it must not touch the OutOfLineBuffer. - if (Allocator::IsSweepForbidden()) - return; + // For garbage collected deque HeapAllocator::BackingFree() will bail out + // during sweeping. buffer_.Destruct(); }
diff --git a/third_party/blink/renderer/platform/wtf/hash_table.h b/third_party/blink/renderer/platform/wtf/hash_table.h index eb73aac..4ab6b1e3 100644 --- a/third_party/blink/renderer/platform/wtf/hash_table.h +++ b/third_party/blink/renderer/platform/wtf/hash_table.h
@@ -29,6 +29,7 @@ #include "third_party/blink/renderer/platform/wtf/allocator/allocator.h" #include "third_party/blink/renderer/platform/wtf/allocator/partition_allocator.h" #include "third_party/blink/renderer/platform/wtf/assertions.h" +#include "third_party/blink/renderer/platform/wtf/conditional_destructor.h" #include "third_party/blink/renderer/platform/wtf/construct_traits.h" #include "third_party/blink/renderer/platform/wtf/hash_traits.h" @@ -694,7 +695,15 @@ typename Traits, typename KeyTraits, typename Allocator> -class HashTable final { +class HashTable final + : public ConditionalDestructor<HashTable<Key, + Value, + Extractor, + HashFunctions, + Traits, + KeyTraits, + Allocator>, + Allocator::kIsGarbageCollected> { DISALLOW_NEW(); public: @@ -726,15 +735,11 @@ HashTable(); - // For design of the destructor, please refer to - // [here](https://docs.google.com/document/d/1AoGTvb3tNLx2tD1hNqAfLRLmyM59GM0O-7rCHTT_7_U/) - ~HashTable() { + void Finalize() { + static_assert(!Allocator::kIsGarbageCollected, + "GCed collections can't be finalized."); if (LIKELY(!table_)) return; - // If this is called during sweeping, it must not touch other heap objects - // such as the backing. - if (Allocator::IsSweepForbidden()) - return; EnterAccessForbiddenScope(); DeleteAllBucketsAndDeallocate(table_, table_size_); LeaveAccessForbiddenScope();
diff --git a/third_party/blink/renderer/platform/wtf/list_hash_set.h b/third_party/blink/renderer/platform/wtf/list_hash_set.h index 046d8390..78bd279 100644 --- a/third_party/blink/renderer/platform/wtf/list_hash_set.h +++ b/third_party/blink/renderer/platform/wtf/list_hash_set.h
@@ -25,6 +25,7 @@ #include <memory> #include "third_party/blink/renderer/platform/wtf/allocator/partition_allocator.h" +#include "third_party/blink/renderer/platform/wtf/conditional_destructor.h" #include "third_party/blink/renderer/platform/wtf/hash_set.h" namespace WTF { @@ -76,7 +77,10 @@ typename HashArg = typename DefaultHash<ValueArg>::Hash, typename AllocatorArg = ListHashSetAllocator<ValueArg, inlineCapacity>> -class ListHashSet { +class ListHashSet + : public ConditionalDestructor< + ListHashSet<ValueArg, inlineCapacity, HashArg, AllocatorArg>, + AllocatorArg::kIsGarbageCollected> { typedef AllocatorArg Allocator; USE_ALLOCATOR(ListHashSet, Allocator); @@ -148,7 +152,7 @@ ListHashSet(ListHashSet&&); ListHashSet& operator=(const ListHashSet&); ListHashSet& operator=(ListHashSet&&); - ~ListHashSet(); + void Finalize(); void Swap(ListHashSet&); @@ -804,14 +808,10 @@ allocator_provider_.Swap(other.allocator_provider_); } -// For design of the destructor, please refer to -// [here](https://docs.google.com/document/d/1AoGTvb3tNLx2tD1hNqAfLRLmyM59GM0O-7rCHTT_7_U/) template <typename T, size_t inlineCapacity, typename U, typename V> -inline ListHashSet<T, inlineCapacity, U, V>::~ListHashSet() { - // If this is called during GC sweeping, it must not touch other heap objects - // such as the ListHashSetNodes that is touching in DeleteAllNodes(). - if (Allocator::IsSweepForbidden()) - return; +inline void ListHashSet<T, inlineCapacity, U, V>::Finalize() { + static_assert(!Allocator::kIsGarbageCollected, + "GCed collections can't be finalized"); DeleteAllNodes(); allocator_provider_.ReleaseAllocator(); }
diff --git a/third_party/blink/renderer/platform/wtf/shared_buffer.cc b/third_party/blink/renderer/platform/wtf/shared_buffer.cc index cf5689cf..9d3eb78 100644 --- a/third_party/blink/renderer/platform/wtf/shared_buffer.cc +++ b/third_party/blink/renderer/platform/wtf/shared_buffer.cc
@@ -31,7 +31,6 @@ #include "third_party/blink/renderer/platform/wtf/allocator/allocator.h" #include "third_party/blink/renderer/platform/wtf/text/unicode.h" #include "third_party/blink/renderer/platform/wtf/text/utf8.h" -#include "third_party/skia/include/core/SkData.h" namespace WTF { @@ -209,19 +208,6 @@ return offset == dest_size; } -sk_sp<SkData> SharedBuffer::GetAsSkData() const { - sk_sp<SkData> data = SkData::MakeUninitialized(size()); - char* buffer = static_cast<char*>(data->writable_data()); - size_t offset = 0; - for (const auto& span : *this) { - memcpy(buffer + offset, span.data(), span.size()); - offset += span.size(); - } - - DCHECK_EQ(offset, size()); - return data; -} - void SharedBuffer::GetMemoryDumpNameAndSize(String& dump_name, size_t& dump_size) const { size_t buffer_size = buffer_.size();
diff --git a/third_party/blink/renderer/platform/wtf/shared_buffer.h b/third_party/blink/renderer/platform/wtf/shared_buffer.h index f309d45d..1111c52 100644 --- a/third_party/blink/renderer/platform/wtf/shared_buffer.h +++ b/third_party/blink/renderer/platform/wtf/shared_buffer.h
@@ -39,10 +39,6 @@ #include "third_party/blink/renderer/platform/wtf/vector.h" #include "third_party/blink/renderer/platform/wtf/wtf_export.h" -class SkData; -template <typename T> -class sk_sp; - namespace WTF { class WTF_EXPORT SharedBuffer : public RefCounted<SharedBuffer> { @@ -176,10 +172,6 @@ return GetBytesInternal(dest, byte_length); } - // Creates an SkData and copies this SharedBuffer's contents to that - // SkData without merging segmented buffers into a flat buffer. - sk_sp<SkData> GetAsSkData() const; - void GetMemoryDumpNameAndSize(String& dump_name, size_t& dump_size) const; // Helper for providing a contiguous view of the data. If the SharedBuffer is
diff --git a/third_party/blink/renderer/platform/wtf/typed_arrays/array_buffer.cc b/third_party/blink/renderer/platform/wtf/typed_arrays/array_buffer.cc index 7e58be3..5bc3bdd 100644 --- a/third_party/blink/renderer/platform/wtf/typed_arrays/array_buffer.cc +++ b/third_party/blink/renderer/platform/wtf/typed_arrays/array_buffer.cc
@@ -35,26 +35,26 @@ scoped_refptr<ArrayBuffer> keep_alive(this); if (!contents_.Data()) { - result.Neuter(); + result.Detach(); return false; } - bool all_views_are_neuterable = true; + bool all_views_are_detachable = true; for (ArrayBufferView* i = first_view_; i; i = i->next_view_) { - if (!i->IsNeuterable()) - all_views_are_neuterable = false; + if (!i->IsDetachable()) + all_views_are_detachable = false; } - if (all_views_are_neuterable) { + if (all_views_are_detachable) { contents_.Transfer(result); while (first_view_) { ArrayBufferView* current = first_view_; RemoveView(current); - current->Neuter(); + current->Detach(); } - is_neutered_ = true; + is_detached_ = true; } else { // TODO(https://crbug.com/763038): See original bug at // https://crbug.com/254728. Copying the buffer instead of transferring is @@ -74,7 +74,7 @@ scoped_refptr<ArrayBuffer> keep_alive(this); if (!contents_.DataShared()) { - result.Neuter(); + result.Detach(); return false; } @@ -87,7 +87,7 @@ scoped_refptr<ArrayBuffer> keep_alive(this); if (!contents_.Data()) { - result.Neuter(); + result.Detach(); return false; }
diff --git a/third_party/blink/renderer/platform/wtf/typed_arrays/array_buffer.h b/third_party/blink/renderer/platform/wtf/typed_arrays/array_buffer.h index ce5a04b3..7383259 100644 --- a/third_party/blink/renderer/platform/wtf/typed_arrays/array_buffer.h +++ b/third_party/blink/renderer/platform/wtf/typed_arrays/array_buffer.h
@@ -86,7 +86,7 @@ bool ShareContentsWith(ArrayBufferContents&); // Documentation see DOMArrayBuffer. bool ShareNonSharedForInternalUse(ArrayBufferContents&); - bool IsNeutered() const { return is_neutered_; } + bool IsDetached() const { return is_detached_; } bool IsShared() const { return contents_.IsShared(); } ~ArrayBuffer() = default; @@ -115,7 +115,7 @@ ArrayBufferContents contents_; ArrayBufferView* first_view_; - bool is_neutered_; + bool is_detached_; }; unsigned ArrayBuffer::ClampValue(int x, unsigned left, unsigned right) { @@ -226,7 +226,7 @@ } ArrayBuffer::ArrayBuffer(ArrayBufferContents& contents) - : first_view_(nullptr), is_neutered_(false) { + : first_view_(nullptr), is_detached_(false) { if (contents.IsShared()) contents.ShareWith(contents_); else
diff --git a/third_party/blink/renderer/platform/wtf/typed_arrays/array_buffer_contents.cc b/third_party/blink/renderer/platform/wtf/typed_arrays/array_buffer_contents.cc index 00312421..ac76d12 100644 --- a/third_party/blink/renderer/platform/wtf/typed_arrays/array_buffer_contents.cc +++ b/third_party/blink/renderer/platform/wtf/typed_arrays/array_buffer_contents.cc
@@ -83,7 +83,7 @@ ArrayBufferContents::~ArrayBufferContents() = default; -void ArrayBufferContents::Neuter() { +void ArrayBufferContents::Detach() { holder_ = nullptr; } @@ -91,7 +91,7 @@ DCHECK(!IsShared()); DCHECK(!other.holder_->Data()); other.holder_ = holder_; - Neuter(); + Detach(); } void ArrayBufferContents::ShareWith(ArrayBufferContents& other) {
diff --git a/third_party/blink/renderer/platform/wtf/typed_arrays/array_buffer_contents.h b/third_party/blink/renderer/platform/wtf/typed_arrays/array_buffer_contents.h index 601046e..929468d 100644 --- a/third_party/blink/renderer/platform/wtf/typed_arrays/array_buffer_contents.h +++ b/third_party/blink/renderer/platform/wtf/typed_arrays/array_buffer_contents.h
@@ -115,7 +115,7 @@ ArrayBufferContents& operator=(ArrayBufferContents&&) = default; - void Neuter(); + void Detach(); void* Data() const { DCHECK(!IsShared());
diff --git a/third_party/blink/renderer/platform/wtf/typed_arrays/array_buffer_view.cc b/third_party/blink/renderer/platform/wtf/typed_arrays/array_buffer_view.cc index 56420a2..1daa4ef 100644 --- a/third_party/blink/renderer/platform/wtf/typed_arrays/array_buffer_view.cc +++ b/third_party/blink/renderer/platform/wtf/typed_arrays/array_buffer_view.cc
@@ -32,7 +32,7 @@ ArrayBufferView::ArrayBufferView(scoped_refptr<ArrayBuffer> buffer, unsigned byte_offset) : byte_offset_(byte_offset), - is_neuterable_(true), + is_detachable_(true), buffer_(std::move(buffer)), prev_view_(nullptr), next_view_(nullptr) { @@ -48,7 +48,7 @@ buffer_->RemoveView(this); } -void ArrayBufferView::Neuter() { +void ArrayBufferView::Detach() { buffer_ = nullptr; base_address_ = nullptr; byte_offset_ = 0;
diff --git a/third_party/blink/renderer/platform/wtf/typed_arrays/array_buffer_view.h b/third_party/blink/renderer/platform/wtf/typed_arrays/array_buffer_view.h index aca42a70..bf595280 100644 --- a/third_party/blink/renderer/platform/wtf/typed_arrays/array_buffer_view.h +++ b/third_party/blink/renderer/platform/wtf/typed_arrays/array_buffer_view.h
@@ -69,8 +69,8 @@ virtual unsigned ByteLength() const = 0; virtual unsigned TypeSize() const = 0; - void SetNeuterable(bool flag) { is_neuterable_ = flag; } - bool IsNeuterable() const { return is_neuterable_; } + void SetDetachable(bool flag) { is_detachable_ = flag; } + bool IsDetachable() const { return is_detachable_; } bool IsShared() const { return buffer_ ? buffer_->IsShared() : false; } virtual ~ArrayBufferView(); @@ -99,13 +99,13 @@ return true; } - virtual void Neuter(); + virtual void Detach(); // This is the address of the ArrayBuffer's storage, plus the byte offset. void* base_address_; unsigned byte_offset_ : 31; - unsigned is_neuterable_ : 1; + unsigned is_detachable_ : 1; private: friend class ArrayBuffer;
diff --git a/third_party/blink/renderer/platform/wtf/typed_arrays/array_piece.cc b/third_party/blink/renderer/platform/wtf/typed_arrays/array_piece.cc index a96ffc0..795f578 100644 --- a/third_party/blink/renderer/platform/wtf/typed_arrays/array_piece.cc +++ b/third_party/blink/renderer/platform/wtf/typed_arrays/array_piece.cc
@@ -27,8 +27,8 @@ return is_null_; } -bool ArrayPiece::IsNeutered() const { - return is_neutered_; +bool ArrayPiece::IsDetached() const { + return is_detached_; } void* ArrayPiece::Data() const { @@ -48,7 +48,7 @@ void ArrayPiece::InitWithArrayBuffer(ArrayBuffer* buffer) { if (buffer) { InitWithData(buffer->Data(), SafeCast<unsigned>(buffer->ByteLength())); - is_neutered_ = buffer->IsNeutered(); + is_detached_ = buffer->IsDetached(); } else { InitNull(); } @@ -57,7 +57,7 @@ void ArrayPiece::InitWithArrayBufferView(ArrayBufferView* buffer) { if (buffer) { InitWithData(buffer->BaseAddress(), buffer->ByteLength()); - is_neutered_ = buffer->Buffer() ? buffer->Buffer()->IsNeutered() : true; + is_detached_ = buffer->Buffer() ? buffer->Buffer()->IsDetached() : true; } else { InitNull(); } @@ -67,14 +67,14 @@ byte_length_ = byte_length; data_ = data; is_null_ = false; - is_neutered_ = false; + is_detached_ = false; } void ArrayPiece::InitNull() { byte_length_ = 0; data_ = nullptr; is_null_ = true; - is_neutered_ = false; + is_detached_ = false; } } // namespace WTF
diff --git a/third_party/blink/renderer/platform/wtf/typed_arrays/array_piece.h b/third_party/blink/renderer/platform/wtf/typed_arrays/array_piece.h index d8ffa222..dd77748ea 100644 --- a/third_party/blink/renderer/platform/wtf/typed_arrays/array_piece.h +++ b/third_party/blink/renderer/platform/wtf/typed_arrays/array_piece.h
@@ -33,7 +33,7 @@ ArrayPiece(ArrayBufferView*); bool IsNull() const; - bool IsNeutered() const; + bool IsDetached() const; void* Data() const; unsigned char* Bytes() const; unsigned ByteLength() const; @@ -49,7 +49,7 @@ void* data_; unsigned byte_length_; bool is_null_; - bool is_neutered_; + bool is_detached_; }; } // namespace WTF
diff --git a/third_party/blink/renderer/platform/wtf/typed_arrays/typed_array_base.h b/third_party/blink/renderer/platform/wtf/typed_arrays/typed_array_base.h index 675c998..dd7308df 100644 --- a/third_party/blink/renderer/platform/wtf/typed_arrays/typed_array_base.h +++ b/third_party/blink/renderer/platform/wtf/typed_arrays/typed_array_base.h
@@ -109,8 +109,8 @@ return Create<Subclass>(std::move(buffer), 0, length); } - void Neuter() final { - ArrayBufferView::Neuter(); + void Detach() final { + ArrayBufferView::Detach(); length_ = 0; }
diff --git a/third_party/blink/renderer/platform/wtf/vector.h b/third_party/blink/renderer/platform/wtf/vector.h index 3091e1c0..43a27f7 100644 --- a/third_party/blink/renderer/platform/wtf/vector.h +++ b/third_party/blink/renderer/platform/wtf/vector.h
@@ -31,6 +31,7 @@ #include "base/template_util.h" #include "build/build_config.h" #include "third_party/blink/renderer/platform/wtf/allocator/partition_allocator.h" +#include "third_party/blink/renderer/platform/wtf/conditional_destructor.h" #include "third_party/blink/renderer/platform/wtf/construct_traits.h" #include "third_party/blink/renderer/platform/wtf/container_annotations.h" #include "third_party/blink/renderer/platform/wtf/forward.h" // For default Vector template parameters. @@ -973,7 +974,11 @@ // store iterators in another heap object. template <typename T, wtf_size_t inlineCapacity, typename Allocator> -class Vector : private VectorBuffer<T, INLINE_CAPACITY, Allocator> { +class Vector + : private VectorBuffer<T, INLINE_CAPACITY, Allocator>, + public ConditionalDestructor<Vector<T, INLINE_CAPACITY, Allocator>, + (INLINE_CAPACITY == 0) && + Allocator::kIsGarbageCollected> { USE_ALLOCATOR(Vector, Allocator); using Base = VectorBuffer<T, INLINE_CAPACITY, Allocator>; using TypeOperations = VectorTypeOperations<T, Allocator>; @@ -1257,12 +1262,12 @@ return Allocator::template MaxElementCountInBackingStore<T>(); } - // For design of the destructor, please refer to - // [here](https://docs.google.com/document/d/1AoGTvb3tNLx2tD1hNqAfLRLmyM59GM0O-7rCHTT_7_U/) - ~Vector() { - if (!INLINE_CAPACITY) { - if (LIKELY(!Base::Buffer())) - return; + void Finalize() { + static_assert(!Allocator::kIsGarbageCollected || INLINE_CAPACITY, + "GarbageCollected collections without inline capacity cannot " + "be finalized."); + if (!INLINE_CAPACITY && LIKELY(!Base::Buffer())) { + return; } ANNOTATE_DELETE_BUFFER(begin(), capacity(), size_); if (LIKELY(size_) && @@ -1271,21 +1276,11 @@ size_ = 0; // Partial protection against use-after-free. } - // If this is called during sweeping, the backing should not be touched. - // Other collections have an early return here if IsSweepForbidden(), but - // adding that resulted in performance regression for shadow dom benchmarks - // (crbug.com/866084) because of the additional access to TLS. The check has - // been removed but the same check exists in HeapAllocator::BackingFree() so - // things should be fine as long as VectorBase does not touch the backing. - + // For garbage collected vector HeapAllocator::BackingFree() will bail out + // during sweeping. Base::Destruct(); } - // This method will be referenced when creating an on-heap HeapVector with - // inline capacity and elements requiring destruction. However usage of such a - // type is banned with a static assert. - void FinalizeGarbageCollectedObject() { NOTREACHED(); } - template <typename VisitorDispatcher, typename A = Allocator> std::enable_if_t<A::kIsGarbageCollected> Trace(VisitorDispatcher);
diff --git a/third_party/blink/web_tests/FlagExpectations/disable-blink-features=LayoutNG b/third_party/blink/web_tests/FlagExpectations/disable-blink-features=LayoutNG index e41d572..54fe2a6 100644 --- a/third_party/blink/web_tests/FlagExpectations/disable-blink-features=LayoutNG +++ b/third_party/blink/web_tests/FlagExpectations/disable-blink-features=LayoutNG
@@ -280,9 +280,6 @@ ### virtual/blink-cors/external/wpt/service-workers/service-worker/ crbug.com/591099 virtual/blink-cors/external/wpt/service-workers/service-worker/registration-updateviacache.https.html [ Failure ] -### virtual/not-omt-sw-fetch/external/wpt/service-workers/service-worker/ -crbug.com/591099 virtual/not-omt-sw-fetch/external/wpt/service-workers/service-worker/registration-schedule-job.https.html [ Failure ] - ### virtual/omt-worker-fetch/external/wpt/service-workers/service-worker/ crbug.com/591099 virtual/omt-worker-fetch/external/wpt/service-workers/service-worker/registration-updateviacache.https.html [ Failure ]
diff --git a/third_party/blink/web_tests/FlagExpectations/enable-browser-side-navigation b/third_party/blink/web_tests/FlagExpectations/enable-browser-side-navigation deleted file mode 100644 index c7c0f72..0000000 --- a/third_party/blink/web_tests/FlagExpectations/enable-browser-side-navigation +++ /dev/null
@@ -1,38 +0,0 @@ -# These tests currently fail when run with --enable-browser-side-navigation -# See https://crbug.com/576261 - -# These tests are flaky. -Bug(none) http/tests/security/popup-allowed-by-sandbox-can-navigate.html [ Failure ] - -# Not disclosing |source_location| and/or |blocked url| between cross-origin -# renderers when a CSP policy is violated regresses the quality of console -# error messages. -Bug(718942) http/tests/misc/onload-detach-during-csp-frame-src-none.html [ Failure ] -Bug(718942) http/tests/security/contentSecurityPolicy/1.1/form-action-src-get-blocked-with-redirect.html [ Failure ] -Bug(718942) http/tests/security/contentSecurityPolicy/1.1/form-action-src-redirect-blocked.html [ Failure ] -Bug(718942) http/tests/security/contentSecurityPolicy/frame-src-cross-origin-load.html [ Failure ] - -# Console error message source location is present with PlzNavigate. It means -# that URLs are potentially disclosed across cross-origin renderers. -# See https://crbug.com/726178. -# One solution would be to send console messages from the browser to the -# devtool process without the round-trip in the renderer. -# See https://crbug.com/721329 -Bug(726178) http/tests/security/mixedContent/insecure-frame-in-data-iframe-in-main-frame-blocked.html [ Failure ] -Bug(726178) http/tests/security/mixedContent/insecure-iframe-in-iframe.html [ Failure ] -Bug(726178) http/tests/security/mixedContent/insecure-iframe-in-main-frame-allowed.html [ Failure ] -Bug(726178) http/tests/security/mixedContent/insecure-iframe-in-main-frame-blocked.html [ Failure ] -Bug(726178) http/tests/security/mixedContent/insecure-iframe-in-main-frame.html [ Failure ] -Bug(726178) http/tests/security/mixedContent/nonwebby-scheme-in-iframe-allowed.https.html [ Failure ] -Bug(726178) http/tests/security/mixedContent/redirect-http-to-https-iframe-in-main-frame.html [ Failure ] -Bug(726178) http/tests/security/mixedContent/redirect-https-to-http-iframe-in-main-frame.html [ Failure ] - -# ------------------------------------------------------------ -# These tests are correct with PlzNavigate but not without it -# ------------------------------------------------------------ -# Without PlzNavigate, the line number of the console message is missing when -# there is a redirect. -Bug(none) http/tests/security/contentSecurityPolicy/frame-src-redirect-blocked.html [ Failure ] -# The line number in CSP violation event should be hidden when it comes from a -# cross-origin iframe. -Bug(none) http/tests/security/contentSecurityPolicy/frame-src-child-frame-navigates-to-blocked-origin.html [ Failure ]
diff --git a/third_party/blink/web_tests/FlagExpectations/enable-features=BackForwardCache b/third_party/blink/web_tests/FlagExpectations/enable-features=BackForwardCache new file mode 100644 index 0000000..80b16f0 --- /dev/null +++ b/third_party/blink/web_tests/FlagExpectations/enable-features=BackForwardCache
@@ -0,0 +1,7 @@ +# These tests currently fail when run with --enable-features=BackForwardCache + +# Document are deleted, because they execute javascript in a frozen document. +# This shouldn't happen if the page didn't enter the BackForwardCache. +crbug.com/991194 external/wpt/lifecycle/child-display-none.tentative.html [ Timeout ] +crbug.com/991194 external/wpt/lifecycle/child-out-of-viewport.tentative.html [ Timeout ] +crbug.com/991194 external/wpt/lifecycle/worker-dispay-none.tentative.html [ Failure ]
diff --git a/third_party/blink/web_tests/MSANExpectations b/third_party/blink/web_tests/MSANExpectations index 10189bf7..13ac6f1 100644 --- a/third_party/blink/web_tests/MSANExpectations +++ b/third_party/blink/web_tests/MSANExpectations
@@ -304,13 +304,11 @@ crbug.com/856601 [ Linux ] http/tests/devtools/a11y-axe-core/security/security-origin-a11y-test.js [ Pass Timeout ] crbug.com/856601 [ Linux ] http/tests/devtools/indexeddb/live-update-indexeddb-content.js [ Pass Timeout ] crbug.com/856601 [ Linux ] http/tests/devtools/indexeddb/live-update-indexeddb-list.js [ Pass Timeout ] -crbug.com/856601 [ Linux ] virtual/not-omt-sw-fetch/external/wpt/service-workers/service-worker/interfaces-sw.https.html [ Pass Timeout ] # Sheriff 2019-07-11 crbug.com/856601 [ Linux ] virtual/cache-storage-sequence/external/wpt/service-workers/service-worker/interfaces-sw.https.html [ Pass Timeout ] # Sheriff 2019-07-19 -crbug.com/856601 [ Linux ] virtual/not-omt-sw-fetch/external/wpt/fetch/api/idl.any.serviceworker.html [ Pass Timeout ] crbug.com/856601 [ Linux ] virtual/omt-worker-fetch/external/wpt/fetch/cors-rfc1918/idlharness.tentative.any.serviceworker.html [ Pass Timeout ] crbug.com/856601 [ Linux ] external/wpt/WebCryptoAPI/idlharness.https.any.html [ Pass Timeout ] crbug.com/856601 [ Linux ] external/wpt/web-animations/interfaces/Animation/idlharness.window.html [ Pass Timeout ] @@ -328,19 +326,11 @@ crbug.com/856601 [ Linux ] external/wpt/xhr/idlharness.any.html [ Pass Timeout ] crbug.com/856601 [ Linux ] external/wpt/xhr/idlharness.any.sharedworker.html [ Pass Timeout ] crbug.com/856601 [ Linux ] http/tests/devtools/a11y-axe-core/settings/geolocations-a11y-test.js [ Pass Timeout ] -crbug.com/856601 [ Linux ] virtual/not-omt-sw-fetch/external/wpt/fetch/api/idl.any.html [ Pass Timeout ] -crbug.com/856601 [ Linux ] virtual/not-omt-sw-fetch/external/wpt/fetch/cors-rfc1918/idlharness.tentative.any.sharedworker.html [ Pass Timeout ] -crbug.com/856601 [ Linux ] virtual/not-omt-sw-fetch/external/wpt/xhr/idlharness.any.html [ Pass Timeout ] -crbug.com/856601 [ Linux ] virtual/not-omt-sw-fetch/external/wpt/xhr/idlharness.any.sharedworker.html [ Pass Timeout ] -crbug.com/856601 [ Linux ] virtual/not-omt-sw-fetch/external/wpt/xhr/idlharness.any.worker.html [ Pass Timeout ] crbug.com/856601 [ Linux ] virtual/omt-worker-fetch/external/wpt/fetch/cors-rfc1918/idlharness.tentative.any.sharedworker.html [ Pass Timeout ] crbug.com/856601 [ Linux ] virtual/omt-worker-fetch/external/wpt/xhr/idlharness.any.html [ Pass Timeout ] crbug.com/856601 [ Linux ] virtual/omt-worker-fetch/external/wpt/xhr/idlharness.any.sharedworker.html [ Pass Timeout ] crbug.com/856601 [ Linux ] virtual/omt-worker-fetch/external/wpt/xhr/idlharness.any.worker.html [ Pass Timeout ] crbug.com/856601 [ Linux ] wpt_internal/std-switch/tentative/interface.html [ Pass Timeout ] crbug.com/856601 [ Linux ] http/tests/devtools/a11y-axe-core/elements/main-tool-test.js [ Pass Timeout ] -crbug.com/856601 [ Linux ] virtual/not-omt-sw-fetch/external/wpt/resource-timing/idlharness.any.html [ Pass Timeout ] -crbug.com/856601 [ Linux ] virtual/not-omt-sw-fetch/external/wpt/resource-timing/idlharness.any.worker.html [ Pass Timeout ] crbug.com/856601 [ Linux ] webaudio/Analyser/realtimeanalyser-freq-data.html [ Pass Timeout ] crbug.com/856601 [ Linux ] external/wpt/secure-contexts/idlharness.any.serviceworker.html [ Pass Timeout ] -crbug.com/856601 [ Linux ] virtual/not-omt-sw-fetch/external/wpt/fetch/cors-rfc1918/idlharness.tentative.any.serviceworker.html [ Pass Timeout ]
diff --git a/third_party/blink/web_tests/NeverFixTests b/third_party/blink/web_tests/NeverFixTests index 8be032d..480c9a1a 100644 --- a/third_party/blink/web_tests/NeverFixTests +++ b/third_party/blink/web_tests/NeverFixTests
@@ -2145,11 +2145,6 @@ virtual/omt-worker-fetch/external/wpt/service-workers/service-worker/fetch-event-is-reload-navigation-manual.https.html [ WontFix ] virtual/omt-worker-fetch/external/wpt/xhr/send-authentication-existing-session-manual.htm [ WontFix ] virtual/omt-worker-fetch/external/wpt/xhr/send-authentication-prompt-2-manual.htm [ WontFix ] -virtual/not-omt-sw-fetch/external/wpt/service-workers/service-worker/fetch-event-is-history-backward-navigation-manual.https.html [ WontFix ] -virtual/not-omt-sw-fetch/external/wpt/service-workers/service-worker/fetch-event-is-history-forward-navigation-manual.https.html [ WontFix ] -virtual/not-omt-sw-fetch/external/wpt/service-workers/service-worker/fetch-event-is-reload-navigation-manual.https.html [ WontFix ] -virtual/not-omt-sw-fetch/external/wpt/xhr/send-authentication-existing-session-manual.htm [ WontFix ] -virtual/not-omt-sw-fetch/external/wpt/xhr/send-authentication-prompt-2-manual.htm [ WontFix ] virtual/cache-storage-parallel/external/wpt/service-workers/service-worker/fetch-event-is-history-backward-navigation-manual.https.html [ WontFix ] virtual/cache-storage-parallel/external/wpt/service-workers/service-worker/fetch-event-is-history-forward-navigation-manual.https.html [ WontFix ] virtual/cache-storage-parallel/external/wpt/service-workers/service-worker/fetch-event-is-reload-navigation-manual.https.html [ WontFix ]
diff --git a/third_party/blink/web_tests/TestExpectations b/third_party/blink/web_tests/TestExpectations index 58b9c23..3c212ef 100644 --- a/third_party/blink/web_tests/TestExpectations +++ b/third_party/blink/web_tests/TestExpectations
@@ -1367,7 +1367,6 @@ ### Missing refs, these are also skipped for existing layout. crbug.com/967329 virtual/layout_ng_experimental/external/wpt/css/css-multicol/columnfill-auto-max-height-002.html [ Failure ] crbug.com/967329 virtual/layout_ng_experimental/external/wpt/css/css-multicol/columnfill-auto-max-height-001.html [ Failure ] -crbug.com/829028 virtual/layout_ng_experimental/external/wpt/css/css-multicol/filter-with-abspos.html [ Failure ] crbug.com/829028 virtual/layout_ng_experimental/external/wpt/css/css-multicol/float-and-block.html [ Failure ] crbug.com/829028 virtual/layout_ng_experimental/external/wpt/css/css-multicol/float-with-line-after-spanner.html [ Failure ] crbug.com/829028 virtual/layout_ng_experimental/external/wpt/css/css-multicol/inline-block-and-column-span-all.html [ Failure ] @@ -1501,8 +1500,6 @@ crbug.com/829028 virtual/layout_ng_experimental/external/wpt/css/css-multicol/multicol-span-all-children-height-005.html [ Failure ] crbug.com/829028 virtual/layout_ng_experimental/external/wpt/css/css-multicol/multicol-span-all-children-height-006.html [ Failure ] crbug.com/924142 virtual/layout_ng_experimental/external/wpt/css/css-multicol/multicol-span-all-dynamic-add-010.html [ Crash Pass ] -crbug.com/829028 virtual/layout_ng_experimental/external/wpt/css/css-multicol/multicol-span-all-dynamic-add-012.html [ Failure Crash ] -crbug.com/829028 virtual/layout_ng_experimental/external/wpt/css/css-multicol/multicol-span-all-dynamic-add-013.html [ Failure Crash ] crbug.com/874051 virtual/layout_ng_experimental/external/wpt/css/css-multicol/multicol-span-all-fieldset-001.html [ Failure ] crbug.com/874051 virtual/layout_ng_experimental/external/wpt/css/css-multicol/multicol-span-all-fieldset-002.html [ Failure ] crbug.com/874051 virtual/layout_ng_experimental/external/wpt/css/css-multicol/multicol-span-all-fieldset-003.html [ Failure ] @@ -1566,7 +1563,6 @@ crbug.com/591099 virtual/layout_ng_experimental/fast/multicol/composited-relpos-resize.html [ Failure ] crbug.com/591099 virtual/layout_ng_experimental/fast/multicol/composited-with-child-layer-in-next-column.html [ Failure ] crbug.com/591099 virtual/layout_ng_experimental/fast/multicol/composited-with-overflow-in-next-column.html [ Failure ] -crbug.com/591099 virtual/layout_ng_experimental/fast/multicol/cssom-view.html [ Crash ] crbug.com/591099 virtual/layout_ng_experimental/fast/multicol/doubly-nested-with-top-padding-crossing-row-boundaries.html [ Failure ] crbug.com/591099 virtual/layout_ng_experimental/fast/multicol/dynamic/abspos-becomes-spanner.html [ Failure ] crbug.com/591099 virtual/layout_ng_experimental/fast/multicol/dynamic/abspos-multicol-with-spanner-becomes-spanner.html [ Failure ] @@ -2243,7 +2239,6 @@ crbug.com/983788 http/tests/cookies/same-site/popup-cross-site-post.html [ Pass Timeout ] crbug.com/984438 external/wpt/css/css-scroll-snap/snap-at-user-scroll-end-manual.html [ Failure Pass ] crbug.com/982148 [ Win7 ] virtual/blink-cors/external/wpt/referrer-policy/same-origin/http-rp/same-origin/http-http/img-tag/keep-origin-redirect/same-origin-insecure.http.html [ Pass Timeout ] -crbug.com/982148 [ Win7 ] virtual/not-omt-sw-fetch/external/wpt/referrer-policy/same-origin/http-rp/same-origin/http-http/img-tag/keep-origin-redirect/same-origin-insecure.http.html [ Pass Timeout ] crbug.com/982148 [ Win7 ] virtual/omt-worker-fetch/external/wpt/referrer-policy/same-origin/http-rp/same-origin/http-http/img-tag/keep-origin-redirect/same-origin-insecure.http.html [ Pass Timeout ] crbug.com/984467 [ Linux Debug ] virtual/gpu/fast/canvas/canvas-composite-stroke-alpha.html [ Pass Timeout ] crbug.com/984467 [ Mac ] virtual/gpu/fast/canvas/canvas-composite-stroke-alpha.html [ Pass Timeout ] @@ -3183,7 +3178,6 @@ crbug.com/832071 external/wpt/service-workers/service-worker/worker-client-id.https.html [ Failure ] crbug.com/832071 virtual/blink-cors/external/wpt/service-workers/service-worker/worker-client-id.https.html [ Failure ] crbug.com/832071 virtual/navigation-mojo-response/external/wpt/service-workers/service-worker/worker-client-id.https.html [ Failure ] -crbug.com/832071 virtual/not-omt-sw-fetch/external/wpt/service-workers/service-worker/worker-client-id.https.html [ Failure ] crbug.com/832071 virtual/cache-storage-parallel/external/wpt/service-workers/service-worker/worker-client-id.https.html [ Failure ] crbug.com/832071 virtual/cache-storage-sequence/external/wpt/service-workers/service-worker/worker-client-id.https.html [ Failure ] @@ -3351,11 +3345,8 @@ crbug.com/626703 [ Win7 ] virtual/omt-worker-fetch/external/wpt/referrer-policy/unsafe-url/attr-referrer/same-origin/http-http/img-tag/keep-origin-redirect/generic.http.html [ Timeout ] crbug.com/626703 external/wpt/css/css-text/line-break/line-break-anywhere-002.html [ Failure ] crbug.com/626703 [ Win7 ] external/wpt/IndexedDB/structured-clone.any.html [ Timeout ] -crbug.com/626703 [ Win7 ] virtual/not-omt-sw-fetch/external/wpt/referrer-policy/unsafe-url/attr-referrer/same-origin/http-http/img-tag/no-redirect/generic.http.html [ Timeout ] crbug.com/626703 [ Win7 ] virtual/omt-worker-fetch/external/wpt/referrer-policy/unset-referrer-policy/attr-referrer/cross-origin/http-http/img-tag/no-redirect/insecure-protocol.http.html [ Timeout ] -crbug.com/626703 [ Win7 ] virtual/not-omt-sw-fetch/external/wpt/referrer-policy/unsafe-url/http-rp/same-origin/http-http/img-tag/swap-origin-redirect/generic.http.html [ Timeout ] crbug.com/626703 [ Win7 ] virtual/omt-worker-fetch/external/wpt/referrer-policy/unset-referrer-policy/attr-referrer/cross-origin/http-http/img-tag/keep-origin-redirect/insecure-protocol.http.html [ Timeout ] -crbug.com/626703 [ Win7 ] virtual/not-omt-sw-fetch/external/wpt/referrer-policy/strict-origin-when-cross-origin/attr-referrer/same-origin/http-http/img-tag/no-redirect/same-insecure.http.html [ Timeout ] crbug.com/626703 [ Win7 ] virtual/blink-cors/external/wpt/referrer-policy/unsafe-url/meta-referrer/same-origin/http-http/img-tag/keep-origin-redirect/generic.http.html [ Timeout ] crbug.com/626703 [ Win7 ] virtual/blink-cors/external/wpt/referrer-policy/unsafe-url/attr-referrer/same-origin/http-http/img-tag/swap-origin-redirect/generic.http.html [ Timeout ] crbug.com/626703 [ Mac10.12 ] external/wpt/html/semantics/embedded-content/media-elements/track/track-element/track-cues-sorted-before-dispatch.html [ Timeout ] @@ -3636,7 +3627,6 @@ crbug.com/626703 external/wpt/service-workers/service-worker/ready.https.html [ Timeout ] crbug.com/626703 virtual/blink-cors/external/wpt/service-workers/service-worker/ready.https.html [ Timeout ] crbug.com/626703 virtual/omt-worker-fetch/external/wpt/service-workers/service-worker/ready.https.html [ Timeout ] -crbug.com/626703 virtual/not-omt-sw-fetch/external/wpt/service-workers/service-worker/ready.https.html [ Timeout ] crbug.com/626703 virtual/cache-storage-parallel/external/wpt/service-workers/service-worker/ready.https.html [ Timeout ] crbug.com/626703 virtual/cache-storage-sequence/external/wpt/service-workers/service-worker/ready.https.html [ Timeout ] crbug.com/626703 [ Linux ] external/wpt/css/css-fonts/math-script-level-and-math-style/math-script-level-auto-and-math-style-002.tentative.html [ Failure ] @@ -3705,7 +3695,6 @@ crbug.com/626703 external/wpt/xhr/abort-after-stop.any.worker.html [ Timeout ] crbug.com/626703 virtual/blink-cors/external/wpt/xhr/abort-after-stop.any.worker.html [ Timeout ] crbug.com/626703 virtual/omt-worker-fetch/external/wpt/xhr/abort-after-stop.any.worker.html [ Timeout ] -crbug.com/626703 virtual/not-omt-sw-fetch/external/wpt/xhr/abort-after-stop.any.worker.html [ Timeout ] crbug.com/626703 external/wpt/webvtt/rendering/cues-with-video/processing-model/bidi/vertical_rl.html [ Failure ] crbug.com/626703 external/wpt/webvtt/rendering/cues-with-video/processing-model/selectors/cue/vertical_ruby-position.html [ Failure ] crbug.com/626703 external/wpt/webvtt/rendering/cues-with-video/processing-model/selectors/cue_function/class_object/class_vertical_text-combine-upright.html [ Failure ] @@ -3772,7 +3761,6 @@ crbug.com/626703 external/wpt/xhr/event-readystatechange-loaded.any.worker.html [ Timeout Failure ] crbug.com/626703 virtual/blink-cors/external/wpt/xhr/event-readystatechange-loaded.any.worker.html [ Timeout Failure ] crbug.com/626703 virtual/omt-worker-fetch/external/wpt/xhr/event-readystatechange-loaded.any.worker.html [ Timeout Failure ] -crbug.com/626703 virtual/not-omt-sw-fetch/external/wpt/xhr/event-readystatechange-loaded.any.worker.html [ Timeout Failure ] crbug.com/626703 external/wpt/css/css-sizing/image-min-max-content-intrinsic-size-change-003.html [ Failure ] crbug.com/626703 external/wpt/css/css-text/line-breaking/line-breaking-017.html [ Failure ] crbug.com/626703 external/wpt/css/css-scroll-snap/scroll-target-padding-003.html [ Failure ] @@ -3795,7 +3783,6 @@ crbug.com/626703 external/wpt/xhr/event-readystatechange-loaded.any.html [ Timeout Failure ] crbug.com/626703 virtual/blink-cors/external/wpt/xhr/event-readystatechange-loaded.any.html [ Timeout Failure ] crbug.com/626703 virtual/omt-worker-fetch/external/wpt/xhr/event-readystatechange-loaded.any.html [ Timeout Failure ] -crbug.com/626703 virtual/not-omt-sw-fetch/external/wpt/xhr/event-readystatechange-loaded.any.html [ Timeout Failure ] crbug.com/626703 virtual/threaded/external/wpt/css/css-scroll-snap/scroll-target-margin-002.html [ Failure ] crbug.com/626703 virtual/threaded/external/wpt/css/css-scroll-snap/scroll-target-padding-002.html [ Failure ] crbug.com/626703 virtual/threaded/external/wpt/css/css-scroll-snap/scroll-target-snap-003.html [ Failure ] @@ -3930,7 +3917,6 @@ crbug.com/626703 external/wpt/fetch/content-type/response.window.html [ Timeout ] crbug.com/626703 virtual/blink-cors/external/wpt/fetch/content-type/response.window.html [ Timeout ] crbug.com/626703 virtual/omt-worker-fetch/external/wpt/fetch/content-type/response.window.html [ Timeout ] -crbug.com/626703 virtual/not-omt-sw-fetch/external/wpt/fetch/content-type/response.window.html [ Timeout ] crbug.com/626703 virtual/streaming-preload/external/wpt/html/semantics/scripting-1/the-script-element/module/dynamic-import/no-active-script-manual-module.html [ Timeout ] crbug.com/626703 virtual/streaming-preload/external/wpt/html/semantics/scripting-1/the-script-element/module/dynamic-import/no-active-script-manual-classic.html [ Timeout ] crbug.com/626703 external/wpt/html/semantics/scripting-1/the-script-element/module/dynamic-import/no-active-script-manual-classic.html [ Timeout ] @@ -4010,11 +3996,6 @@ crbug.com/626703 virtual/omt-worker-fetch/external/wpt/referrer-policy/css-integration/svg/internal-stylesheet.html [ Timeout Failure ] crbug.com/626703 virtual/omt-worker-fetch/external/wpt/referrer-policy/css-integration/svg/presentation-attribute.html [ Timeout Failure ] crbug.com/626703 virtual/omt-worker-fetch/external/wpt/referrer-policy/css-integration/svg/processing-instruction.html [ Timeout Failure ] -crbug.com/626703 virtual/not-omt-sw-fetch/external/wpt/referrer-policy/css-integration/svg/external-stylesheet.html [ Timeout Failure ] -crbug.com/626703 virtual/not-omt-sw-fetch/external/wpt/referrer-policy/css-integration/svg/inline-style.html [ Timeout Failure ] -crbug.com/626703 virtual/not-omt-sw-fetch/external/wpt/referrer-policy/css-integration/svg/internal-stylesheet.html [ Timeout Failure ] -crbug.com/626703 virtual/not-omt-sw-fetch/external/wpt/referrer-policy/css-integration/svg/presentation-attribute.html [ Timeout Failure ] -crbug.com/626703 virtual/not-omt-sw-fetch/external/wpt/referrer-policy/css-integration/svg/processing-instruction.html [ Timeout Failure ] crbug.com/367760 external/wpt/svg/pservers/reftests/meshgradient-complex-001.svg [ Failure ] crbug.com/367760 external/wpt/svg/pservers/reftests/meshgradient-bicubic-001.svg [ Failure ] @@ -4141,7 +4122,6 @@ crbug.com/626703 external/wpt/fetch/security/redirect-to-url-with-credentials.https.html [ Timeout ] crbug.com/626703 virtual/blink-cors/external/wpt/fetch/security/redirect-to-url-with-credentials.https.html [ Timeout ] crbug.com/626703 virtual/omt-worker-fetch/external/wpt/fetch/security/redirect-to-url-with-credentials.https.html [ Timeout ] -crbug.com/626703 virtual/not-omt-sw-fetch/external/wpt/fetch/security/redirect-to-url-with-credentials.https.html [ Timeout ] crbug.com/626703 external/wpt/css/vendor-imports/mozilla/mozilla-central-reftests/shapes1/shape-outside-polygon-024.html [ Failure ] crbug.com/626703 external/wpt/css/vendor-imports/mozilla/mozilla-central-reftests/shapes1/shape-outside-ellipse-048.html [ Failure ] crbug.com/626703 external/wpt/css/vendor-imports/mozilla/mozilla-central-reftests/shapes1/shape-outside-inset-026.html [ Failure ] @@ -4216,7 +4196,6 @@ crbug.com/626703 external/wpt/fetch/http-cache/basic-auth-cache-test.html [ Timeout ] crbug.com/626703 virtual/blink-cors/external/wpt/fetch/http-cache/basic-auth-cache-test.html [ Timeout ] crbug.com/626703 virtual/omt-worker-fetch/external/wpt/fetch/http-cache/basic-auth-cache-test.html [ Timeout ] -crbug.com/626703 virtual/not-omt-sw-fetch/external/wpt/fetch/http-cache/basic-auth-cache-test.html [ Timeout ] crbug.com/626703 external/wpt/css/css-fonts/font-feature-settings-descriptor-01.html [ Failure ] crbug.com/626703 [ Win10 ] external/wpt/fetch/api/redirect/redirect-count.any.worker.html [ Timeout ] crbug.com/626703 [ Win10 ] external/wpt/fetch/api/redirect/redirect-count.any.html [ Timeout ] @@ -4457,7 +4436,6 @@ crbug.com/648295 external/wpt/service-workers/service-worker/update-bytecheck.https.html [ Timeout ] crbug.com/648295 virtual/blink-cors/external/wpt/service-workers/service-worker/update-bytecheck.https.html [ Timeout ] crbug.com/648295 virtual/omt-worker-fetch/external/wpt/service-workers/service-worker/update-bytecheck.https.html [ Timeout ] -crbug.com/648295 virtual/not-omt-sw-fetch/external/wpt/service-workers/service-worker/update-bytecheck.https.html [ Timeout ] crbug.com/648295 virtual/cache-storage-parallel/external/wpt/service-workers/service-worker/update-bytecheck.https.html [ Timeout ] crbug.com/648295 virtual/cache-storage-sequence/external/wpt/service-workers/service-worker/update-bytecheck.https.html [ Timeout ] crbug.com/626703 external/wpt/svg/linking/reftests/href-filter-element.html [ Failure ] @@ -4675,11 +4653,9 @@ crbug.com/626703 external/wpt/xhr/preserve-ua-header-on-redirect.htm [ Failure ] crbug.com/626703 virtual/blink-cors/external/wpt/xhr/preserve-ua-header-on-redirect.htm [ Failure ] crbug.com/626703 virtual/omt-worker-fetch/external/wpt/xhr/preserve-ua-header-on-redirect.htm [ Failure ] -crbug.com/626703 virtual/not-omt-sw-fetch/external/wpt/xhr/preserve-ua-header-on-redirect.htm [ Failure ] crbug.com/626703 external/wpt/xhr/setrequestheader-header-allowed.htm [ Failure ] crbug.com/626703 virtual/blink-cors/external/wpt/xhr/setrequestheader-header-allowed.htm [ Failure ] crbug.com/626703 virtual/omt-worker-fetch/external/wpt/xhr/setrequestheader-header-allowed.htm [ Failure ] -crbug.com/626703 virtual/not-omt-sw-fetch/external/wpt/xhr/setrequestheader-header-allowed.htm [ Failure ] crbug.com/626703 [ Win10 ] external/wpt/preload/delaying-onload-link-preload-after-discovery.html [ Timeout ] crbug.com/626703 [ Win ] external/wpt/css/css-writing-modes/box-offsets-rel-pos-vlr-005.xht [ Failure ] crbug.com/626703 [ Win ] external/wpt/css/css-writing-modes/box-offsets-rel-pos-vrl-004.xht [ Failure ] @@ -4738,7 +4714,6 @@ crbug.com/917554 external/wpt/upgrade-insecure-requests/worker-subresource-fetch-upgrade.https.html [ Crash ] crbug.com/917554 virtual/omt-worker-fetch/external/wpt/upgrade-insecure-requests/worker-subresource-fetch-upgrade.https.html [ Crash ] -crbug.com/917554 virtual/not-omt-sw-fetch/external/wpt/upgrade-insecure-requests/worker-subresource-fetch-upgrade.https.html [ Crash ] # Different results on try bots and CQ, skipped to unblock wpt import. crbug.com/888443 external/wpt/css/cssom-view/scroll-behavior-default-css.html [ Skip ] @@ -4757,8 +4732,6 @@ crbug.com/888470 virtual/blink-cors/external/wpt/referrer-policy/css-integration/child-css/processing-instruction.html [ Failure ] crbug.com/888470 virtual/omt-worker-fetch/external/wpt/referrer-policy/css-integration/child-css/internal-import-stylesheet.html [ Failure ] crbug.com/888470 virtual/omt-worker-fetch/external/wpt/referrer-policy/css-integration/child-css/processing-instruction.html [ Failure ] -crbug.com/888470 virtual/not-omt-sw-fetch/external/wpt/referrer-policy/css-integration/child-css/internal-import-stylesheet.html [ Failure ] -crbug.com/888470 virtual/not-omt-sw-fetch/external/wpt/referrer-policy/css-integration/child-css/processing-instruction.html [ Failure ] # This behavior (popups during unload) is being reverted on trunk; this test is # expected to fail when this change is merged back to earlier branches. @@ -4792,14 +4765,11 @@ crbug.com/881180 external/wpt/xhr/open-url-multi-window-4.htm [ Timeout ] crbug.com/881180 virtual/blink-cors/external/wpt/xhr/open-url-multi-window-4.htm [ Timeout ] crbug.com/881180 virtual/omt-worker-fetch/external/wpt/xhr/open-url-multi-window-4.htm [ Timeout ] -crbug.com/881180 virtual/not-omt-sw-fetch/external/wpt/xhr/open-url-multi-window-4.htm [ Timeout ] crbug.com/655458 external/wpt/workers/Worker_terminate_event_queue.htm [ Pass Timeout ] crbug.com/655458 external/wpt/workers/semantics/multiple-workers/007.html [ Timeout ] crbug.com/655458 virtual/omt-worker-fetch/external/wpt/workers/Worker_terminate_event_queue.htm [ Pass Timeout ] crbug.com/655458 virtual/omt-worker-fetch/external/wpt/workers/semantics/multiple-workers/007.html [ Timeout ] -crbug.com/655458 virtual/not-omt-sw-fetch/external/wpt/workers/Worker_terminate_event_queue.htm [ Pass Timeout ] -crbug.com/655458 virtual/not-omt-sw-fetch/external/wpt/workers/semantics/multiple-workers/007.html [ Timeout ] crbug.com/910709 navigator_language/worker_navigator_language.html [ Timeout ] @@ -4865,7 +4835,6 @@ crbug.com/691944 external/wpt/service-workers/service-worker/update-after-oneday.https.html [ Skip ] crbug.com/691944 virtual/blink-cors/external/wpt/service-workers/service-worker/update-after-oneday.https.html [ Skip ] crbug.com/691944 virtual/omt-worker-fetch/external/wpt/service-workers/service-worker/update-after-oneday.https.html [ Skip ] -crbug.com/691944 virtual/not-omt-sw-fetch/external/wpt/service-workers/service-worker/update-after-oneday.https.html [ Skip ] crbug.com/691944 virtual/cache-storage-parallel/external/wpt/service-workers/service-worker/update-after-oneday.https.html [ Skip ] crbug.com/691944 virtual/cache-storage-sequence/external/wpt/service-workers/service-worker/update-after-oneday.https.html [ Skip ] @@ -4873,7 +4842,6 @@ crbug.com/595993 external/wpt/service-workers/service-worker/fetch-header-visibility.https.html [ Failure ] crbug.com/595993 virtual/blink-cors/external/wpt/service-workers/service-worker/fetch-header-visibility.https.html [ Failure ] crbug.com/595993 virtual/omt-worker-fetch/external/wpt/service-workers/service-worker/fetch-header-visibility.https.html [ Failure ] -crbug.com/595993 virtual/not-omt-sw-fetch/external/wpt/service-workers/service-worker/fetch-header-visibility.https.html [ Failure ] crbug.com/595993 virtual/cache-storage-parallel/external/wpt/service-workers/service-worker/fetch-header-visibility.https.html [ Failure ] crbug.com/595993 virtual/cache-storage-sequence/external/wpt/service-workers/service-worker/fetch-header-visibility.https.html [ Failure ] @@ -5134,7 +5102,6 @@ crbug.com/889798 virtual/blink-cors/external/wpt/service-workers/service-worker/import-scripts-redirect.https.html [ Skip ] crbug.com/889798 virtual/cache-storage-parallel/external/wpt/service-workers/service-worker/import-scripts-redirect.https.html [ Skip ] crbug.com/889798 virtual/cache-storage-sequence/external/wpt/service-workers/service-worker/import-scripts-redirect.https.html [ Skip ] -crbug.com/889798 virtual/not-omt-sw-fetch/external/wpt/service-workers/service-worker/import-scripts-redirect.https.html [ Skip ] crbug.com/889798 virtual/omt-worker-fetch/external/wpt/service-workers/service-worker/import-scripts-redirect.https.html [ Skip ] # Sheriff failures 2017-07-03 @@ -5720,8 +5687,6 @@ crbug.com/873873 external/wpt/service-workers/service-worker/fetch-canvas-tainting-video.https.html [ Timeout Pass ] crbug.com/873873 external/wpt/service-workers/service-worker/fetch-canvas-tainting-video-cache.https.html [ Timeout Pass ] -crbug.com/873873 virtual/not-omt-sw-fetch/external/wpt/service-workers/service-worker/fetch-canvas-tainting-video.https.html [ Timeout Pass ] -crbug.com/873873 virtual/not-omt-sw-fetch/external/wpt/service-workers/service-worker/fetch-canvas-tainting-video-cache.https.html [ Timeout Pass ] crbug.com/873873 virtual/cache-storage-parallel/external/wpt/service-workers/service-worker/fetch-canvas-tainting-video.https.html [ Timeout Pass ] crbug.com/873873 virtual/cache-storage-parallel/external/wpt/service-workers/service-worker/fetch-canvas-tainting-video-cache.https.html [ Timeout Pass ] crbug.com/873873 virtual/cache-storage-sequence/external/wpt/service-workers/service-worker/fetch-canvas-tainting-video.https.html [ Timeout Pass ] @@ -6076,7 +6041,6 @@ crbug.com/933880 external/wpt/service-workers/service-worker/request-end-to-end.https.html [ Failure ] crbug.com/933880 virtual/blink-cors/external/wpt/service-workers/service-worker/request-end-to-end.https.html [ Failure ] crbug.com/933880 virtual/omt-worker-fetch/external/wpt/service-workers/service-worker/request-end-to-end.https.html [ Failure ] -crbug.com/933880 virtual/not-omt-sw-fetch/external/wpt/service-workers/service-worker/request-end-to-end.https.html [ Failure ] crbug.com/933880 virtual/cache-storage-parallel/external/wpt/service-workers/service-worker/request-end-to-end.https.html [ Failure ] crbug.com/933880 virtual/cache-storage-sequence/external/wpt/service-workers/service-worker/request-end-to-end.https.html [ Failure ] crbug.com/933880 http/tests/inspector-protocol/network/interception-take-stream.js [ Failure ] @@ -6309,9 +6273,6 @@ crbug.com/865432 [ Linux ] virtual/omt-worker-fetch/external/wpt/workers/modules/dedicated-worker-import-blob-url.any.worker.html [ Timeout Pass ] crbug.com/867532 [ Linux ] virtual/omt-worker-fetch/external/wpt/workers/modules/dedicated-worker-import-data-url.any.worker.html [ Timeout Pass ] crbug.com/867532 [ Linux ] virtual/omt-worker-fetch/external/wpt/workers/modules/dedicated-worker-import.any.worker.html [ Timeout Pass ] -crbug.com/865432 [ Linux ] virtual/not-omt-sw-fetch/external/wpt/workers/modules/dedicated-worker-import-blob-url.any.worker.html [ Timeout Pass ] -crbug.com/867532 [ Linux ] virtual/not-omt-sw-fetch/external/wpt/workers/modules/dedicated-worker-import-data-url.any.worker.html [ Timeout Pass ] -crbug.com/867532 [ Linux ] virtual/not-omt-sw-fetch/external/wpt/workers/modules/dedicated-worker-import.any.worker.html [ Timeout Pass ] crbug.com/937170 [ Linux Win7 ] external/wpt/IndexedDB/interleaved-cursors-large.html [ Pass Timeout ] crbug.com/937991 [ Win7 Release ] http/tests/devtools/cache-storage/cache-data.js [ Pass Timeout ] @@ -6436,7 +6397,6 @@ crbug.com/979565 [ Mac ] virtual/focusless-spat-nav/fast/spatial-navigation/focusless/snav-focusless-fullscreen-video.html [ Pass Failure ] crbug.com/979593 [ Linux Win ] external/wpt/service-workers/service-worker/registration-schedule-job.https.html [ Pass Failure ] crbug.com/979593 [ Linux Win ] virtual/blink-cors/external/wpt/service-workers/service-worker/registration-schedule-job.https.html [ Pass Failure ] -crbug.com/979593 [ Linux Win ] virtual/not-omt-sw-fetch/external/wpt/service-workers/service-worker/registration-schedule-job.https.html [ Pass Failure ] crbug.com/979593 [ Linux Win ] virtual/omt-worker-fetch/external/wpt/service-workers/service-worker/registration-schedule-job.https.html [ Pass Failure ] # Sheriff 2019-07-03 @@ -6458,7 +6418,6 @@ # Sheriff 2019-07-17 crbug.com/982149 [ Win7 ] external/wpt/referrer-policy/unsafe-url/http-rp/cross-origin/http-http/img-tag/no-redirect/generic.http.html [ Pass Timeout ] crbug.com/982149 [ Win7 ] virtual/blink-cors/external/wpt/referrer-policy/unsafe-url/http-rp/cross-origin/http-http/img-tag/no-redirect/generic.http.html [ Pass Timeout ] -crbug.com/982149 [ Win7 ] virtual/not-omt-sw-fetch/external/wpt/referrer-policy/unsafe-url/http-rp/cross-origin/http-http/img-tag/no-redirect/generic.http.html [ Pass Timeout ] crbug.com/982149 [ Win7 ] virtual/omt-worker-fetch/external/wpt/referrer-policy/unsafe-url/http-rp/cross-origin/http-http/img-tag/no-redirect/generic.http.html [ Pass Timeout ] # WebRTC "onnegotiationneeded" firing too early causing us to miss the event. @@ -6533,7 +6492,6 @@ crbug.com/626703 [ Mac ] external/wpt/css/cssom-view/scrollIntoView-sideways-rl-writing-mode-and-rtl-direction.html [ Failure ] crbug.com/988890 [ Win7 Release ] external/wpt/referrer-policy/strict-origin-when-cross-origin/attr-referrer/same-origin/http-http/img-tag/keep-origin-redirect/same-insecure.http.html [ Pass Timeout ] crbug.com/988890 [ Win7 Release ] virtual/blink-cors/external/wpt/referrer-policy/strict-origin-when-cross-origin/attr-referrer/same-origin/http-http/img-tag/keep-origin-redirect/same-insecure.http.html [ Pass Timeout ] -crbug.com/988890 [ Win7 Release ] virtual/not-omt-sw-fetch/external/wpt/referrer-policy/strict-origin-when-cross-origin/attr-referrer/same-origin/http-http/img-tag/keep-origin-redirect/same-insecure.http.html [ Pass Timeout ] # Sheriff 2019-07-31 crbug.com/979422 [ Mac ] fast/borders/border-radius-mask-video-shadow.html [ Failure ] @@ -6555,14 +6513,12 @@ # Sheriff 2019-08-01 crbug.com/989860 [ Mac10.13 Linux Debug ] http/tests/devtools/indexeddb/live-update-indexeddb-list.js [ Pass Failure ] crbug.com/989717 [ Fuchsia ] http/tests/preload/avoid_delaying_onload_link_preload.html [ Pass Failure ] -crbug.com/988074 [ Linux ] virtual/not-omt-sw-fetch/http/tests/security/cors-rfc1918/addressspace-serviceworker-basic.html [ Pass Failure ] crbug.com/988074 [ Linux ] virtual/omt-worker-fetch/http/tests/security/cors-rfc1918/addressspace-serviceworker-basic.html [ Pass Failure ] # Sheriff 2019-08-05 crbug.com/981522 [ Linux ] external/wpt/svg/animations/correct-events-for-short-animations-with-syncbases.html [ Pass Failure Timeout ] crbug.com/991243 [ Linux ] external/wpt/workers/semantics/multiple-workers/003.html [ Pass Timeout ] crbug.com/991243 [ Linux ] virtual/omt-worker-fetch/external/wpt/workers/semantics/multiple-workers/003.html [ Pass Timeout ] -crbug.com/991243 [ Linux ] virtual/not-omt-sw-fetch/external/wpt/workers/semantics/multiple-workers/003.html [ Pass Timeout ] # Sheriff 2019-08-08 crbug.com/992148 [ Linux ] virtual/disable-blink-gen-property-trees/animations/stability/animation-iteration-event-destroy-renderer.html [ Pass Timeout ]
diff --git a/third_party/blink/web_tests/VirtualTestSuites b/third_party/blink/web_tests/VirtualTestSuites index 371517d..2a262f9 100644 --- a/third_party/blink/web_tests/VirtualTestSuites +++ b/third_party/blink/web_tests/VirtualTestSuites
@@ -596,183 +596,93 @@ { "prefix": "omt-worker-fetch", "base": "external/wpt/content-security-policy/inside-worker", - "args": ["--enable-features=OffMainThreadDedicatedWorkerScriptFetch,PlzDedicatedWorker,OffMainThreadServiceWorkerScriptFetch"] + "args": ["--enable-features=OffMainThreadDedicatedWorkerScriptFetch,PlzDedicatedWorker"] }, { "prefix": "omt-worker-fetch", "base": "external/wpt/content-security-policy/worker-src", - "args": ["--enable-features=OffMainThreadDedicatedWorkerScriptFetch,PlzDedicatedWorker,OffMainThreadServiceWorkerScriptFetch"] + "args": ["--enable-features=OffMainThreadDedicatedWorkerScriptFetch,PlzDedicatedWorker"] }, { "prefix": "omt-worker-fetch", "base": "external/wpt/fetch/", - "args": ["--enable-features=OffMainThreadDedicatedWorkerScriptFetch,PlzDedicatedWorker,OffMainThreadServiceWorkerScriptFetch"] + "args": ["--enable-features=OffMainThreadDedicatedWorkerScriptFetch,PlzDedicatedWorker"] }, { "prefix": "omt-worker-fetch", "base": "external/wpt/html/browsers/offline/appcache/workers/", - "args": ["--enable-features=OffMainThreadDedicatedWorkerScriptFetch,PlzDedicatedWorker,OffMainThreadServiceWorkerScriptFetch"] + "args": ["--enable-features=OffMainThreadDedicatedWorkerScriptFetch,PlzDedicatedWorker"] }, { "prefix": "omt-worker-fetch", "base": "external/wpt/mixed-content/classic-data-worker-fetch", - "args": ["--enable-features=OffMainThreadDedicatedWorkerScriptFetch,PlzDedicatedWorker,OffMainThreadServiceWorkerScriptFetch"] + "args": ["--enable-features=OffMainThreadDedicatedWorkerScriptFetch,PlzDedicatedWorker"] }, { "prefix": "omt-worker-fetch", "base": "external/wpt/mixed-content/module-data-worker-import", - "args": ["--enable-features=OffMainThreadDedicatedWorkerScriptFetch,PlzDedicatedWorker,OffMainThreadServiceWorkerScriptFetch"] + "args": ["--enable-features=OffMainThreadDedicatedWorkerScriptFetch,PlzDedicatedWorker"] }, { "prefix": "omt-worker-fetch", "base": "external/wpt/mixed-content/module-worker-top-level", - "args": ["--enable-features=OffMainThreadDedicatedWorkerScriptFetch,PlzDedicatedWorker,OffMainThreadServiceWorkerScriptFetch"] + "args": ["--enable-features=OffMainThreadDedicatedWorkerScriptFetch,PlzDedicatedWorker"] }, { "prefix": "omt-worker-fetch", "base": "external/wpt/mixed-content/worker-request", - "args": ["--enable-features=OffMainThreadDedicatedWorkerScriptFetch,PlzDedicatedWorker,OffMainThreadServiceWorkerScriptFetch"] + "args": ["--enable-features=OffMainThreadDedicatedWorkerScriptFetch,PlzDedicatedWorker"] }, { "prefix": "omt-worker-fetch", "base": "external/wpt/referrer-policy", - "args": ["--enable-features=OffMainThreadDedicatedWorkerScriptFetch,PlzDedicatedWorker,OffMainThreadServiceWorkerScriptFetch"] + "args": ["--enable-features=OffMainThreadDedicatedWorkerScriptFetch,PlzDedicatedWorker"] }, { "prefix": "omt-worker-fetch", "base": "external/wpt/resource-timing", - "args": ["--enable-features=OffMainThreadDedicatedWorkerScriptFetch,PlzDedicatedWorker,OffMainThreadServiceWorkerScriptFetch"] + "args": ["--enable-features=OffMainThreadDedicatedWorkerScriptFetch,PlzDedicatedWorker"] }, { "prefix": "omt-worker-fetch", "base": "external/wpt/service-workers", - "args": ["--enable-features=OffMainThreadDedicatedWorkerScriptFetch,PlzDedicatedWorker,OffMainThreadServiceWorkerScriptFetch"] + "args": ["--enable-features=OffMainThreadDedicatedWorkerScriptFetch,PlzDedicatedWorker"] }, { "prefix": "omt-worker-fetch", "base": "external/wpt/upgrade-insecure-requests", - "args": ["--enable-features=OffMainThreadDedicatedWorkerScriptFetch,PlzDedicatedWorker,OffMainThreadServiceWorkerScriptFetch"] + "args": ["--enable-features=OffMainThreadDedicatedWorkerScriptFetch,PlzDedicatedWorker"] }, { "prefix": "omt-worker-fetch", "base": "external/wpt/workers", - "args": ["--enable-features=OffMainThreadDedicatedWorkerScriptFetch,PlzDedicatedWorker,OffMainThreadServiceWorkerScriptFetch"] + "args": ["--enable-features=OffMainThreadDedicatedWorkerScriptFetch,PlzDedicatedWorker"] }, { "prefix": "omt-worker-fetch", "base": "external/wpt/xhr", - "args": ["--enable-features=OffMainThreadDedicatedWorkerScriptFetch,PlzDedicatedWorker,OffMainThreadServiceWorkerScriptFetch"] + "args": ["--enable-features=OffMainThreadDedicatedWorkerScriptFetch,PlzDedicatedWorker"] }, { "prefix": "omt-worker-fetch", "base": "fast/workers", - "args": ["--enable-features=OffMainThreadDedicatedWorkerScriptFetch,PlzDedicatedWorker,OffMainThreadServiceWorkerScriptFetch"] + "args": ["--enable-features=OffMainThreadDedicatedWorkerScriptFetch,PlzDedicatedWorker"] }, { "prefix": "omt-worker-fetch", "base": "http/tests/origin_trials", - "args": ["--enable-features=OffMainThreadDedicatedWorkerScriptFetch,PlzDedicatedWorker,OffMainThreadServiceWorkerScriptFetch"] + "args": ["--enable-features=OffMainThreadDedicatedWorkerScriptFetch,PlzDedicatedWorker"] }, { "prefix": "omt-worker-fetch", "base": "http/tests/security/cors-rfc1918", - "args": ["--enable-features=OffMainThreadDedicatedWorkerScriptFetch,PlzDedicatedWorker,OffMainThreadServiceWorkerScriptFetch", + "args": ["--enable-features=OffMainThreadDedicatedWorkerScriptFetch,PlzDedicatedWorker", "--enable-blink-features=CorsRFC1918"] }, { "prefix": "omt-worker-fetch", "base": "http/tests/workers", - "args": ["--enable-features=OffMainThreadDedicatedWorkerScriptFetch,PlzDedicatedWorker,OffMainThreadServiceWorkerScriptFetch"] - }, - { - "prefix": "not-omt-sw-fetch", - "base": "external/wpt/content-security-policy/inside-worker", - "args": ["--disable-features=OffMainThreadServiceWorkerScriptFetch"] - }, - { - "prefix": "not-omt-sw-fetch", - "base": "external/wpt/content-security-policy/worker-src", - "args": ["--disable-features=OffMainThreadServiceWorkerScriptFetch"] - }, - { - "prefix": "not-omt-sw-fetch", - "base": "external/wpt/fetch/", - "args": ["--disable-features=OffMainThreadServiceWorkerScriptFetch"] - }, - { - "prefix": "not-omt-sw-fetch", - "base": "external/wpt/html/browsers/offline/appcache/workers/", - "args": ["--disable-features=OffMainThreadServiceWorkerScriptFetch"] - }, - { - "prefix": "not-omt-sw-fetch", - "base": "external/wpt/mixed-content/classic-data-worker-fetch", - "args": ["--disable-features=OffMainThreadServiceWorkerScriptFetch"] - }, - { - "prefix": "not-omt-sw-fetch", - "base": "external/wpt/mixed-content/module-data-worker-import", - "args": ["--disable-features=OffMainThreadServiceWorkerScriptFetch"] - }, - { - "prefix": "not-omt-sw-fetch", - "base": "external/wpt/mixed-content/module-worker-top-level", - "args": ["--disable-features=OffMainThreadServiceWorkerScriptFetch"] - }, - { - "prefix": "not-omt-sw-fetch", - "base": "external/wpt/mixed-content/worker-request", - "args": ["--disable-features=OffMainThreadServiceWorkerScriptFetch"] - }, - { - "prefix": "not-omt-sw-fetch", - "base": "external/wpt/referrer-policy", - "args": ["--disable-features=OffMainThreadServiceWorkerScriptFetch"] - }, - { - "prefix": "not-omt-sw-fetch", - "base": "external/wpt/resource-timing", - "args": ["--disable-features=OffMainThreadServiceWorkerScriptFetch"] - }, - { - "prefix": "not-omt-sw-fetch", - "base": "external/wpt/service-workers", - "args": ["--disable-features=OffMainThreadServiceWorkerScriptFetch"] - }, - { - "prefix": "not-omt-sw-fetch", - "base": "external/wpt/upgrade-insecure-requests", - "args": ["--disable-features=OffMainThreadServiceWorkerScriptFetch"] - }, - { - "prefix": "not-omt-sw-fetch", - "base": "external/wpt/workers", - "args": ["--disable-features=OffMainThreadServiceWorkerScriptFetch"] - }, - { - "prefix": "not-omt-sw-fetch", - "base": "external/wpt/xhr", - "args": ["--disable-features=OffMainThreadServiceWorkerScriptFetch"] - }, - { - "prefix": "not-omt-sw-fetch", - "base": "fast/workers", - "args": ["--disable-features=OffMainThreadServiceWorkerScriptFetch"] - }, - { - "prefix": "not-omt-sw-fetch", - "base": "http/tests/origin_trials", - "args": ["--disable-features=OffMainThreadServiceWorkerScriptFetch"] - }, - { - "prefix": "not-omt-sw-fetch", - "base": "http/tests/security/cors-rfc1918", - "args": ["--disable-features=OffMainThreadServiceWorkerScriptFetch", "--enable-blink-features=CorsRFC1918"] - }, - { - "prefix": "not-omt-sw-fetch", - "base": "http/tests/workers", - "args": ["--disable-features=OffMainThreadServiceWorkerScriptFetch"] + "args": ["--enable-features=OffMainThreadDedicatedWorkerScriptFetch,PlzDedicatedWorker"] }, { "prefix": "webrtc-wpt-plan-b", @@ -1218,14 +1128,12 @@ { "prefix": "cache-storage-parallel", "base": "external/wpt/service-workers", - "args": ["--enable-features=CacheStorageParallelOps<CSPO", - "--force-fieldtrials=CSPO/G1", - "--force-fieldtrial-params=CSPO.G1:max_shared_ops/64"] + "args": ["--disable-features=CacheStorageParallelOps"] }, { "prefix": "cache-storage-sequence", "base": "external/wpt/service-workers", - "args": ["--enable-features=CacheStorageSequence"] + "args": ["--disable-features=CacheStorageSequence"] }, { "prefix": "conditional-appcache-delay",
diff --git a/third_party/blink/web_tests/WPTOverrideExpectations b/third_party/blink/web_tests/WPTOverrideExpectations index 0bbc5dd..97bdfbe 100644 --- a/third_party/blink/web_tests/WPTOverrideExpectations +++ b/third_party/blink/web_tests/WPTOverrideExpectations
@@ -25,6 +25,7 @@ crbug.com/lpz external/wpt/2dcontext/text-styles/2d.text.draw.space.collapse.space.html [ Failure ] crbug.com/lpz external/wpt/2dcontext/text-styles/2d.text.draw.space.collapse.start.html [ Failure ] crbug.com/lpz external/wpt/2dcontext/text-styles/2d.text.measure.width.space.html [ Failure ] +crbug.com/lpz external/wpt/2dcontext/wide-gamut-canvas/canvas-createImageBitmap-e_srgb.html [ Pass Failure ] crbug.com/lpz external/wpt/BackgroundSync/periodicsync.https.window.html [ Failure ] crbug.com/lpz external/wpt/FileAPI/file/File-constructor.html [ Failure ] crbug.com/lpz external/wpt/FileAPI/historical.https.html [ Failure ] @@ -121,6 +122,7 @@ crbug.com/lpz external/wpt/client-hints/sec-ch-ua.https.html [ Failure ] crbug.com/lpz external/wpt/clipboard-apis/async-interfaces.https.html [ Failure ] crbug.com/lpz external/wpt/compat/idlharness.window.html [ Failure ] +crbug.com/lpz external/wpt/contacts/contacts-select.https.window.html [ Failure ] crbug.com/lpz external/wpt/content-security-policy/frame-ancestors/frame-ancestors-nested-cross-in-cross-none-block.html [ Failure ] crbug.com/lpz external/wpt/content-security-policy/frame-ancestors/frame-ancestors-nested-cross-in-cross-self-block.html [ Failure ] crbug.com/lpz external/wpt/content-security-policy/frame-ancestors/frame-ancestors-nested-cross-in-cross-url-block.html [ Failure ] @@ -1120,6 +1122,7 @@ crbug.com/lpz external/wpt/html/semantics/interactive-elements/the-dialog-element/centering.html [ Failure ] crbug.com/lpz external/wpt/html/semantics/interactive-elements/the-dialog-element/dialog-showModal.html [ Failure ] crbug.com/lpz external/wpt/html/semantics/interfaces.html [ Failure ] +crbug.com/lpz external/wpt/html/semantics/links/links-created-by-a-and-area-elements/htmlanchorelement_noopener.html [ Pass Failure ] crbug.com/lpz external/wpt/html/semantics/links/links-created-by-a-and-area-elements/target_blank_implicit_noopener.html [ Failure Timeout ] crbug.com/lpz external/wpt/html/semantics/links/links-created-by-a-and-area-elements/target_blank_implicit_noopener_base.html [ Failure Timeout ] crbug.com/lpz external/wpt/html/semantics/rellist-feature-detection.html [ Failure ] @@ -1460,6 +1463,7 @@ crbug.com/lpz external/wpt/screen-orientation/onchange-event-subframe.html [ Failure ] crbug.com/lpz external/wpt/scroll-animations/constructor.html [ Failure ] crbug.com/lpz external/wpt/scroll-animations/idlharness.window.html [ Failure ] +crbug.com/lpz external/wpt/scroll-behavior-smooth.html [ Failure Timeout ] crbug.com/lpz external/wpt/secure-contexts/basic-dedicated-worker.html [ Failure ] crbug.com/lpz external/wpt/secure-contexts/basic-shared-worker.html [ Failure ] crbug.com/lpz external/wpt/secure-contexts/basic-shared-worker.https.html [ Failure ]
diff --git a/third_party/blink/web_tests/external/WPT_BASE_MANIFEST_6.json b/third_party/blink/web_tests/external/WPT_BASE_MANIFEST_6.json index b5e75e7..199d6921 100644 --- a/third_party/blink/web_tests/external/WPT_BASE_MANIFEST_6.json +++ b/third_party/blink/web_tests/external/WPT_BASE_MANIFEST_6.json
@@ -482972,7 +482972,7 @@ "support" ], "tools/wptrunner/requirements_firefox.txt": [ - "9d7520dd01f29936cc7e232c2e08b1d5d6f6467a", + "78e53e60d94e3267f7f91b0cf6f2f65b6a35fcdc", "support" ], "tools/wptrunner/requirements_ie.txt": [ @@ -486168,7 +486168,7 @@ "support" ], "web-share/META.yml": [ - "e054ccc8ec34058cc749a04cb3f06c0a72368f76", + "d2eccca6f424e93cc463fafc5a3b16e5a7ecc565", "support" ], "web-share/OWNERS": [ @@ -486188,7 +486188,7 @@ "testharness" ], "web-share/idlharness.https.window.js": [ - "cbaf9d72c5c11d9b75cd4a36aa0cf45bc0db35aa", + "1520387caf133dc43c5f036bbf24a99ef73a7f3c", "testharness" ], "web-share/resources/manual-helper.js": [ @@ -488252,7 +488252,7 @@ "support" ], "webdriver/tests/switch_to_window/alerts.py": [ - "e3a3342449912dafafaac1bec7bf90f98b29c44c", + "8824138c2d25c07232847062c4853d73075eb94e", "wdspec" ], "webdriver/tests/switch_to_window/switch.py": [
diff --git a/third_party/blink/web_tests/external/wpt/tools/wptrunner/requirements_firefox.txt b/third_party/blink/web_tests/external/wpt/tools/wptrunner/requirements_firefox.txt index 9d7520dd..78e53e6 100644 --- a/third_party/blink/web_tests/external/wpt/tools/wptrunner/requirements_firefox.txt +++ b/third_party/blink/web_tests/external/wpt/tools/wptrunner/requirements_firefox.txt
@@ -1,8 +1,8 @@ marionette_driver==2.8.0 -mozprofile==2.2.0 +mozprofile==2.3.0 mozprocess==1.0.0 mozcrash==1.1.0 -mozrunner==7.4.0 +mozrunner==7.5.1 mozleak==0.2 mozinstall==2.0.0 mozdownload==1.26.0
diff --git a/third_party/blink/web_tests/external/wpt/webdriver/tests/switch_to_window/alerts.py b/third_party/blink/web_tests/external/wpt/webdriver/tests/switch_to_window/alerts.py index e3a33424..8824138 100644 --- a/third_party/blink/web_tests/external/wpt/webdriver/tests/switch_to_window/alerts.py +++ b/third_party/blink/web_tests/external/wpt/webdriver/tests/switch_to_window/alerts.py
@@ -3,7 +3,6 @@ from webdriver import error from tests.support.asserts import assert_success -from tests.support.inline import inline def switch_to_window(session, handle): @@ -19,13 +18,15 @@ response = switch_to_window(session, new_handle) assert_success(response) - session.url = inline("<script>window.alert('Hello');</script>") + session.execute_script("window.alert('Hello');") assert session.alert.text == "Hello" + response = switch_to_window(session, handle) assert_success(response) with pytest.raises(error.NoSuchAlertException): session.alert.text == "Hello" + response = switch_to_window(session, new_handle) assert_success(response)
diff --git a/third_party/blink/web_tests/fast/canvas/canvas-ImageData-neutered-source-expected.txt b/third_party/blink/web_tests/fast/canvas/canvas-ImageData-detached-source-expected.txt similarity index 91% rename from third_party/blink/web_tests/fast/canvas/canvas-ImageData-neutered-source-expected.txt rename to third_party/blink/web_tests/fast/canvas/canvas-ImageData-detached-source-expected.txt index d5a4934..33f34b63 100644 --- a/third_party/blink/web_tests/fast/canvas/canvas-ImageData-neutered-source-expected.txt +++ b/third_party/blink/web_tests/fast/canvas/canvas-ImageData-detached-source-expected.txt
@@ -1,4 +1,4 @@ -Tests how putImageData and createImageBitmap would react when the source data is neutered +Tests how putImageData and createImageBitmap would react when the source data is detached On success, you will see a series of "PASS" messages, followed by "TEST COMPLETE". @@ -16,7 +16,7 @@ PASS image.data[1] is undefined PASS image.data[2] is undefined PASS image.data[3] is undefined -PASS context.putImageData(image, 0, 0) threw exception InvalidStateError: Failed to execute 'putImageData' on 'CanvasRenderingContext2D': The source data has been neutered.. +PASS context.putImageData(image, 0, 0) threw exception InvalidStateError: Failed to execute 'putImageData' on 'CanvasRenderingContext2D': The source data has been detached.. PASS Promise rejected as expected: InvalidStateError: The source data has been detached. PASS successfullyParsed is true
diff --git a/third_party/blink/web_tests/fast/canvas/canvas-ImageData-neutered-source.html b/third_party/blink/web_tests/fast/canvas/canvas-ImageData-detached-source.html similarity index 96% rename from third_party/blink/web_tests/fast/canvas/canvas-ImageData-neutered-source.html rename to third_party/blink/web_tests/fast/canvas/canvas-ImageData-detached-source.html index aebd4a3..3c8fea3 100644 --- a/third_party/blink/web_tests/fast/canvas/canvas-ImageData-neutered-source.html +++ b/third_party/blink/web_tests/fast/canvas/canvas-ImageData-detached-source.html
@@ -7,7 +7,7 @@ jsTestIsAsync = true; var worker = new Worker('./resources/worker-onmessage-noop.js'); -description("Tests how putImageData and createImageBitmap would react when the source data is neutered"); +description("Tests how putImageData and createImageBitmap would react when the source data is detached"); var imageWidth = 1; var imageHeight = 1; @@ -33,7 +33,7 @@ shouldBe("newImage.data[2]", "0"); shouldBe("newImage.data[3]", "255"); -// transfer the array buffer to the worker so that the source data is now neutered +// transfer the array buffer to the worker so that the source data is now detached worker.postMessage({data: image.data.buffer}, [image.data.buffer]); len = image.data.byteLength;
diff --git a/third_party/blink/web_tests/fast/dom/Window/window-postmessage-args-expected.txt b/third_party/blink/web_tests/fast/dom/Window/window-postmessage-args-expected.txt index ff0790e..7785e3bd 100644 --- a/third_party/blink/web_tests/fast/dom/Window/window-postmessage-args-expected.txt +++ b/third_party/blink/web_tests/fast/dom/Window/window-postmessage-args-expected.txt
@@ -19,10 +19,10 @@ PASS Posting message ('data', [object MessagePort],[object MessagePort]): threw exception DataCloneError: Failed to execute 'postMessage' on 'Window': Port at index 0 is already neutered. PASS Posting message ('[object MessagePort],[object MessagePort]', ): threw exception DataCloneError: Failed to execute 'postMessage' on 'Window': A MessagePort could not be cloned because it was not transferred. PASS Posting message ('[object ArrayBuffer]', [object ArrayBuffer]) did not throw an exception -PASS arrayBuffer neutered -PASS view neutered +PASS arrayBuffer detached +PASS view detached PASS Posting message ('[object ArrayBuffer]', ): threw exception DataCloneError: Failed to execute 'postMessage' on 'Window': An ArrayBuffer is neutered and could not be cloned. -PASS Posting message ('data', [object ArrayBuffer]): threw exception DataCloneError: Failed to execute 'postMessage' on 'Window': ArrayBuffer at index 0 is already neutered. +PASS Posting message ('data', [object ArrayBuffer]): threw exception DataCloneError: Failed to execute 'postMessage' on 'Window': ArrayBuffer at index 0 is already detached. PASS Posting message ('[detached TypedArray]', ): threw exception DataCloneError: Failed to execute 'postMessage' on 'Window': An ArrayBuffer is neutered and could not be cloned. PASS Posting message ('data', [detached TypedArray]): threw exception TypeError: Failed to execute 'postMessage' on 'Window': Value at index 0 does not have a transferable type. PASS Posting message ('data', [object Object]): threw exception TypeError: Failed to execute 'postMessage' on 'Window': Iterator getter is not callable.
diff --git a/third_party/blink/web_tests/fast/dom/Window/window-postmessage-args.html b/third_party/blink/web_tests/fast/dom/Window/window-postmessage-args.html index 20b9aa5..7d121c3c3 100644 --- a/third_party/blink/web_tests/fast/dom/Window/window-postmessage-args.html +++ b/third_party/blink/web_tests/fast/dom/Window/window-postmessage-args.html
@@ -85,14 +85,14 @@ var int8View = new Int8Array(arrayBuffer, 2, 10); tryPostMessageFunction(window.postMessage, arrayBuffer, '*', [arrayBuffer]); if (!(arrayBuffer.byteLength === 0)) - testFailed("arrayBuffer not neutered; byteLength = " + arrayBuffer.byteLength); + testFailed("arrayBuffer not detached; byteLength = " + arrayBuffer.byteLength); else - testPassed("arrayBuffer neutered"); + testPassed("arrayBuffer detached"); if (!(int8View.length == 0)) - testFailed("view was not neutered; length = " + int8View.length); + testFailed("view was not detached; length = " + int8View.length); else - testPassed("view neutered"); + testPassed("view detached"); tryPostMessageFunction(window.postMessage, arrayBuffer, '*', [], true); tryPostMessageFunction(window.postMessage, 'data', '*', [arrayBuffer], true);
diff --git a/third_party/blink/web_tests/http/tests/inspector-protocol/service-worker/periodicsync-event-expected.txt b/third_party/blink/web_tests/http/tests/inspector-protocol/service-worker/periodicsync-event-expected.txt new file mode 100644 index 0000000..c7a9c7b --- /dev/null +++ b/third_party/blink/web_tests/http/tests/inspector-protocol/service-worker/periodicsync-event-expected.txt
@@ -0,0 +1,3 @@ +Tests delivery of a periodicsync event to the service worker. +Got periodicsync event with tag: test-tag-from-devtools +
diff --git a/third_party/blink/web_tests/http/tests/inspector-protocol/service-worker/periodicsync-event.js b/third_party/blink/web_tests/http/tests/inspector-protocol/service-worker/periodicsync-event.js new file mode 100644 index 0000000..b1ac81e --- /dev/null +++ b/third_party/blink/web_tests/http/tests/inspector-protocol/service-worker/periodicsync-event.js
@@ -0,0 +1,26 @@ +(async testRunner => { + const { page, session, dp } = await testRunner.startURL( + 'resources/periodicsync-event-worker.html', + `Tests delivery of a periodicsync event to the service worker.`); + + async function waitForServiceWorkerActivation() { + let versions; + do { + const result = await dp.ServiceWorker.onceWorkerVersionUpdated(); + versions = result.params.versions; + } while (!versions.length || versions[0].status !== "activated"); + return versions[0].registrationId; + } + + const registrationIdPromise = waitForServiceWorkerActivation(); + + await dp.Runtime.enable(); + await dp.ServiceWorker.enable(); + const registrationId = await registrationIdPromise; + + dp.ServiceWorker.dispatchPeriodicSyncEvent({ origin: 'http://127.0.0.1:8000', registrationId: registrationId, tag: 'devtools-test-tag' }); + const tag = await session.evaluateAsync('window.__periodicsyncTagPromise'); + testRunner.log(`Got periodicsync event with tag: ` + tag); + + testRunner.completeTest(); +});
diff --git a/third_party/blink/web_tests/http/tests/inspector-protocol/service-worker/resources/periodicsync-event-worker.html b/third_party/blink/web_tests/http/tests/inspector-protocol/service-worker/resources/periodicsync-event-worker.html new file mode 100644 index 0000000..25ad0329 --- /dev/null +++ b/third_party/blink/web_tests/http/tests/inspector-protocol/service-worker/resources/periodicsync-event-worker.html
@@ -0,0 +1,19 @@ +<!DOCTYPE html> +<html> + +<head> + <title>Test periodicsync event in a serviceworker.</title> + <script> + function installSW() { + navigator.serviceWorker.register('periodicsync-event-worker.js'); + } + + window.__periodicsyncTagPromise = new Promise(fulfill => + navigator.serviceWorker.onmessage = message => fulfill(message.data)); + + </script> +</head> + +<body onload="installSW()"></body> + +</html>
diff --git a/third_party/blink/web_tests/http/tests/inspector-protocol/service-worker/resources/periodicsync-event-worker.js b/third_party/blink/web_tests/http/tests/inspector-protocol/service-worker/resources/periodicsync-event-worker.js new file mode 100644 index 0000000..0c6af7a --- /dev/null +++ b/third_party/blink/web_tests/http/tests/inspector-protocol/service-worker/resources/periodicsync-event-worker.js
@@ -0,0 +1,5 @@ +self.addEventListener('periodicsync', async event => { + const clients = await self.clients.matchAll({ includeUncontrolled: true }); + for (const client of clients) + client.postMessage('test-tag-from-devtools'); +});
diff --git a/third_party/blink/web_tests/virtual/cache-storage-parallel/external/wpt/service-workers/README.txt b/third_party/blink/web_tests/virtual/cache-storage-parallel/external/wpt/service-workers/README.txt index 8e43317..61a3a1c8 100644 --- a/third_party/blink/web_tests/virtual/cache-storage-parallel/external/wpt/service-workers/README.txt +++ b/third_party/blink/web_tests/virtual/cache-storage-parallel/external/wpt/service-workers/README.txt
@@ -1,4 +1,3 @@ This suite runs the ServiceWorker and CacheStorage tests with the -CacheStorageParallelOps feature enabled and set to 64 maximum shared -operations. This makes cache_storage execute read operations in -parallel. +CacheStorageParallelOps feature disabled. This makes cache_storage +execute read operations in sequence.
diff --git a/third_party/blink/web_tests/virtual/cache-storage-sequence/external/wpt/service-workers/README.txt b/third_party/blink/web_tests/virtual/cache-storage-sequence/external/wpt/service-workers/README.txt index 7ad2004b..a63f3fc 100644 --- a/third_party/blink/web_tests/virtual/cache-storage-sequence/external/wpt/service-workers/README.txt +++ b/third_party/blink/web_tests/virtual/cache-storage-sequence/external/wpt/service-workers/README.txt
@@ -1,3 +1,3 @@ This suite runs the ServiceWorker and CacheStorage tests with the -CacheStorageSequence feature enabled. This makes CacheStorage operate off +CacheStorageSequence feature disabled. This makes CacheStorage operate on the IO thread in the browser process.
diff --git a/third_party/blink/web_tests/fast/canvas/canvas-ImageData-neutered-source-expected.txt b/third_party/blink/web_tests/virtual/gpu/fast/canvas/canvas-ImageData-detached-source-expected.txt similarity index 91% copy from third_party/blink/web_tests/fast/canvas/canvas-ImageData-neutered-source-expected.txt copy to third_party/blink/web_tests/virtual/gpu/fast/canvas/canvas-ImageData-detached-source-expected.txt index d5a4934..33f34b63 100644 --- a/third_party/blink/web_tests/fast/canvas/canvas-ImageData-neutered-source-expected.txt +++ b/third_party/blink/web_tests/virtual/gpu/fast/canvas/canvas-ImageData-detached-source-expected.txt
@@ -1,4 +1,4 @@ -Tests how putImageData and createImageBitmap would react when the source data is neutered +Tests how putImageData and createImageBitmap would react when the source data is detached On success, you will see a series of "PASS" messages, followed by "TEST COMPLETE". @@ -16,7 +16,7 @@ PASS image.data[1] is undefined PASS image.data[2] is undefined PASS image.data[3] is undefined -PASS context.putImageData(image, 0, 0) threw exception InvalidStateError: Failed to execute 'putImageData' on 'CanvasRenderingContext2D': The source data has been neutered.. +PASS context.putImageData(image, 0, 0) threw exception InvalidStateError: Failed to execute 'putImageData' on 'CanvasRenderingContext2D': The source data has been detached.. PASS Promise rejected as expected: InvalidStateError: The source data has been detached. PASS successfullyParsed is true
diff --git a/third_party/blink/web_tests/virtual/gpu/fast/canvas/canvas-ImageData-neutered-source-expected.txt b/third_party/blink/web_tests/virtual/gpu/fast/canvas/canvas-ImageData-neutered-source-expected.txt deleted file mode 100644 index d5a4934..0000000 --- a/third_party/blink/web_tests/virtual/gpu/fast/canvas/canvas-ImageData-neutered-source-expected.txt +++ /dev/null
@@ -1,24 +0,0 @@ -Tests how putImageData and createImageBitmap would react when the source data is neutered - -On success, you will see a series of "PASS" messages, followed by "TEST COMPLETE". - -PASS len is 4 -PASS image.data[0] is 255 -PASS image.data[1] is 0 -PASS image.data[2] is 0 -PASS image.data[3] is 255 -PASS newImage.data[0] is 255 -PASS newImage.data[1] is 0 -PASS newImage.data[2] is 0 -PASS newImage.data[3] is 255 -PASS len is 0 -PASS image.data[0] is undefined -PASS image.data[1] is undefined -PASS image.data[2] is undefined -PASS image.data[3] is undefined -PASS context.putImageData(image, 0, 0) threw exception InvalidStateError: Failed to execute 'putImageData' on 'CanvasRenderingContext2D': The source data has been neutered.. -PASS Promise rejected as expected: InvalidStateError: The source data has been detached. -PASS successfullyParsed is true - -TEST COMPLETE -
diff --git a/third_party/blink/web_tests/virtual/not-omt-sw-fetch/README.md b/third_party/blink/web_tests/virtual/not-omt-sw-fetch/README.md deleted file mode 100644 index a00c8fe..0000000 --- a/third_party/blink/web_tests/virtual/not-omt-sw-fetch/README.md +++ /dev/null
@@ -1,4 +0,0 @@ -# virtual/not-omt-sw-fetch - -Fetch toplevel service worker scripts on the main thread. This virtual tests -and `virtual/omt-worker-fetch` contradict each other.
diff --git a/third_party/harfbuzz-ng/BUILD.gn b/third_party/harfbuzz-ng/BUILD.gn index 72013eb1d..88bc9cc 100644 --- a/third_party/harfbuzz-ng/BUILD.gn +++ b/third_party/harfbuzz-ng/BUILD.gn
@@ -99,6 +99,8 @@ "src/src/hb-font.cc", "src/src/hb-font.hh", "src/src/hb-ft.cc", + "src/src/hb-gdi.cc", + "src/src/hb-gdi.h", "src/src/hb-icu.cc", "src/src/hb-map.cc", "src/src/hb-map.hh", @@ -138,6 +140,12 @@ "src/src/hb-ot-math-table.hh", "src/src/hb-ot-math.cc", "src/src/hb-ot-maxp-table.hh", + "src/src/hb-ot-meta-table.hh", + "src/src/hb-ot-meta.cc", + "src/src/hb-ot-meta.h", + "src/src/hb-ot-metrics.cc", + "src/src/hb-ot-metrics.h", + "src/src/hb-ot-metrics.hh", "src/src/hb-ot-name-language-static.hh", "src/src/hb-ot-name-language.hh", "src/src/hb-ot-name-table.hh", @@ -237,6 +245,11 @@ # that is part of HarfBuzz. "HB_NO_UCD", + # TODO(https://crbug.com/992390): Don't use the HarfBuzz metrics + # implementation, as we're retrieving metrics from Skia. Consider using this + # implementation at least for vertical metrics. + "HB_NO_METRICS", + # TODO(https://crbug.com/949962): Remove once this is fixed upstream. "U_DISABLE_VERSION_SUFFIX=0", ]
diff --git a/third_party/harfbuzz-ng/README.chromium b/third_party/harfbuzz-ng/README.chromium index 4dbce93..c3d48d16 100644 --- a/third_party/harfbuzz-ng/README.chromium +++ b/third_party/harfbuzz-ng/README.chromium
@@ -1,9 +1,9 @@ Name: harfbuzz-ng Short Name: harfbuzz-ng URL: http://harfbuzz.org -Version: 2.5.3-60 -Date: 20190708 -Revision: 2e7021da7d1726a37822e6a001b9218f82255bc8 +Version: 2.5.3-155 +Date: 20190809 +Revision: 60485ab0473630c585bb96fcdc14dbe415edf4f2 Security Critical: yes License: MIT License File: src/COPYING
diff --git a/third_party/private-join-and-compute/README.chromium b/third_party/private-join-and-compute/README.chromium new file mode 100644 index 0000000..1db55e3 --- /dev/null +++ b/third_party/private-join-and-compute/README.chromium
@@ -0,0 +1,19 @@ +Name: Private Join and Compute subset +Short Name: private-join-and-compute +URL: https://github.com/google/private-join-and-compute +Version: 0 +Date: Jun 27 2019 +Revision: 375be83109e10b32441483dbd0f1ac493488d197 +License: Apache 2.0 +License File: LICENSE +Security Critical: yes + +Description: +The package contains a communicative cipher. It's used to communicate with the leak detection Google server. + +Local Modifications: +Stripped all the dependencies except for BoringSSL. chromium_patch.h is the only new file. Other modifications are removing the includes, fixing the macroses to those used in Chrome and removing unused functions and classes. The diff files are in order of modifications: +files.diff - the files deleted from the original library. +dependencies.diff - removes all the dependencies on Abseil and other libraries replacing them with Chrome's analogues. +compilation.diff - fixes compilation/static analyzers in Chrome. +fix_nulls.diff - makes the presubmit happy by replacing NULL with nullptr.
diff --git a/third_party/private-join-and-compute/README.md b/third_party/private-join-and-compute/README.md new file mode 100644 index 0000000..f81c6c5d --- /dev/null +++ b/third_party/private-join-and-compute/README.md
@@ -0,0 +1,167 @@ +# Private Join and Compute + +This project contains an implementation of the "Private Join and Compute" +functionality. This functionality allows two users, each holding an input file, +to privately compute the sum of associated values for records that have common +identifiers. + +In more detail, suppose a Server has a file containing the following +identifiers: + +Identifiers | +----------- | +Sam | +Ada | +Ruby | +Brendan | + +And a Client has a file containing the following identifiers, paired with +associated integer values: + +Identifiers | Associated Values +----------- | ----------------- +Ruby | 10 +Ada | 30 +Alexander | 5 +Mika | 35 + +Then the Private Join and Compute functionality would allow the Client to learn +that the input files had *2* identifiers in common, and that the associated +values summed to *40*. It does this *without* revealing which specific +identifiers were in common (Ada and Ruby in the example above), or revealing +anything additional about the other identifiers in the two parties' data set. + +Private Join and Compute is a variant of the well-studied Private Set +Intersection functionality. We sometimes also refer to Private Join and Compute +as Private Intersection-Sum. + +## How to run the protocol + +In order to run Private Join and Compute, you need to install Bazel, if you +don't have it already. +[Follow the instructions for your platform on the Bazel website.](https://docs.bazel.build/versions/master/install.html) + +You also need to install Git, if you don't have it already. +[Follow the instructions for your platform on the Git website.](https://git-scm.com/book/en/v2/Getting-Started-Installing-Git) + +Once you've installed Bazel and Git, open a Terminal and clone the Private Join +and Compute repository into a local folder: + +```shell +git clone https://github.com/google/private-join-and-compute.git +``` + +Navigate into the `private-join-and-compute` folder you just created, and build +the Private Join and Compute library and dependencies using Bazel: + +```bash +cd private-join-and-compute +bazel build :all +``` + +If you get an error, you may need to build with the following flags: + +```bash +bazel build :all --incompatible_disable_deprecated_attr_params=false --incompatible_depset_is_not_iterable=false --incompatible_new_actions_api=false --incompatible_no_support_tools_in_action_inputs=false +``` + +(All the following instructions must be run from inside the +private-join-and-compute folder.) + +Next, generate some dummy data to run the protocol on: + +```shell +bazel-bin/generate_dummy_data --server_data_file=/tmp/dummy_server_data.csv \ +--client_data_file=/tmp/dummy_client_data.csv +``` + +This will create dummy data for the server and client at the specified +locations. You can look at the files in `/tmp/dummy_server_data.csv` and +`/tmp/dummy_client_data.csv` to see the dummy data that was generated. You can +also change the size of the dummy data generated using additional flags. For +example: + +```shell +bazel-bin/generate_dummy_data \ +--server_data_file=/tmp/dummy_server_data.csv \ +--client_data_file=/tmp/dummy_client_data.csv --server_data_size=1000 \ +--client_data_size=1000 --intersection_size=200 --max_associated_value=100 +``` + +Once you've generated dummy data, you can start the server as follows: + +```shell +bazel-bin/server --server_data_file=/tmp/dummy_server_data.csv +``` + +The server will load data from the specified file, and wait for a connection +from the client. + +Once the server is running, you can start a client to connect to the server. +Create a new terminal and navigate to the private-join-and-compute folder. Once +there, run the following command to start the client: + +```shell +bazel-bin/client --client_data_file=/tmp/dummy_client_data.csv +``` + +The client will connect to the server and execute the steps of the protocol +sequentially. At the end of the protocol, the client will output the +Intersection Size (the number of identifiers in common) and the Intersection Sum +(the sum of associated values). If the protocol was successful, both the server +and client will shut down. + +## Caveats + +Several caveats should be carefully considered before using Private Join and +Compute. + +### Security Model + +Our protocol has security against honest-but-curious adversaries. This means +that as long as both participants follow the protocol honestly, neither will +learn more than the size of the intersection and the intersection-sum. However, +if a participant deviates from the protocol, it is possible they could learn +more than the prescribed information. For example, they could learn the specific +identifiers in the intersection. If the underlying data is sensitive, we +recommend performing a careful risk analysis before using Private Join and +Compute, to ensure that neither party has an incentive to deviate from the +protocol. The protocol can also be supplemented with external enforcement such +as code audits to ensure that no party deviates from the protocol. + +### Maliciously Chosen Inputs + +We note that our protocol does not authenticate that parties use "real" input, +nor does it prevent them from arbitrarily changing their input. We suggest +careful analysis of whether any party has an incentive to lie about their +inputs. This risk can also be mitigated by external enforcement such as code +audits. + +### Leakage from the Intersection-Sum. + +While the Private Join and Compute functionality is supposed to reveal only the +intersection-size and intersection-sum, it is possible that the intersection-sum +itself could reveal something about which identifiers were in common. + +For example, if an identifier has a very unique associated integer values, then +it may be easy to detect if that identifier was in the intersection simply by +looking at the intersection-sum. One way this could happen is if one of the +identifiers has a very large associated value compared to all other identifiers. +In that case, if the intersection-sum is large, one could reasonably infer that +that identifier was in the intersection. To mitigate this, we suggest scrubbing +inputs to remove identifiers with "outlier" values. + +Another way that the intersection-sum may leak which identifiers are in the +intersection is if the intersection is too small. This could make it easier to +guess which combination of identifiers could be in the intersection in order to +yield a particular intersection-sum. To mitigate this, one could abort the +protocol if the intersection-size is below a certain threshold, or to add noise +to the output of the protocol. + +(Note that these mitigations are not currently implemented in this open-source +library.) + +## Disclaimers + +This is not an officially supported Google product. The software is provided +as-is without any guarantees or warranties, express or implied.
diff --git a/third_party/private-join-and-compute/patches/compilation.diff b/third_party/private-join-and-compute/patches/compilation.diff new file mode 100644 index 0000000..37cbc20 --- /dev/null +++ b/third_party/private-join-and-compute/patches/compilation.diff
@@ -0,0 +1,162 @@ +diff -ur --strip-trailing-cr /tmp/private-join-and-compute.original/crypto/context.cc third_party/private-join-and-compute/crypto/context.cc +--- /tmp/private-join-and-compute.original/crypto/context.cc 2019-08-06 16:15:39.918264597 +0200 ++++ third_party/private-join-and-compute/crypto/context.cc 2019-08-07 12:42:02.483051443 +0200 +@@ -41,10 +37,6 @@ + one_bn_(CreateBigNum(1)), + two_bn_(CreateBigNum(2)), + three_bn_(CreateBigNum(3)) { +-#if defined(OS_NACL) +- nacl::SeedOpenSSLRand(); +-#endif +- OpenSSLInit(); + CHECK(RAND_status()) << "OpenSSL PRNG is not properly seeded."; + HMAC_CTX_init(&hmac_ctx_); + } +@@ -127,7 +119,7 @@ + + BigNum Context::PRF(const std::string& key, const std::string& data, + const BigNum& max_value) { +- CHECK_GE(key.size() * 8, 80); ++ CHECK_GE(key.size() * 8, 80u); + CHECK_LE(max_value.BitLength(), 512) + << "The requested output length is not supported. The maximum " + "supported output length is 512. The requested output length is " +diff -ur --strip-trailing-cr /tmp/private-join-and-compute.original/crypto/ec_commutative_cipher.cc third_party/private-join-and-compute/crypto/ec_commutative_cipher.cc +--- /tmp/private-join-and-compute.original/crypto/ec_commutative_cipher.cc 2019-08-07 14:21:57.192714845 +0200 ++++ third_party/private-join-and-compute/crypto/ec_commutative_cipher.cc 2019-08-07 12:42:02.483051443 +0200 +@@ -93,25 +93,6 @@ + return point.Mul(private_key_); + } + +-StatusOr<std::pair<std::string, std::string>> +-ECCommutativeCipher::ReEncryptElGamalCiphertext( +- const std::pair<std::string, std::string>& elgamal_ciphertext) const { +- ASSIGN_OR_RETURN(ECPoint u, group_.CreateECPoint(elgamal_ciphertext.first)); +- ASSIGN_OR_RETURN(ECPoint e, group_.CreateECPoint(elgamal_ciphertext.second)); +- +- elgamal::Ciphertext decoded_ciphertext = {std::move(u), std::move(e)}; +- +- ASSIGN_OR_RETURN(elgamal::Ciphertext reencrypted_ciphertext, +- elgamal::Exp(decoded_ciphertext, private_key_)); +- +- ASSIGN_OR_RETURN(std::string serialized_u, +- reencrypted_ciphertext.u.ToBytesCompressed()); +- ASSIGN_OR_RETURN(std::string serialized_e, +- reencrypted_ciphertext.e.ToBytesCompressed()); +- +- return std::make_pair(std::move(serialized_u), std::move(serialized_e)); +-} +- + StatusOr<std::string> ECCommutativeCipher::Decrypt( + const std::string& ciphertext) const { + ASSIGN_OR_RETURN(ECPoint point, group_.CreateECPoint(ciphertext)); +diff -ur --strip-trailing-cr /tmp/private-join-and-compute.original/crypto/ec_commutative_cipher.h third_party/private-join-and-compute/crypto/ec_commutative_cipher.h +--- /tmp/private-join-and-compute.original/crypto/ec_commutative_cipher.h 2019-08-07 14:21:57.192714845 +0200 ++++ third_party/private-join-and-compute/crypto/ec_commutative_cipher.h 2019-08-07 12:42:02.483051443 +0200 +@@ -139,16 +139,6 @@ + ::private_join_and_compute::StatusOr<std::string> ReEncrypt( + const std::string& ciphertext) const; + +- // Encrypts an ElGamal ciphertext with the private key. +- // +- // Returns an INVALID_ARGUMENT error code if the input is not a valid encoding +- // of an ElGamal ciphertext on this curve as defined in ANSI X9.62 ECDSA. +- // +- // The result is another ElGamal ciphertext, encoded in compressed form. +- ::private_join_and_compute::StatusOr<std::pair<std::string, std::string>> +- ReEncryptElGamalCiphertext( +- const std::pair<std::string, std::string>& elgamal_ciphertext) const; +- + // Decrypts an encoded point with the private key. + // + // Returns an INVALID_ARGUMENT error code if the input is not a valid encoding +diff -ur --strip-trailing-cr /tmp/private-join-and-compute.original/util/status.cc third_party/private-join-and-compute/util/status.cc +--- /tmp/private-join-and-compute.original/util/status.cc 2019-08-06 16:15:39.922264595 +0200 ++++ third_party/private-join-and-compute/util/status.cc 2019-08-07 12:42:02.483051443 +0200 +@@ -20,26 +20,6 @@ + + namespace private_join_and_compute { + +-namespace { +- +-const Status& GetOk() { +- static const Status* status = new Status(); +- return *status; +-} +- +-const Status& GetCancelled() { +- static const Status* status = +- new Status(private_join_and_compute::StatusCode::kCancelled, ""); +- return *status; +-} +- +-const Status& GetUnknown() { +- static const Status* status = new Status(private_join_and_compute::StatusCode::kUnknown, ""); +- return *status; +-} +- +-} // namespace +- + Status::Status() : code_(private_join_and_compute::StatusCode::kOk), message_("") {} + + Status::Status(private_join_and_compute::StatusCode error, std::string error_message) +@@ -58,10 +38,6 @@ + return *this; + } + +-const Status& Status::OK = GetOk(); +-const Status& Status::CANCELLED = GetCancelled(); +-const Status& Status::UNKNOWN = GetUnknown(); +- + std::string Status::ToString() const { + if (code_ == private_join_and_compute::StatusCode::kOk) { + return "OK"; +diff -ur --strip-trailing-cr /tmp/private-join-and-compute.original/util/status.h third_party/private-join-and-compute/util/status.h +--- /tmp/private-join-and-compute.original/util/status.h 2019-08-06 16:15:39.922264595 +0200 ++++ third_party/private-join-and-compute/util/status.h 2019-08-07 12:42:02.483051443 +0200 +@@ -54,9 +54,12 @@ + Status& operator=(const Status& other); + + // Some pre-defined Status objects +- static const Status& OK; // NOLINT // Identical to 0-arg constructor +- static const Status& CANCELLED; // NOLINT +- static const Status& UNKNOWN; // NOLINT ++ static Status OK() { ++ return Status(); ++ } ++ static Status UNKNOWN() { ++ return Status(private_join_and_compute::StatusCode::kUnknown, ""); ++ } + + // Accessors + bool ok() const { return code_ == private_join_and_compute::StatusCode::kOk; } +diff -ur --strip-trailing-cr /tmp/private-join-and-compute.original/util/statusor.h third_party/private-join-and-compute/util/statusor.h +--- /tmp/private-join-and-compute.original/util/statusor.h 2019-08-06 16:15:39.922264595 +0200 ++++ third_party/private-join-and-compute/util/statusor.h 2019-08-07 12:42:02.939051124 +0200 +@@ -177,7 +177,7 @@ + } // namespace internal + + template <typename T> +-inline StatusOr<T>::StatusOr() : status_(Status::UNKNOWN), value_(nullptr) {} ++inline StatusOr<T>::StatusOr() : status_(Status::UNKNOWN()), value_(nullptr) {} + + template <typename T> + inline StatusOr<T>::StatusOr(const Status& status) +@@ -189,7 +189,7 @@ + + template <typename T> + inline StatusOr<T>::StatusOr(const T& value) +- : status_(Status::OK), value_(new T(value)) { ++ : status_(Status::OK()), value_(new T(value)) { + if (internal::StatusOrHelper::Specialize<T>::IsValueNull(*value_)) { + status_ = internal::StatusOrHelper::HandleNullObjectCtorArg(); + } +@@ -209,7 +209,7 @@ + + template <typename T> + inline StatusOr<T>::StatusOr(T&& value) +- : status_(Status::OK), value_(new T(std::forward<T>(value))) { ++ : status_(Status::OK()), value_(new T(std::forward<T>(value))) { + if (internal::StatusOrHelper::Specialize<T>::IsValueNull(*value_)) { + status_ = internal::StatusOrHelper::HandleNullObjectCtorArg(); + }
diff --git a/third_party/private-join-and-compute/patches/dependencies.diff b/third_party/private-join-and-compute/patches/dependencies.diff new file mode 100644 index 0000000..5de6f3db --- /dev/null +++ b/third_party/private-join-and-compute/patches/dependencies.diff
@@ -0,0 +1,492 @@ +Only in /tmp/private-join-and-compute.original: BUILD +Only in third_party/private-join-and-compute/src: BUILD.gn +Only in third_party/private-join-and-compute/src: chromium_patch.h +Only in /tmp/private-join-and-compute.original: client.cc +Only in /tmp/private-join-and-compute.original: client_impl.cc +Only in /tmp/private-join-and-compute.original: client_impl.h +diff -ur --strip-trailing-cr /tmp/private-join-and-compute.original/crypto/big_num.cc third_party/private-join-and-compute/src/crypto/big_num.cc +--- /tmp/private-join-and-compute.original/crypto/big_num.cc 2019-08-07 14:34:50.936156293 +0200 ++++ third_party/private-join-and-compute/src/crypto/big_num.cc 2019-08-08 19:07:01.405866572 +0200 +@@ -13,16 +13,15 @@ + * limitations under the License. + */ + +-#include "crypto/big_num.h" ++#include "third_party/private-join-and-compute/src/crypto/big_num.h" + + #include <cmath> + #include <vector> + +-#include "gflags/gflags.h" +-#include "glog/logging.h" +-#include "crypto/context.h" +-#include "crypto/openssl.inc" +-#include "util/status.inc" ++#include "third_party/private-join-and-compute/src/chromium_patch.h" ++#include "third_party/private-join-and-compute/src/crypto/context.h" ++#include "third_party/private-join-and-compute/src/crypto/openssl.inc" ++#include "third_party/private-join-and-compute/src/util/status.inc" + + namespace private_join_and_compute { + +diff -ur --strip-trailing-cr /tmp/private-join-and-compute.original/crypto/big_num.h third_party/private-join-and-compute/src/crypto/big_num.h +--- /tmp/private-join-and-compute.original/crypto/big_num.h 2019-08-07 14:34:50.936156293 +0200 ++++ third_party/private-join-and-compute/src/crypto/big_num.h 2019-08-08 19:07:13.709859666 +0200 +@@ -21,9 +21,8 @@ + #include <memory> + #include <string> + +-#include "gflags/gflags_declare.h" +-#include "crypto/openssl.inc" +-#include "util/status.inc" ++#include "third_party/private-join-and-compute/src/crypto/openssl.inc" ++#include "third_party/private-join-and-compute/src/util/status.inc" + + namespace private_join_and_compute { + +Only in /tmp/private-join-and-compute.original/crypto: BUILD +diff -ur --strip-trailing-cr /tmp/private-join-and-compute.original/crypto/context.cc third_party/private-join-and-compute/src/crypto/context.cc +--- /tmp/private-join-and-compute.original/crypto/context.cc 2019-08-07 14:34:50.936156293 +0200 ++++ third_party/private-join-and-compute/src/crypto/context.cc 2019-08-08 19:07:22.945854482 +0200 +@@ -13,18 +13,14 @@ + * limitations under the License. + */ + +-#include "crypto/context.h" ++#include "third_party/private-join-and-compute/src/crypto/context.h" + + #include <math.h> + + #include <algorithm> + #include <cmath> + +-#include "glog/logging.h" +-#include "crypto/openssl_init.h" +-#if defined(OS_NACL) +-#include "privacy/blinders/cpp/nacl_context.h" +-#endif ++#include "third_party/private-join-and-compute/src/chromium_patch.h" + + namespace private_join_and_compute { + +diff -ur --strip-trailing-cr /tmp/private-join-and-compute.original/crypto/context.h third_party/private-join-and-compute/src/crypto/context.h +--- /tmp/private-join-and-compute.original/crypto/context.h 2019-08-07 14:34:50.936156293 +0200 ++++ third_party/private-join-and-compute/src/crypto/context.h 2019-08-08 19:08:23.005820766 +0200 +@@ -21,9 +21,9 @@ + #include <memory> + #include <string> + +-#include "glog/logging.h" +-#include "crypto/big_num.h" +-#include "crypto/openssl.inc" ++#include "third_party/private-join-and-compute/src/chromium_patch.h" ++#include "third_party/private-join-and-compute/src/crypto/big_num.h" ++#include "third_party/private-join-and-compute/src/crypto/openssl.inc" + + #define CRYPTO_CHECK(expr) CHECK(expr) << OpenSSLErrorString(); + +diff -ur --strip-trailing-cr /tmp/private-join-and-compute.original/crypto/ec_commutative_cipher.cc third_party/private-join-and-compute/src/crypto/ec_commutative_cipher.cc +--- /tmp/private-join-and-compute.original/crypto/ec_commutative_cipher.cc 2019-08-07 14:34:50.936156293 +0200 ++++ third_party/private-join-and-compute/src/crypto/ec_commutative_cipher.cc 2019-08-08 19:05:21.197922804 +0200 +@@ -13,12 +13,11 @@ + * limitations under the License. + */ + +-#include "crypto/ec_commutative_cipher.h" ++#include "third_party/private-join-and-compute/src/crypto/ec_commutative_cipher.h" + + #include <utility> + +-#include "crypto/elgamal.h" +-#include "util/status.inc" ++#include "third_party/private-join-and-compute/src/util/status.inc" + + namespace private_join_and_compute { + +diff -ur --strip-trailing-cr /tmp/private-join-and-compute.original/crypto/ec_commutative_cipher.h third_party/private-join-and-compute/src/crypto/ec_commutative_cipher.h +--- /tmp/private-join-and-compute.original/crypto/ec_commutative_cipher.h 2019-08-07 14:34:50.936156293 +0200 ++++ third_party/private-join-and-compute/src/crypto/ec_commutative_cipher.h 2019-08-08 19:09:01.177798754 +0200 +@@ -19,12 +19,11 @@ + #include <memory> + #include <string> + +-#include "absl/base/port.h" +-#include "crypto/big_num.h" +-#include "crypto/context.h" +-#include "crypto/ec_group.h" +-#include "crypto/ec_point.h" +-#include "util/status.inc" ++#include "third_party/private-join-and-compute/src/crypto/big_num.h" ++#include "third_party/private-join-and-compute/src/crypto/context.h" ++#include "third_party/private-join-and-compute/src/crypto/ec_group.h" ++#include "third_party/private-join-and-compute/src/crypto/ec_point.h" ++#include "third_party/private-join-and-compute/src/util/status.inc" + + namespace private_join_and_compute { + +diff -ur --strip-trailing-cr /tmp/private-join-and-compute.original/crypto/ec_group.cc third_party/private-join-and-compute/src/crypto/ec_group.cc +--- /tmp/private-join-and-compute.original/crypto/ec_group.cc 2019-08-07 14:34:50.936156293 +0200 ++++ third_party/private-join-and-compute/src/crypto/ec_group.cc 2019-08-08 19:09:34.065779733 +0200 +@@ -13,16 +13,14 @@ + * limitations under the License. + */ + +-#include "crypto/ec_group.h" ++#include "third_party/private-join-and-compute/src/crypto/ec_group.h" + + #include <algorithm> + #include <utility> + +-#include "glog/logging.h" +-#include "crypto/ec_point.h" +-#include "crypto/openssl.inc" +-#include "util/status.inc" +-#include "absl/strings/str_cat.h" ++#include "third_party/private-join-and-compute/src/crypto/ec_point.h" ++#include "third_party/private-join-and-compute/src/crypto/openssl.inc" ++#include "third_party/private-join-and-compute/src/util/status.inc" + + namespace private_join_and_compute { + +@@ -35,8 +33,8 @@ + // If this fails, this is usually due to an invalid curve id. + if (ec_group_ptr == nullptr) { + return InvalidArgumentError( +- absl::StrCat("ECGroup::CreateGroup() - Could not create group. ", +- OpenSSLErrorString())); ++ "ECGroup::CreateGroup() - Could not create group. " + ++ OpenSSLErrorString()); + } + return ECGroup::ECGroupPtr(ec_group_ptr); + } +@@ -47,13 +45,13 @@ + BIGNUM* bn = BN_new(); + if (bn == nullptr) { + return InternalError( +- absl::StrCat("ECGroup::CreateOrder - Could not create BIGNUM. ", +- OpenSSLErrorString())); ++ "ECGroup::CreateOrder - Could not create BIGNUM. " + ++ OpenSSLErrorString()); + } + BigNum::BignumPtr order = BigNum::BignumPtr(bn); + if (EC_GROUP_get_order(group, order.get(), context->GetBnCtx()) != 1) { +- return InternalError(absl::StrCat( +- "ECGroup::CreateOrder - Could not get order. ", OpenSSLErrorString())); ++ return InternalError( ++ "ECGroup::CreateOrder - Could not get order. " + OpenSSLErrorString()); + } + return context->CreateBigNum(std::move(order)); + } +@@ -63,14 +61,14 @@ + BIGNUM* bn = BN_new(); + if (bn == nullptr) { + return InternalError( +- absl::StrCat("ECGroup::CreateCofactor - Could not create BIGNUM. ", +- OpenSSLErrorString())); ++ "ECGroup::CreateCofactor - Could not create BIGNUM. " + ++ OpenSSLErrorString()); + } + BigNum::BignumPtr cofactor = BigNum::BignumPtr(bn); + if (EC_GROUP_get_cofactor(group, cofactor.get(), context->GetBnCtx()) != 1) { + return InternalError( +- absl::StrCat("ECGroup::CreateCofactor - Could not get cofactor. ", +- OpenSSLErrorString())); ++ "ECGroup::CreateCofactor - Could not get cofactor. " + ++ OpenSSLErrorString()); + } + return context->CreateBigNum(std::move(cofactor)); + } +@@ -84,8 +82,8 @@ + BIGNUM* bn3 = BN_new(); + if (bn1 == nullptr || bn2 == nullptr || bn3 == nullptr) { + return InternalError( +- absl::StrCat("ECGroup::CreateCurveParams - Could not create BIGNUM. ", +- OpenSSLErrorString())); ++ "ECGroup::CreateCurveParams - Could not create BIGNUM. " + ++ OpenSSLErrorString()); + } + BigNum::BignumPtr p = BigNum::BignumPtr(bn1); + BigNum::BignumPtr a = BigNum::BignumPtr(bn2); +@@ -93,13 +91,13 @@ + if (EC_GROUP_get_curve_GFp(group, p.get(), a.get(), b.get(), + context->GetBnCtx()) != 1) { + return InternalError( +- absl::StrCat("ECGroup::CreateCurveParams - Could not get params. ", +- OpenSSLErrorString())); ++ "ECGroup::CreateCurveParams - Could not get params. " + ++ OpenSSLErrorString()); + } + BigNum p_bn = context->CreateBigNum(std::move(p)); + if (!p_bn.IsPrime()) { +- return InternalError(absl::StrCat( +- "ECGroup::CreateCurveParams - p is not prime. ", OpenSSLErrorString())); ++ return InternalError( ++ "ECGroup::CreateCurveParams - p is not prime. " + OpenSSLErrorString()); + } + return ECGroup::CurveParams{std::move(p_bn), + context->CreateBigNum(std::move(a)), +@@ -244,8 +242,7 @@ + reinterpret_cast<const unsigned char*>(bytes.data()), + bytes.size(), context_->GetBnCtx()) != 1) { + return InvalidArgumentError( +- absl::StrCat("ECGroup::CreateECPoint(string) - Could not decode point.", +- "\n", OpenSSLErrorString())); ++ "ECGroup::CreateECPoint(string) - Could not decode point.\n" + OpenSSLErrorString()); + } + + ECPoint ec_point(group_.get(), context_->GetBnCtx(), std::move(point)); +diff -ur --strip-trailing-cr /tmp/private-join-and-compute.original/crypto/ec_group.h third_party/private-join-and-compute/src/crypto/ec_group.h +--- /tmp/private-join-and-compute.original/crypto/ec_group.h 2019-08-06 16:15:39.918264597 +0200 ++++ third_party/private-join-and-compute/src/crypto/ec_group.h 2019-08-08 19:09:43.601774218 +0200 +@@ -19,10 +19,10 @@ + #include <memory> + #include <string> + +-#include "crypto/big_num.h" +-#include "crypto/context.h" +-#include "crypto/openssl.inc" +-#include "util/status.inc" ++#include "third_party/private-join-and-compute/src/crypto/big_num.h" ++#include "third_party/private-join-and-compute/src/crypto/context.h" ++#include "third_party/private-join-and-compute/src/crypto/openssl.inc" ++#include "third_party/private-join-and-compute/src/util/status.inc" + + namespace private_join_and_compute { + +diff -ur --strip-trailing-cr /tmp/private-join-and-compute.original/crypto/ec_point.cc third_party/private-join-and-compute/src/crypto/ec_point.cc +--- /tmp/private-join-and-compute.original/crypto/ec_point.cc 2019-08-07 14:34:50.940156290 +0200 ++++ third_party/private-join-and-compute/src/crypto/ec_point.cc 2019-08-08 19:10:00.545764419 +0200 +@@ -13,16 +13,15 @@ + * limitations under the License. + */ + +-#include "crypto/ec_point.h" ++#include "third_party/private-join-and-compute/src/crypto/ec_point.h" + + #include <vector> + +-#include "glog/logging.h" +-#include "crypto/big_num.h" +-#include "crypto/context.h" +-#include "crypto/openssl.inc" +-#include "util/status.inc" +-#include "absl/strings/str_cat.h" ++#include "third_party/private-join-and-compute/src/chromium_patch.h" ++#include "third_party/private-join-and-compute/src/crypto/big_num.h" ++#include "third_party/private-join-and-compute/src/crypto/context.h" ++#include "third_party/private-join-and-compute/src/crypto/openssl.inc" ++#include "third_party/private-join-and-compute/src/util/status.inc" + + namespace private_join_and_compute { + +@@ -51,7 +50,7 @@ + if (0 == EC_POINT_point2oct(group_, point_.get(), POINT_CONVERSION_COMPRESSED, + bytes.data(), length, bn_ctx_)) { + return InternalError( +- absl::StrCat("EC_POINT_point2oct failed:", OpenSSLErrorString())); ++ "EC_POINT_point2oct failed:" + OpenSSLErrorString()); + } + return std::string(reinterpret_cast<char*>(bytes.data()), bytes.size()); + } +@@ -64,7 +63,7 @@ + POINT_CONVERSION_UNCOMPRESSED, bytes.data(), + length, bn_ctx_)) { + return InternalError( +- absl::StrCat("EC_POINT_point2oct failed:", OpenSSLErrorString())); ++ "EC_POINT_point2oct failed:" + OpenSSLErrorString()); + } + return std::string(reinterpret_cast<char*>(bytes.data()), bytes.size()); + } +@@ -74,7 +73,7 @@ + if (1 != EC_POINT_mul(group_, r.point_.get(), nullptr, point_.get(), + scalar.GetConstBignumPtr(), bn_ctx_)) { + return InternalError( +- absl::StrCat("EC_POINT_mul failed:", OpenSSLErrorString())); ++ "EC_POINT_mul failed:" + OpenSSLErrorString()); + } + return std::move(r); + } +@@ -84,7 +83,7 @@ + if (1 != EC_POINT_add(group_, r.point_.get(), point_.get(), + point.point_.get(), bn_ctx_)) { + return InternalError( +- absl::StrCat("EC_POINT_add failed:", OpenSSLErrorString())); ++ "EC_POINT_add failed:" + OpenSSLErrorString()); + } + return std::move(r); + } +@@ -93,7 +92,7 @@ + ECPoint r = ECPoint(group_, bn_ctx_); + if (1 != EC_POINT_copy(r.point_.get(), point_.get())) { + return InternalError( +- absl::StrCat("EC_POINT_copy failed:", OpenSSLErrorString())); ++ "EC_POINT_copy failed:" + OpenSSLErrorString()); + } + return std::move(r); + } +@@ -104,7 +103,7 @@ + // Invert the copy in-place. + if (1 != EC_POINT_invert(group_, inv.point_.get(), bn_ctx_)) { + return InternalError( +- absl::StrCat("EC_POINT_invert failed:", OpenSSLErrorString())); ++ "EC_POINT_invert failed:" + OpenSSLErrorString()); + } + return std::move(inv); + } +diff -ur --strip-trailing-cr /tmp/private-join-and-compute.original/crypto/ec_point.h third_party/private-join-and-compute/src/crypto/ec_point.h +--- /tmp/private-join-and-compute.original/crypto/ec_point.h 2019-08-06 16:15:39.918264597 +0200 ++++ third_party/private-join-and-compute/src/crypto/ec_point.h 2019-08-08 19:10:12.805757330 +0200 +@@ -19,8 +19,8 @@ + #include <memory> + #include <string> + +-#include "crypto/openssl.inc" +-#include "util/status.inc" ++#include "third_party/private-join-and-compute/src/crypto/openssl.inc" ++#include "third_party/private-join-and-compute/src/util/status.inc" + + namespace private_join_and_compute { + +Only in /tmp/private-join-and-compute.original/crypto: elgamal.cc +Only in /tmp/private-join-and-compute.original/crypto: elgamal.h +Only in /tmp/private-join-and-compute.original/crypto: fixed_base_exp.cc +Only in /tmp/private-join-and-compute.original/crypto: fixed_base_exp.h +Only in /tmp/private-join-and-compute.original/crypto: mont_mul.cc +Only in /tmp/private-join-and-compute.original/crypto: mont_mul.h +Only in /tmp/private-join-and-compute.original/crypto: openssl_init.cc +Only in /tmp/private-join-and-compute.original/crypto: openssl_init.h +Only in /tmp/private-join-and-compute.original/crypto: paillier.cc +Only in /tmp/private-join-and-compute.original/crypto: paillier.h +Only in /tmp/private-join-and-compute.original/crypto: two_modulus_crt.cc +Only in /tmp/private-join-and-compute.original/crypto: two_modulus_crt.h +Only in /tmp/private-join-and-compute.original: data_util.cc +Only in /tmp/private-join-and-compute.original: data_util.h +Only in third_party/private-join-and-compute/src: DEPS +Only in /tmp/private-join-and-compute.original: generate_dummy_data.cc +Only in /tmp/private-join-and-compute.original: .git +Only in /tmp/private-join-and-compute.original: glog_files +Only in /tmp/private-join-and-compute.original: match.proto +Only in /tmp/private-join-and-compute.original: message_sink.h +Only in third_party/private-join-and-compute/src: OWNERS +Only in /tmp/private-join-and-compute.original: private_intersection_sum.proto +Only in /tmp/private-join-and-compute.original: private_join_and_compute.proto +Only in /tmp/private-join-and-compute.original: private_join_and_compute_rpc_impl.cc +Only in /tmp/private-join-and-compute.original: private_join_and_compute_rpc_impl.h +Only in /tmp/private-join-and-compute.original: protocol_client.h +Only in /tmp/private-join-and-compute.original: protocol_server.h +Only in /tmp/private-join-and-compute.original: README.md +Only in /tmp/private-join-and-compute.original: server.cc +Only in /tmp/private-join-and-compute.original: server_impl.cc +Only in /tmp/private-join-and-compute.original: server_impl.h +Only in /tmp/private-join-and-compute.original/util: BUILD +diff -ur --strip-trailing-cr /tmp/private-join-and-compute.original/util/canonical_errors.cc third_party/private-join-and-compute/src/util/canonical_errors.cc +--- /tmp/private-join-and-compute.original/util/canonical_errors.cc 2019-08-06 16:15:39.922264595 +0200 ++++ third_party/private-join-and-compute/src/util/canonical_errors.cc 2019-08-08 19:20:26.173402991 +0200 +@@ -13,11 +13,11 @@ + * limitations under the License. + */ + +-#include "util/canonical_errors.h" ++#include "third_party/private-join-and-compute/src/util/canonical_errors.h" + + #include <string> + +-#include "util/status.h" ++#include "third_party/private-join-and-compute/src/util/status.h" + + namespace private_join_and_compute { + +diff -ur --strip-trailing-cr /tmp/private-join-and-compute.original/util/canonical_errors.h third_party/private-join-and-compute/src/util/canonical_errors.h +--- /tmp/private-join-and-compute.original/util/canonical_errors.h 2019-08-06 16:15:39.922264595 +0200 ++++ third_party/private-join-and-compute/src/util/canonical_errors.h 2019-08-08 19:20:19.329406941 +0200 +@@ -18,7 +18,7 @@ + + #include <string> + +-#include "util/status.h" ++#include "third_party/private-join-and-compute/src/util/status.h" + + namespace private_join_and_compute { + +diff -ur --strip-trailing-cr /tmp/private-join-and-compute.original/util/status.cc third_party/private-join-and-compute/src/util/status.cc +--- /tmp/private-join-and-compute.original/util/status.cc 2019-08-07 14:34:50.940156290 +0200 ++++ third_party/private-join-and-compute/src/util/status.cc 2019-08-08 19:20:32.405399394 +0200 +@@ -13,7 +13,7 @@ + * limitations under the License. + */ + +-#include "util/status.h" ++#include "third_party/private-join-and-compute/src/util/status.h" + + #include <sstream> + #include <utility> +diff -ur --strip-trailing-cr /tmp/private-join-and-compute.original/util/status.inc third_party/private-join-and-compute/src/util/status.inc +--- /tmp/private-join-and-compute.original/util/status.inc 2019-08-06 16:15:39.922264595 +0200 ++++ third_party/private-join-and-compute/src/util/status.inc 2019-08-08 19:21:07.805378963 +0200 +@@ -13,7 +13,7 @@ + * limitations under the License. + */ + +-#include "util/canonical_errors.h" +-#include "util/status.h" +-#include "util/statusor.h" +-#include "util/status_macros.h" ++#include "third_party/private-join-and-compute/src/util/canonical_errors.h" ++#include "third_party/private-join-and-compute/src/util/status.h" ++#include "third_party/private-join-and-compute/src/util/statusor.h" ++#include "third_party/private-join-and-compute/src/util/status_macros.h" +diff -ur --strip-trailing-cr /tmp/private-join-and-compute.original/util/status_macros.h third_party/private-join-and-compute/src/util/status_macros.h +--- /tmp/private-join-and-compute.original/util/status_macros.h 2019-08-07 14:34:50.940156290 +0200 ++++ third_party/private-join-and-compute/src/util/status_macros.h 2019-08-08 19:25:03.901242758 +0200 +@@ -16,9 +16,9 @@ + #ifndef UTIL_STATUS_MACROS_H_ + #define UTIL_STATUS_MACROS_H_ + +-#include "absl/base/port.h" +-#include "util/status.h" +-#include "util/statusor.h" ++#include "third_party/private-join-and-compute/src/chromium_patch.h" ++#include "third_party/private-join-and-compute/src/util/status.h" ++#include "third_party/private-join-and-compute/src/util/statusor.h" + + // Helper macro that checks if the right hand side (rexpression) evaluates to a + // StatusOr with Status OK, and if so assigns the value to the value on the left +@@ -32,7 +32,7 @@ + // Internal helper. + #define PRIVACY_BLINDERS_ASSIGN_OR_RETURN_IMPL_(statusor, lhs, rexpr) \ + auto statusor = (rexpr); \ +- if (ABSL_PREDICT_FALSE(!statusor.ok())) { \ ++ if (UNLIKELY(!statusor.ok())) { \ + return std::move(statusor).status(); \ + } \ + lhs = std::move(statusor).ValueOrDie() +diff -ur --strip-trailing-cr /tmp/private-join-and-compute.original/util/statusor.cc third_party/private-join-and-compute/src/util/statusor.cc +--- /tmp/private-join-and-compute.original/util/statusor.cc 2019-08-07 14:34:50.940156290 +0200 ++++ third_party/private-join-and-compute/src/util/statusor.cc 2019-08-08 19:25:59.309210530 +0200 +@@ -13,10 +13,10 @@ + * limitations under the License. + */ + +-#include "util/statusor.h" ++#include "third_party/private-join-and-compute/src/util/statusor.h" + +-#include "glog/logging.h" +-#include "util/status.h" ++#include "third_party/private-join-and-compute/src/chromium_patch.h" ++#include "third_party/private-join-and-compute/src/util/status.h" + + namespace private_join_and_compute { + namespace internal { +diff -ur --strip-trailing-cr /tmp/private-join-and-compute.original/util/statusor.h third_party/private-join-and-compute/src/util/statusor.h +--- /tmp/private-join-and-compute.original/util/statusor.h 2019-08-07 14:34:50.940156290 +0200 ++++ third_party/private-join-and-compute/src/util/statusor.h 2019-08-08 19:20:59.625383684 +0200 +@@ -73,7 +73,7 @@ + #include <new> + #include <utility> + +-#include "util/status.h" // IWYU pragma: export // for Status ++#include "third_party/private-join-and-compute/src/util/status.h" // IWYU pragma: export // for Status + + namespace private_join_and_compute { + +Only in /tmp/private-join-and-compute.original: WORKSPACE
diff --git a/third_party/private-join-and-compute/patches/files.diff b/third_party/private-join-and-compute/patches/files.diff new file mode 100644 index 0000000..4bdfa60 --- /dev/null +++ b/third_party/private-join-and-compute/patches/files.diff
@@ -0,0 +1,53 @@ +Only in /tmp/private-join-and-compute.original: BUILD +Only in third_party/private-join-and-compute: BUILD.gn +Only in third_party/private-join-and-compute: chromium_patch.h +Only in /tmp/private-join-and-compute.original: client.cc +Only in /tmp/private-join-and-compute.original: client_impl.cc +Only in /tmp/private-join-and-compute.original: client_impl.h +Files /tmp/private-join-and-compute.original/crypto/big_num.cc and third_party/private-join-and-compute/crypto/big_num.cc differ +Files /tmp/private-join-and-compute.original/crypto/big_num.h and third_party/private-join-and-compute/crypto/big_num.h differ +Only in /tmp/private-join-and-compute.original/crypto: BUILD +Files /tmp/private-join-and-compute.original/crypto/context.cc and third_party/private-join-and-compute/crypto/context.cc differ +Files /tmp/private-join-and-compute.original/crypto/context.h and third_party/private-join-and-compute/crypto/context.h differ +Files /tmp/private-join-and-compute.original/crypto/ec_commutative_cipher.cc and third_party/private-join-and-compute/crypto/ec_commutative_cipher.cc differ +Files /tmp/private-join-and-compute.original/crypto/ec_commutative_cipher.h and third_party/private-join-and-compute/crypto/ec_commutative_cipher.h differ +Files /tmp/private-join-and-compute.original/crypto/ec_group.cc and third_party/private-join-and-compute/crypto/ec_group.cc differ +Files /tmp/private-join-and-compute.original/crypto/ec_point.cc and third_party/private-join-and-compute/crypto/ec_point.cc differ +Only in /tmp/private-join-and-compute.original/crypto: elgamal.cc +Only in /tmp/private-join-and-compute.original/crypto: elgamal.h +Only in /tmp/private-join-and-compute.original/crypto: fixed_base_exp.cc +Only in /tmp/private-join-and-compute.original/crypto: fixed_base_exp.h +Only in /tmp/private-join-and-compute.original/crypto: mont_mul.cc +Only in /tmp/private-join-and-compute.original/crypto: mont_mul.h +Only in /tmp/private-join-and-compute.original/crypto: openssl_init.cc +Only in /tmp/private-join-and-compute.original/crypto: openssl_init.h +Only in /tmp/private-join-and-compute.original/crypto: paillier.cc +Only in /tmp/private-join-and-compute.original/crypto: paillier.h +Only in /tmp/private-join-and-compute.original/crypto: two_modulus_crt.cc +Only in /tmp/private-join-and-compute.original/crypto: two_modulus_crt.h +Only in /tmp/private-join-and-compute.original: data_util.cc +Only in /tmp/private-join-and-compute.original: data_util.h +Only in third_party/private-join-and-compute: DEPS +Only in /tmp/private-join-and-compute.original: generate_dummy_data.cc +Only in /tmp/private-join-and-compute.original: .git +Only in /tmp/private-join-and-compute.original: glog_files +Only in /tmp/private-join-and-compute.original: match.proto +Only in /tmp/private-join-and-compute.original: message_sink.h +Only in third_party/private-join-and-compute: OWNERS +Only in /tmp/private-join-and-compute.original: private_intersection_sum.proto +Only in /tmp/private-join-and-compute.original: private_join_and_compute.proto +Only in /tmp/private-join-and-compute.original: private_join_and_compute_rpc_impl.cc +Only in /tmp/private-join-and-compute.original: private_join_and_compute_rpc_impl.h +Only in /tmp/private-join-and-compute.original: protocol_client.h +Only in /tmp/private-join-and-compute.original: protocol_server.h +Only in third_party/private-join-and-compute: README.chromium +Only in /tmp/private-join-and-compute.original: server.cc +Only in /tmp/private-join-and-compute.original: server_impl.cc +Only in /tmp/private-join-and-compute.original: server_impl.h +Only in /tmp/private-join-and-compute.original/util: BUILD +Files /tmp/private-join-and-compute.original/util/status.cc and third_party/private-join-and-compute/util/status.cc differ +Files /tmp/private-join-and-compute.original/util/status.h and third_party/private-join-and-compute/util/status.h differ +Files /tmp/private-join-and-compute.original/util/status_macros.h and third_party/private-join-and-compute/util/status_macros.h differ +Files /tmp/private-join-and-compute.original/util/statusor.cc and third_party/private-join-and-compute/util/statusor.cc differ +Files /tmp/private-join-and-compute.original/util/statusor.h and third_party/private-join-and-compute/util/statusor.h differ +Only in /tmp/private-join-and-compute.original: WORKSPACE
diff --git a/third_party/private-join-and-compute/patches/fix_nulls.diff b/third_party/private-join-and-compute/patches/fix_nulls.diff new file mode 100644 index 0000000..de35a94 --- /dev/null +++ b/third_party/private-join-and-compute/patches/fix_nulls.diff
@@ -0,0 +1,43 @@ +diff -ur --strip-trailing-cr /tmp/private-join-and-compute.original/util/statusor.cc third_party/private-join-and-compute/util/statusor.cc +--- /tmp/private-join-and-compute.original/util/statusor.cc 2019-08-07 14:21:57.196714841 +0200 ++++ third_party/private-join-and-compute/util/statusor.cc 2019-08-07 12:42:02.939051124 +0200 +@@ -24,7 +24,7 @@ + static const char* kInvalidStatusCtorArgMessage = + "Status::OK is not a valid constructor argument to StatusOr<T>"; + static const char* kNullObjectCtorArgMessage = +- "NULL is not a valid constructor argument to StatusOr<T*>"; ++ "nullptr is not a valid constructor argument to StatusOr<T*>"; + + Status StatusOrHelper::HandleInvalidStatusCtorArg() { + LOG(DFATAL) << kInvalidStatusCtorArgMessage; +diff -ur --strip-trailing-cr /tmp/private-join-and-compute.original/util/statusor.h third_party/private-join-and-compute/util/statusor.h +--- /tmp/private-join-and-compute.original/util/statusor.h 2019-08-07 14:26:10.384523517 +0200 ++++ third_party/private-join-and-compute/util/statusor.h 2019-08-07 12:42:02.939051124 +0200 +@@ -96,15 +96,15 @@ + StatusOr(const Status& status); // NOLINT - no explicit + + // Construct a new StatusOr with the given value. If T is a plain pointer, +- // value must not be NULL. After calling this constructor, calls to ++ // value must not be nullptr. After calling this constructor, calls to + // ValueOrDie() will succeed, and calls to status() will return OK. + // + // NOTE: Not explicit - we want to use StatusOr<T> as a return type + // so it is convenient and sensible to be able to do 'return T()' + // when the return type is StatusOr<T>. + // +- // REQUIRES: if T is a plain pointer, value != NULL. This requirement is +- // DCHECKed. In optimized builds, passing a NULL pointer here will have ++ // REQUIRES: if T is a plain pointer, value != nullptr. This requirement is ++ // DCHECKed. In optimized builds, passing a nullptr pointer here will have + // the effect of passing ::private_join_and_compute::StatusCode::kInternal as a fallback. + StatusOr(const T& value); // NOLINT - no explicit + +@@ -165,7 +165,7 @@ + + template <typename T> + struct StatusOrHelper::Specialize { +- // For non-pointer T, a reference can never be NULL. ++ // For non-pointer T, a reference can never be nullptr. + static inline bool IsValueNull(const T& t) { return false; } + }; +
diff --git a/third_party/private-join-and-compute/src/BUILD.gn b/third_party/private-join-and-compute/src/BUILD.gn new file mode 100644 index 0000000..d4eea396 --- /dev/null +++ b/third_party/private-join-and-compute/src/BUILD.gn
@@ -0,0 +1,38 @@ +config("private_join_and_compute_config") { + include_dirs = [ + "//third_party/boringssl/src/include", + ] +} + +source_set("ec_commutative_cipher") { + sources = [ + "chromium_patch.h", + "crypto/big_num.cc", + "crypto/big_num.h", + "crypto/context.cc", + "crypto/context.h", + "crypto/ec_commutative_cipher.cc", + "crypto/ec_commutative_cipher.h", + "crypto/ec_group.cc", + "crypto/ec_group.h", + "crypto/ec_point.cc", + "crypto/ec_point.h", + "crypto/openssl.inc", + "util/canonical_errors.cc", + "util/canonical_errors.h", + "util/status.cc", + "util/status.h", + "util/status.inc", + "util/status_builder.h", + "util/status_macros.h", + "util/statusor.cc", + "util/statusor.h", + ] + deps = [ + "//base", + "//third_party/boringssl", + ] + + configs += [ "//build/config/compiler:no_chromium_code" ] + public_configs = [ ":private_join_and_compute_config" ] +}
diff --git a/third_party/private-join-and-compute/src/CONTRIBUTING.md b/third_party/private-join-and-compute/src/CONTRIBUTING.md new file mode 100644 index 0000000..db177d4a --- /dev/null +++ b/third_party/private-join-and-compute/src/CONTRIBUTING.md
@@ -0,0 +1,28 @@ +# How to Contribute + +We'd love to accept your patches and contributions to this project. There are +just a few small guidelines you need to follow. + +## Contributor License Agreement + +Contributions to this project must be accompanied by a Contributor License +Agreement. You (or your employer) retain the copyright to your contribution; +this simply gives us permission to use and redistribute your contributions as +part of the project. Head over to <https://cla.developers.google.com/> to see +your current agreements on file or to sign a new one. + +You generally only need to submit a CLA once, so if you've already submitted one +(even if it was for a different project), you probably don't need to do it +again. + +## Code reviews + +All submissions, including submissions by project members, require review. We +use GitHub pull requests for this purpose. Consult +[GitHub Help](https://help.github.com/articles/about-pull-requests/) for more +information on using pull requests. + +## Community Guidelines + +This project follows +[Google's Open Source Community Guidelines](https://opensource.google.com/conduct/).
diff --git a/third_party/private-join-and-compute/src/DEPS b/third_party/private-join-and-compute/src/DEPS new file mode 100644 index 0000000..7faa9ca --- /dev/null +++ b/third_party/private-join-and-compute/src/DEPS
@@ -0,0 +1,6 @@ +specific_include_rules = { + "chromium_patch.h": [ + "+base", + ] +} +
diff --git a/third_party/private-join-and-compute/src/LICENSE b/third_party/private-join-and-compute/src/LICENSE new file mode 100644 index 0000000..7a4a3ea --- /dev/null +++ b/third_party/private-join-and-compute/src/LICENSE
@@ -0,0 +1,202 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. \ No newline at end of file
diff --git a/third_party/private-join-and-compute/src/OWNERS b/third_party/private-join-and-compute/src/OWNERS new file mode 100644 index 0000000..b80f4f1 --- /dev/null +++ b/third_party/private-join-and-compute/src/OWNERS
@@ -0,0 +1,4 @@ +jdoerrie@chromium.org +vasilii@chromium.org + +# COMPONENT: UI>Browser>Passwords
diff --git a/third_party/private-join-and-compute/src/chromium_patch.h b/third_party/private-join-and-compute/src/chromium_patch.h new file mode 100644 index 0000000..931a53ef --- /dev/null +++ b/third_party/private-join-and-compute/src/chromium_patch.h
@@ -0,0 +1,25 @@ +// Copyright 2019 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "base/compiler_specific.h" +#include "base/logging.h" + +#ifndef THIRD_PARTY_PRIVATE_JOIN_AND_COMPUTE_CHROMIUM_PATCH_H_ +#define THIRD_PARTY_PRIVATE_JOIN_AND_COMPUTE_CHROMIUM_PATCH_H_ + +namespace chromium_patch { + +// Replacement for glog macro. +template <typename T> +inline T CheckNotNull(const char* names, T&& t) { + CHECK(t) << names; + return std::forward<T>(t); +} + +} // namespace chromium_patch + +#define CHECK_NOTNULL(val) \ + ::chromium_patch::CheckNotNull("'" #val "' Must be non nullptr", (val)) + +#endif // THIRD_PARTY_PRIVATE_JOIN_AND_COMPUTE_CHROMIUM_PATCH_H_
diff --git a/third_party/private-join-and-compute/src/crypto/LICENSE b/third_party/private-join-and-compute/src/crypto/LICENSE new file mode 100644 index 0000000..7a4a3ea --- /dev/null +++ b/third_party/private-join-and-compute/src/crypto/LICENSE
@@ -0,0 +1,202 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. \ No newline at end of file
diff --git a/third_party/private-join-and-compute/src/crypto/big_num.cc b/third_party/private-join-and-compute/src/crypto/big_num.cc new file mode 100644 index 0000000..f50beb3 --- /dev/null +++ b/third_party/private-join-and-compute/src/crypto/big_num.cc
@@ -0,0 +1,257 @@ +/* + * Copyright 2019 Google Inc. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "third_party/private-join-and-compute/src/crypto/big_num.h" + +#include <cmath> +#include <vector> + +#include "third_party/private-join-and-compute/src/chromium_patch.h" +#include "third_party/private-join-and-compute/src/crypto/context.h" +#include "third_party/private-join-and-compute/src/crypto/openssl.inc" +#include "third_party/private-join-and-compute/src/util/status.inc" + +namespace private_join_and_compute { + +BigNum::BigNum(const BigNum& other) + : bn_(BignumPtr(CHECK_NOTNULL(BN_dup(other.bn_.get())))), + bn_ctx_(other.bn_ctx_) {} + +BigNum& BigNum::operator=(const BigNum& other) { + bn_ = BignumPtr(CHECK_NOTNULL(BN_dup(other.bn_.get()))); + bn_ctx_ = other.bn_ctx_; + return *this; +} + +BigNum::BigNum(BigNum&& other) + : bn_(std::move(other.bn_)), bn_ctx_(other.bn_ctx_) {} + +BigNum& BigNum::operator=(BigNum&& other) { + bn_ = std::move(other.bn_); + bn_ctx_ = other.bn_ctx_; + return *this; +} + +BigNum::BigNum(BN_CTX* bn_ctx, uint64_t number) : BigNum::BigNum(bn_ctx) { + CRYPTO_CHECK(BN_set_u64(bn_.get(), number)); +} + +BigNum::BigNum(BN_CTX* bn_ctx, const std::string& bytes) + : BigNum::BigNum(bn_ctx) { + CRYPTO_CHECK(nullptr != + BN_bin2bn(reinterpret_cast<const unsigned char*>(bytes.data()), + bytes.size(), bn_.get())); +} + +BigNum::BigNum(BN_CTX* bn_ctx, const unsigned char* bytes, int length) + : BigNum::BigNum(bn_ctx) { + CRYPTO_CHECK(nullptr != BN_bin2bn(bytes, length, bn_.get())); +} + +BigNum::BigNum(BN_CTX* bn_ctx) { + bn_ = BignumPtr(CHECK_NOTNULL(BN_new())); + bn_ctx_ = bn_ctx; +} + +BigNum::BigNum(BN_CTX* bn_ctx, BignumPtr bn) { + bn_ = std::move(bn); + bn_ctx_ = bn_ctx; +} + +const BIGNUM* BigNum::GetConstBignumPtr() const { return bn_.get(); } + +std::string BigNum::ToBytes() const { + CHECK(IsNonNegative()) << "Cannot serialize a negative BigNum."; + int length = BN_num_bytes(bn_.get()); + std::vector<unsigned char> bytes(length); + BN_bn2bin(bn_.get(), bytes.data()); + return std::string(reinterpret_cast<char*>(bytes.data()), bytes.size()); +} + +StatusOr<uint64_t> BigNum::ToIntValue() const { + uint64_t val; + if (!BN_get_u64(bn_.get(), &val)) { + return InvalidArgumentError("BigNum has more than 64 bits."); + } + return val; +} + +int BigNum::BitLength() const { return BN_num_bits(bn_.get()); } + +bool BigNum::IsPrime(double prime_error_probability) const { + int rounds = static_cast<int>(ceil(-log(prime_error_probability) / log(4))); + return (1 == BN_is_prime_ex(bn_.get(), rounds, bn_ctx_, nullptr)); +} + +bool BigNum::IsSafePrime(double prime_error_probability) const { + return IsPrime(prime_error_probability) && + ((*this - BigNum(bn_ctx_, 1)) / BigNum(bn_ctx_, 2)) + .IsPrime(prime_error_probability); +} + +bool BigNum::IsZero() const { return BN_is_zero(bn_.get()); } + +bool BigNum::IsOne() const { return BN_is_one(bn_.get()); } + +bool BigNum::IsNonNegative() const { return !BN_is_negative(bn_.get()); } + +BigNum BigNum::GetLastNBits(int n) const { + BigNum r = *this; + // Returns 0 on error (if r is already shorter than n bits), but the return + // value in that case should be the original value so there is no need to have + // error checking here. + BN_mask_bits(r.bn_.get(), n); + return r; +} + +bool BigNum::IsBitSet(int n) const { return BN_is_bit_set(bn_.get(), n); } + +// Returns a BigNum whose value is (- *this). +// Causes a check failure if the operation fails. +BigNum BigNum::Neg() const { + BigNum r = *this; + BN_set_negative(r.bn_.get(), !BN_is_negative(r.bn_.get())); + return r; +} + +BigNum BigNum::Add(const BigNum& val) const { + BigNum r(bn_ctx_); + CRYPTO_CHECK(1 == BN_add(r.bn_.get(), bn_.get(), val.bn_.get())); + return r; +} + +BigNum BigNum::Mul(const BigNum& val) const { + BigNum r(bn_ctx_); + CRYPTO_CHECK(1 == BN_mul(r.bn_.get(), bn_.get(), val.bn_.get(), bn_ctx_)); + return r; +} + +BigNum BigNum::Sub(const BigNum& val) const { + BigNum r(bn_ctx_); + CRYPTO_CHECK(1 == BN_sub(r.bn_.get(), bn_.get(), val.bn_.get())); + return r; +} + +BigNum BigNum::Div(const BigNum& val) const { + BigNum r(bn_ctx_); + BignumPtr rem(CHECK_NOTNULL(BN_new())); + CRYPTO_CHECK( + 1 == BN_div(r.bn_.get(), rem.get(), bn_.get(), val.bn_.get(), bn_ctx_)); + CHECK(BN_is_zero(rem.get())) << "Use DivAndTruncate() instead of Div() if " + "you want truncated division."; + return r; +} + +BigNum BigNum::DivAndTruncate(const BigNum& val) const { + BigNum r(bn_ctx_); + BignumPtr rem(CHECK_NOTNULL(BN_new())); + CRYPTO_CHECK( + 1 == BN_div(r.bn_.get(), rem.get(), bn_.get(), val.bn_.get(), bn_ctx_)); + return r; +} + +int BigNum::CompareTo(const BigNum& val) const { + return BN_cmp(bn_.get(), val.bn_.get()); +} + +BigNum BigNum::Exp(const BigNum& exponent) const { + BigNum r(bn_ctx_); + CRYPTO_CHECK(1 == + BN_exp(r.bn_.get(), bn_.get(), exponent.bn_.get(), bn_ctx_)); + return r; +} + +BigNum BigNum::Mod(const BigNum& m) const { + BigNum r(bn_ctx_); + CRYPTO_CHECK(1 == BN_nnmod(r.bn_.get(), bn_.get(), m.bn_.get(), bn_ctx_)); + return r; +} + +BigNum BigNum::ModAdd(const BigNum& val, const BigNum& m) const { + BigNum r(bn_ctx_); + CRYPTO_CHECK(1 == BN_mod_add(r.bn_.get(), bn_.get(), val.bn_.get(), + m.bn_.get(), bn_ctx_)); + return r; +} + +BigNum BigNum::ModSub(const BigNum& val, const BigNum& m) const { + BigNum r(bn_ctx_); + CRYPTO_CHECK(1 == BN_mod_sub(r.bn_.get(), bn_.get(), val.bn_.get(), + m.bn_.get(), bn_ctx_)); + return r; +} + +BigNum BigNum::ModMul(const BigNum& val, const BigNum& m) const { + BigNum r(bn_ctx_); + CRYPTO_CHECK(1 == BN_mod_mul(r.bn_.get(), bn_.get(), val.bn_.get(), + m.bn_.get(), bn_ctx_)); + return r; +} + +BigNum BigNum::ModExp(const BigNum& exponent, const BigNum& m) const { + CHECK(exponent.IsNonNegative()) << "Cannot use a negative exponent in BigNum " + "ModExp."; + BigNum r(bn_ctx_); + CRYPTO_CHECK(1 == BN_mod_exp(r.bn_.get(), bn_.get(), exponent.bn_.get(), + m.bn_.get(), bn_ctx_)); + return r; +} + +BigNum BigNum::ModSqr(const BigNum& m) const { + BigNum r(bn_ctx_); + CRYPTO_CHECK(1 == BN_mod_sqr(r.bn_.get(), bn_.get(), m.bn_.get(), bn_ctx_)); + return r; +} + +BigNum BigNum::ModInverse(const BigNum& m) const { + BigNum r(bn_ctx_); + CRYPTO_CHECK(nullptr != + BN_mod_inverse(r.bn_.get(), bn_.get(), m.bn_.get(), bn_ctx_)); + return r; +} + +BigNum BigNum::ModSqrt(const BigNum& m) const { + BigNum r(bn_ctx_); + CRYPTO_CHECK(nullptr != + BN_mod_sqrt(r.bn_.get(), bn_.get(), m.bn_.get(), bn_ctx_)); + return r; +} + +BigNum BigNum::ModNegate(const BigNum& m) const { + if (IsZero()) { + return *this; + } + return m - Mod(m); +} + +BigNum BigNum::Lshift(int n) const { + BigNum r(bn_ctx_); + CRYPTO_CHECK(1 == BN_lshift(r.bn_.get(), bn_.get(), n)); + return r; +} + +BigNum BigNum::Rshift(int n) const { + BigNum r(bn_ctx_); + CRYPTO_CHECK(1 == BN_rshift(r.bn_.get(), bn_.get(), n)); + return r; +} + +BigNum BigNum::Gcd(const BigNum& val) const { + BigNum r(bn_ctx_); + CRYPTO_CHECK(1 == BN_gcd(r.bn_.get(), bn_.get(), val.bn_.get(), bn_ctx_)); + return r; +} + +} // namespace private_join_and_compute
diff --git a/third_party/private-join-and-compute/src/crypto/big_num.h b/third_party/private-join-and-compute/src/crypto/big_num.h new file mode 100644 index 0000000..aa13244 --- /dev/null +++ b/third_party/private-join-and-compute/src/crypto/big_num.h
@@ -0,0 +1,243 @@ +/* + * Copyright 2019 Google Inc. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef CRYPTO_BIG_NUM_H_ +#define CRYPTO_BIG_NUM_H_ + +#include <stdint.h> + +#include <memory> +#include <string> + +#include "third_party/private-join-and-compute/src/crypto/openssl.inc" +#include "third_party/private-join-and-compute/src/util/status.inc" + +namespace private_join_and_compute { + +// Immutable wrapper class for openssl BIGNUM numbers. +// Used for arithmetic operations on big numbers. +// Makes use of a BN_CTX structure that holds temporary BIGNUMs needed for +// arithmetic operations as dynamic memory allocation to create BIGNUMs is +// expensive. +class BigNum { + public: + // Deletes a BIGNUM. + class BnDeleter { + public: + void operator()(BIGNUM* bn) { BN_clear_free(bn); } + }; + + // Copies the given BigNum. + BigNum(const BigNum& other); + BigNum& operator=(const BigNum& other); + + // Moves the given BigNum. + BigNum(BigNum&& other); + BigNum& operator=(BigNum&& other); + + typedef std::unique_ptr<BIGNUM, BnDeleter> BignumPtr; + + // Returns the absolute value of this in big-endian form. + std::string ToBytes() const; + + // Converts this BigNum to a uint64_t value. Returns an INVALID_ARGUMENT + // error code if the value of *this is larger than 64 bits. + StatusOr<uint64_t> ToIntValue() const; + + // Returns the bit length of this BigNum. + int BitLength() const; + + // Returns False if the number is composite, True if it is prime with an + // error probability of 1e-40, which gives at least 128 bit security. + bool IsPrime(double prime_error_probability = 1e-40) const; + + // Returns False if the number is composite, True if it is safe prime with an + // error probability of at most 1e-40. + bool IsSafePrime(double prime_error_probability = 1e-40) const; + + // Return True if this BigNum is zero. + bool IsZero() const; + + // Return True if this BigNum is one. + bool IsOne() const; + + // Returns True if this BigNum is not negative. + bool IsNonNegative() const; + + // Returns a BigNum that is equal to the last n bits of this BigNum. + BigNum GetLastNBits(int n) const; + + // Returns true if n-th bit of this big_num is set, false otherwise. + bool IsBitSet(int n) const; + + // Returns a BigNum whose value is (- *this). + // Causes a check failure if the operation fails. + BigNum Neg() const; + + // Returns a BigNum whose value is (*this + val). + // Causes a check failure if the operation fails. + BigNum Add(const BigNum& val) const; + + // Returns a BigNum whose value is (*this * val). + // Causes a check failure if the operation fails. + BigNum Mul(const BigNum& val) const; + + // Returns a BigNum whose value is (*this - val). + // Causes a check failure if the operation fails. + BigNum Sub(const BigNum& val) const; + + // Returns a BigNum whose value is (*this / val). + // Causes a check failure if the remainder != 0 or if the operation fails. + BigNum Div(const BigNum& val) const; + + // Returns a BigNum whose value is *this / val, rounding towards zero. + // Causes a check failure if the remainder != 0 or if the operation fails. + BigNum DivAndTruncate(const BigNum& val) const; + + // Compares this BigNum with the specified BigNum. + // Returns -1 if *this < val, 0 if *this == val and 1 if *this > val. + int CompareTo(const BigNum& val) const; + + // Returns a BigNum whose value is (*this ^ exponent). + // Causes a check failure if the operation fails. + BigNum Exp(const BigNum& exponent) const; + + // Returns a BigNum whose value is (*this mod m). + BigNum Mod(const BigNum& m) const; + + // Returns a BigNum whose value is (*this + val mod m). + // Causes a check failure if the operation fails. + BigNum ModAdd(const BigNum& val, const BigNum& m) const; + + // Returns a BigNum whose value is (*this - val mod m). + // Causes a check failure if the operation fails. + BigNum ModSub(const BigNum& val, const BigNum& m) const; + + // Returns a BigNum whose value is (*this * val mod m). + // For efficiency, please use Montgomery multiplication module if this is done + // multiple times with the same modulus. + // Causes a check failure if the operation fails. + BigNum ModMul(const BigNum& val, const BigNum& m) const; + + // Returns a BigNum whose value is (*this ^ exponent mod m). + // Causes a check failure if the operation fails. + BigNum ModExp(const BigNum& exponent, const BigNum& m) const; + + // Return a BigNum whose value is (*this ^ 2 mod m). + // Causes a check failure if the operation fails. + BigNum ModSqr(const BigNum& m) const; + + // Returns a BigNum whose value is (*this ^ -1 mod m). + // Causes a check failure if the operation fails. + BigNum ModInverse(const BigNum& m) const; + + // Returns r such that r ^ 2 == *this mod p. + // Causes a check failure if the operation fails. + BigNum ModSqrt(const BigNum& m) const; + + // Computes -a mod m. + // Causes a check failure if the operation fails. + BigNum ModNegate(const BigNum& m) const; + + // Returns a BigNum whose value is (*this >> n). + BigNum Rshift(int n) const; + + // Returns a BigNum whose value is (*this << n). + // Causes a check failure if the operation fails. + BigNum Lshift(int n) const; + + // Computes the greatest common divisor of *this and val. + // Causes a check failure if the operation fails. + BigNum Gcd(const BigNum& val) const; + + // Returns a pointer to const BIGNUM to be used with openssl functions. + const BIGNUM* GetConstBignumPtr() const; + + private: + // Creates a new BigNum object from a bytes string. + explicit BigNum(BN_CTX* bn_ctx, const std::string& bytes); + // Creates a new BigNum object from a char array. + explicit BigNum(BN_CTX* bn_ctx, const unsigned char* bytes, int length); + // Creates a new BigNum object from the number. + explicit BigNum(BN_CTX* bn_ctx, uint64_t number); + // Creates a new BigNum object with no defined value. + explicit BigNum(BN_CTX* bn_ctx); + // Creates a new BigNum object from the given BIGNUM value. + explicit BigNum(BN_CTX* bn_ctx, BignumPtr bn); + + BignumPtr bn_; + BN_CTX* bn_ctx_; + + // Context is a factory for BigNum objects. + friend class Context; +}; + +inline BigNum operator-(const BigNum& a) { return a.Neg(); } + +inline BigNum operator+(const BigNum& a, const BigNum& b) { return a.Add(b); } + +inline BigNum operator*(const BigNum& a, const BigNum& b) { return a.Mul(b); } + +inline BigNum operator-(const BigNum& a, const BigNum& b) { return a.Sub(b); } + +// Returns a BigNum whose value is (a / b). +// Causes a check failure if the remainder != 0. +inline BigNum operator/(const BigNum& a, const BigNum& b) { return a.Div(b); } + +inline BigNum& operator+=(BigNum& a, const BigNum& b) { return a = a + b; } + +inline BigNum& operator*=(BigNum& a, const BigNum& b) { return a = a * b; } + +inline BigNum& operator-=(BigNum& a, const BigNum& b) { return a = a - b; } + +inline BigNum& operator/=(BigNum& a, const BigNum& b) { return a = a / b; } + +inline bool operator==(const BigNum& a, const BigNum& b) { + return 0 == a.CompareTo(b); +} + +inline bool operator!=(const BigNum& a, const BigNum& b) { return !(a == b); } + +inline bool operator<(const BigNum& a, const BigNum& b) { + return -1 == a.CompareTo(b); +} + +inline bool operator>(const BigNum& a, const BigNum& b) { + return 1 == a.CompareTo(b); +} + +inline bool operator<=(const BigNum& a, const BigNum& b) { + return a.CompareTo(b) <= 0; +} + +inline bool operator>=(const BigNum& a, const BigNum& b) { + return a.CompareTo(b) >= 0; +} + +inline BigNum operator%(const BigNum& a, const BigNum& m) { return a.Mod(m); } + +inline BigNum operator>>(const BigNum& a, int n) { return a.Rshift(n); } + +inline BigNum operator<<(const BigNum& a, int n) { return a.Lshift(n); } + +inline BigNum& operator%=(BigNum& a, const BigNum& b) { return a = a % b; } + +inline BigNum& operator>>=(BigNum& a, int n) { return a = a >> n; } + +inline BigNum& operator<<=(BigNum& a, int n) { return a = a << n; } + +} // namespace private_join_and_compute + +#endif // CRYPTO_BIG_NUM_H_
diff --git a/third_party/private-join-and-compute/src/crypto/context.cc b/third_party/private-join-and-compute/src/crypto/context.cc new file mode 100644 index 0000000..299e3b9 --- /dev/null +++ b/third_party/private-join-and-compute/src/crypto/context.cc
@@ -0,0 +1,186 @@ +/* + * Copyright 2019 Google Inc. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "third_party/private-join-and-compute/src/crypto/context.h" + +#include <math.h> + +#include <algorithm> +#include <cmath> + +#include "third_party/private-join-and-compute/src/chromium_patch.h" + +namespace private_join_and_compute { + +std::string OpenSSLErrorString() { + char buf[256]; + ERR_error_string_n(ERR_get_error(), buf, sizeof(buf)); + return buf; +} + +Context::Context() + : bn_ctx_(CHECK_NOTNULL(BN_CTX_new())), + evp_md_ctx_(CHECK_NOTNULL(EVP_MD_CTX_create())), + zero_bn_(CreateBigNum(0)), + one_bn_(CreateBigNum(1)), + two_bn_(CreateBigNum(2)), + three_bn_(CreateBigNum(3)) { + CHECK(RAND_status()) << "OpenSSL PRNG is not properly seeded."; + HMAC_CTX_init(&hmac_ctx_); +} + +Context::~Context() { HMAC_CTX_cleanup(&hmac_ctx_); } + +BN_CTX* Context::GetBnCtx() { return bn_ctx_.get(); } + +BigNum Context::CreateBigNum(const std::string& bytes) { + return BigNum(bn_ctx_.get(), bytes); +} + +BigNum Context::CreateBigNum(uint64_t number) { + return BigNum(bn_ctx_.get(), number); +} + +BigNum Context::CreateBigNum(BigNum::BignumPtr bn) { + return BigNum(bn_ctx_.get(), std::move(bn)); +} + +std::string Context::Sha256String(const std::string& bytes) { + unsigned char hash[EVP_MAX_MD_SIZE]; + CRYPTO_CHECK(1 == + EVP_DigestInit_ex(evp_md_ctx_.get(), EVP_sha256(), nullptr)); + CRYPTO_CHECK( + 1 == EVP_DigestUpdate(evp_md_ctx_.get(), bytes.c_str(), bytes.length())); + unsigned int md_len; + CRYPTO_CHECK(1 == EVP_DigestFinal_ex(evp_md_ctx_.get(), hash, &md_len)); + return std::string(reinterpret_cast<char*>(hash), md_len); +} + +std::string Context::Sha512String(const std::string& bytes) { + unsigned char hash[EVP_MAX_MD_SIZE]; + CRYPTO_CHECK(1 == + EVP_DigestInit_ex(evp_md_ctx_.get(), EVP_sha512(), nullptr)); + CRYPTO_CHECK( + 1 == EVP_DigestUpdate(evp_md_ctx_.get(), bytes.c_str(), bytes.length())); + unsigned int md_len; + CRYPTO_CHECK(1 == EVP_DigestFinal_ex(evp_md_ctx_.get(), hash, &md_len)); + return std::string(reinterpret_cast<char*>(hash), md_len); +} + +BigNum Context::RandomOracle(const std::string& x, const BigNum& max_value, + RandomOracleHashType hash_type) { + int hash_output_length = 256; + if (hash_type == SHA512) { + hash_output_length = 512; + } + int output_bit_length = max_value.BitLength() + hash_output_length; + int iter_count = + std::ceil(static_cast<float>(output_bit_length) / hash_output_length); + CHECK(iter_count * hash_output_length < 130048) + << "The domain bit length must not be greater than " + "130048. Desired bit length: " + << output_bit_length; + int excess_bit_count = (iter_count * hash_output_length) - output_bit_length; + BigNum hash_output = CreateBigNum(0); + for (int i = 1; i < iter_count + 1; i++) { + hash_output = hash_output.Lshift(hash_output_length); + std::string hashed_string; + if (hash_type == SHA512) { + hashed_string = Sha512String(CreateBigNum(i).ToBytes().append(x)); + } else { + hashed_string = Sha256String(CreateBigNum(i).ToBytes().append(x)); + } + hash_output = hash_output + CreateBigNum(hashed_string); + } + return hash_output.Rshift(excess_bit_count).Mod(max_value); +} + +BigNum Context::RandomOracleSha512(const std::string& x, + const BigNum& max_value) { + return RandomOracle(x, max_value, SHA512); +} + +BigNum Context::RandomOracleSha256(const std::string& x, + const BigNum& max_value) { + return RandomOracle(x, max_value, SHA256); +} + +BigNum Context::PRF(const std::string& key, const std::string& data, + const BigNum& max_value) { + CHECK_GE(key.size() * 8, 80u); + CHECK_LE(max_value.BitLength(), 512) + << "The requested output length is not supported. The maximum " + "supported output length is 512. The requested output length is " + << max_value.BitLength(); + CRYPTO_CHECK(1 == HMAC_Init_ex(&hmac_ctx_, key.c_str(), key.size(), + EVP_sha512(), nullptr)); + CRYPTO_CHECK(1 == + HMAC_Update(&hmac_ctx_, + reinterpret_cast<const unsigned char*>(data.data()), + data.size())); + unsigned int md_len; + unsigned char hash[EVP_MAX_MD_SIZE]; + CRYPTO_CHECK(1 == HMAC_Final(&hmac_ctx_, hash, &md_len)); + BigNum hash_bn(bn_ctx_.get(), hash, md_len); + BigNum hash_bn_reduced = hash_bn.GetLastNBits(max_value.BitLength()); + if (hash_bn_reduced < max_value) { + return hash_bn_reduced; + } else { + return Context::PRF(key, hash_bn.ToBytes(), max_value); + } +} + +BigNum Context::GenerateSafePrime(int prime_length) { + BigNum r(bn_ctx_.get()); + CRYPTO_CHECK(1 == BN_generate_prime_ex(r.bn_.get(), prime_length, 1, nullptr, + nullptr, nullptr)); + return r; +} + +BigNum Context::GeneratePrime(int prime_length) { + BigNum r(bn_ctx_.get()); + CRYPTO_CHECK(1 == BN_generate_prime_ex(r.bn_.get(), prime_length, 0, nullptr, + nullptr, nullptr)); + return r; +} + +BigNum Context::GenerateRandLessThan(const BigNum& max_value) { + BigNum r(bn_ctx_.get()); + CRYPTO_CHECK(1 == BN_rand_range(r.bn_.get(), max_value.bn_.get())); + return r; +} + +BigNum Context::GenerateRandBetween(const BigNum& start, const BigNum& end) { + CHECK(start < end); + return GenerateRandLessThan(end - start) + start; +} + +std::string Context::GenerateRandomBytes(int num_bytes) { + CHECK_GE(num_bytes, 0) << "num_bytes must be nonnegative, provided value was " + << num_bytes << "."; + std::unique_ptr<unsigned char[]> bytes(new unsigned char[num_bytes]); + CRYPTO_CHECK(1 == RAND_bytes(bytes.get(), num_bytes)); + return std::string(reinterpret_cast<char*>(bytes.get()), num_bytes); +} + +BigNum Context::RelativelyPrimeRandomLessThan(const BigNum& num) { + BigNum rand_num = GenerateRandLessThan(num); + while (rand_num.Gcd(num) > One()) { + rand_num = GenerateRandLessThan(num); + } + return rand_num; +} + +} // namespace private_join_and_compute
diff --git a/third_party/private-join-and-compute/src/crypto/context.h b/third_party/private-join-and-compute/src/crypto/context.h new file mode 100644 index 0000000..9b0384d --- /dev/null +++ b/third_party/private-join-and-compute/src/crypto/context.h
@@ -0,0 +1,181 @@ +/* + * Copyright 2019 Google Inc. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef CRYPTO_CONTEXT_H_ +#define CRYPTO_CONTEXT_H_ + +#include <stdint.h> + +#include <memory> +#include <string> + +#include "third_party/private-join-and-compute/src/chromium_patch.h" +#include "third_party/private-join-and-compute/src/crypto/big_num.h" +#include "third_party/private-join-and-compute/src/crypto/openssl.inc" + +#define CRYPTO_CHECK(expr) CHECK(expr) << OpenSSLErrorString(); + +namespace private_join_and_compute { + +std::string OpenSSLErrorString(); + +// Wrapper around various contexts needed for openssl operations. It holds a +// BN_CTX to be reused when doing BigNum arithmetic operations and an EVP_MD_CTX +// to be reused when doing hashing operations. +// +// This class provides factory methods for creating BigNum objects that take +// advantage of the BN_CTX structure for arithmetic operations. +// +// This class is not thread-safe, so each thread needs to have a unique Context +// initialized. +class Context { + public: + // Deletes a BN_CTX. + class BnCtxDeleter { + public: + void operator()(BN_CTX* ctx) { BN_CTX_free(ctx); } + }; + typedef std::unique_ptr<BN_CTX, BnCtxDeleter> BnCtxPtr; + + // Deletes an EVP_MD_CTX. + class EvpMdCtxDeleter { + public: + void operator()(EVP_MD_CTX* ctx) { EVP_MD_CTX_destroy(ctx); } + }; + typedef std::unique_ptr<EVP_MD_CTX, EvpMdCtxDeleter> EvpMdCtxPtr; + + Context(); + + // Context is neither copyable nor movable. + Context(const Context&) = delete; + Context& operator=(const Context&) = delete; + + virtual ~Context(); + + // Returns a pointer to the openssl BN_CTX that can be reused for arithmetic + // operations. + BN_CTX* GetBnCtx(); + + // Creates a BigNum initialized with the given BIGNUM value. + BigNum CreateBigNum(BigNum::BignumPtr bn); + + // Creates a BigNum initialized with the given bytes string. + BigNum CreateBigNum(const std::string& bytes); + + // Creates a BigNum initialized with the given number. + BigNum CreateBigNum(uint64_t number); + + // Hashes a string using SHA-256 to a byte string. + virtual std::string Sha256String(const std::string& bytes); + + // Hashes a string using SHA-512 to a byte string. + virtual std::string Sha512String(const std::string& bytes); + + // A random oracle function mapping x deterministically into a large domain. + // + // The random oracle is similar to the example given in the last paragraph of + // Chapter 6 of [1] where the output is expanded by successively hashing the + // concatenation of the input with a fixed sized counter starting from 1. + // + // [1] Bellare, Mihir, and Phillip Rogaway. "Random oracles are practical: + // A paradigm for designing efficient protocols." Proceedings of the 1st ACM + // conference on Computer and communications security. ACM, 1993. + // + // Returns a long value from the set [0, max_value). + // + // Check Error: if bit length of max_value is greater than 130048. + // Since the counter used for expanding the output is expanded to 8 bit length + // (hard-coded), any counter value that is greater than 256 would cause + // variable length inputs passed to the underlying sha256/sha512 calls and + // might make this random oracle's output not uniform across the output + // domain. + // + // The output length is increased by a security value of 256/512 which reduces + // the bias of selecting certain values more often than others when max_value + // is not a multiple of 2. + virtual BigNum RandomOracleSha256(const std::string& x, + const BigNum& max_value); + virtual BigNum RandomOracleSha512(const std::string& x, + const BigNum& max_value); + + // Evaluates a PRF keyed by 'key' on the given data. The returned value is + // less than max_value. + // + // The maximum supported output length is 512. Causes a check failure if the + // bit length of max_value is > 512. + // + // Security: + // The security of this function is given by the length of the key. The key + // should be at least 80 bits long which gives 80 bit security. Fails if the + // key is less than 80 bits. + // + // This function is susceptible to timing attacks. + BigNum PRF(const std::string& key, const std::string& data, + const BigNum& max_value); + + // Creates a safe prime BigNum with the given bit-length. + BigNum GenerateSafePrime(int prime_length); + + // Creates a prime BigNum with the given bit-length. + // + // Note: In many cases, we need to use a safe prime for cryptographic security + // to hold. In this case, we should use GenerateSafePrime. + BigNum GeneratePrime(int prime_length); + + // Generates a cryptographically strong pseudo-random in the range [0, + // max_value). + // Marked virtual for tests. + virtual BigNum GenerateRandLessThan(const BigNum& max_value); + + // Generates a cryptographically strong pseudo-random in the range [start, + // end). + // Marked virtual for tests. + virtual BigNum GenerateRandBetween(const BigNum& start, const BigNum& end); + + // Generates a cryptographically strong pseudo-random bytes of the specified + // length. + // Marked virtual for tests. + virtual std::string GenerateRandomBytes(int num_bytes); + + // Returns a BigNum that is relatively prime to the num and less than the num. + virtual BigNum RelativelyPrimeRandomLessThan(const BigNum& num); + + inline const BigNum& Zero() const { return zero_bn_; } + inline const BigNum& One() const { return one_bn_; } + inline const BigNum& Two() const { return two_bn_; } + inline const BigNum& Three() const { return three_bn_; } + + private: + BnCtxPtr bn_ctx_; + EvpMdCtxPtr evp_md_ctx_; + HMAC_CTX hmac_ctx_; + const BigNum zero_bn_; + const BigNum one_bn_; + const BigNum two_bn_; + const BigNum three_bn_; + + enum RandomOracleHashType { + SHA256, + SHA512, + }; + + // If hash_type is invalid, this function will default to using SHA256. + virtual BigNum RandomOracle(const std::string& x, const BigNum& max_value, + RandomOracleHashType hash_type); +}; + +} // namespace private_join_and_compute + +#endif // CRYPTO_CONTEXT_H_
diff --git a/third_party/private-join-and-compute/src/crypto/ec_commutative_cipher.cc b/third_party/private-join-and-compute/src/crypto/ec_commutative_cipher.cc new file mode 100644 index 0000000..0075ae0 --- /dev/null +++ b/third_party/private-join-and-compute/src/crypto/ec_commutative_cipher.cc
@@ -0,0 +1,107 @@ +/* + * Copyright 2019 Google Inc. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "third_party/private-join-and-compute/src/crypto/ec_commutative_cipher.h" + +#include <utility> + +#include "third_party/private-join-and-compute/src/util/status.inc" + +namespace private_join_and_compute { + +ECCommutativeCipher::ECCommutativeCipher(std::unique_ptr<Context> context, + ECGroup group, BigNum private_key, + HashType hash_type) + : context_(std::move(context)), + group_(std::move(group)), + private_key_(std::move(private_key)), + private_key_inverse_(private_key_.ModInverse(group_.GetOrder())), + hash_type_(hash_type) {} + +bool ECCommutativeCipher::ValidateHashType(HashType hash_type) { + return (hash_type == SHA256 || hash_type == SHA512); +} + +StatusOr<std::unique_ptr<ECCommutativeCipher>> +ECCommutativeCipher::CreateWithNewKey(int curve_id, HashType hash_type) { + std::unique_ptr<Context> context(new Context); + ASSIGN_OR_RETURN(ECGroup group, ECGroup::Create(curve_id, context.get())); + if (!ECCommutativeCipher::ValidateHashType(hash_type)) { + return InvalidArgumentError("Invalid hash type."); + } + BigNum private_key = group.GeneratePrivateKey(); + return std::unique_ptr<ECCommutativeCipher>(new ECCommutativeCipher( + std::move(context), std::move(group), std::move(private_key), hash_type)); +} + +StatusOr<std::unique_ptr<ECCommutativeCipher>> +ECCommutativeCipher::CreateFromKey(int curve_id, const std::string& key_bytes, + HashType hash_type) { + std::unique_ptr<Context> context(new Context); + ASSIGN_OR_RETURN(ECGroup group, ECGroup::Create(curve_id, context.get())); + if (!ECCommutativeCipher::ValidateHashType(hash_type)) { + return InvalidArgumentError("Invalid hash type."); + } + BigNum private_key = context->CreateBigNum(key_bytes); + auto status = group.CheckPrivateKey(private_key); + if (!status.ok()) { + return status; + } + return std::unique_ptr<ECCommutativeCipher>(new ECCommutativeCipher( + std::move(context), std::move(group), std::move(private_key), hash_type)); +} + +StatusOr<std::string> ECCommutativeCipher::Encrypt( + const std::string& plaintext) const { + StatusOr<ECPoint> status_or_point; + if (hash_type_ == SHA512) { + status_or_point = group_.GetPointByHashingToCurveSha512(plaintext); + } else if (hash_type_ == SHA256) { + status_or_point = group_.GetPointByHashingToCurveSha256(plaintext); + } else { + return InvalidArgumentError("Invalid hash type."); + } + + if (!status_or_point.ok()) { + return status_or_point.status(); + } + ASSIGN_OR_RETURN(ECPoint encrypted_point, + Encrypt(status_or_point.ValueOrDie())); + return encrypted_point.ToBytesCompressed(); +} + +StatusOr<std::string> ECCommutativeCipher::ReEncrypt( + const std::string& ciphertext) const { + ASSIGN_OR_RETURN(ECPoint point, group_.CreateECPoint(ciphertext)); + ASSIGN_OR_RETURN(ECPoint reencrypted_point, Encrypt(point)); + return reencrypted_point.ToBytesCompressed(); +} + +StatusOr<ECPoint> ECCommutativeCipher::Encrypt(const ECPoint& point) const { + return point.Mul(private_key_); +} + +StatusOr<std::string> ECCommutativeCipher::Decrypt( + const std::string& ciphertext) const { + ASSIGN_OR_RETURN(ECPoint point, group_.CreateECPoint(ciphertext)); + ASSIGN_OR_RETURN(ECPoint decrypted_point, point.Mul(private_key_inverse_)); + return decrypted_point.ToBytesCompressed(); +} + +std::string ECCommutativeCipher::GetPrivateKeyBytes() const { + return private_key_.ToBytes(); +} + +} // namespace private_join_and_compute
diff --git a/third_party/private-join-and-compute/src/crypto/ec_commutative_cipher.h b/third_party/private-join-and-compute/src/crypto/ec_commutative_cipher.h new file mode 100644 index 0000000..11f2b09 --- /dev/null +++ b/third_party/private-join-and-compute/src/crypto/ec_commutative_cipher.h
@@ -0,0 +1,189 @@ +/* + * Copyright 2019 Google Inc. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef EC_COMMUTATIVE_CIPHER_H_ +#define EC_COMMUTATIVE_CIPHER_H_ + +#include <memory> +#include <string> + +#include "third_party/private-join-and-compute/src/crypto/big_num.h" +#include "third_party/private-join-and-compute/src/crypto/context.h" +#include "third_party/private-join-and-compute/src/crypto/ec_group.h" +#include "third_party/private-join-and-compute/src/crypto/ec_point.h" +#include "third_party/private-join-and-compute/src/util/status.inc" + +namespace private_join_and_compute { + +// ECCommutativeCipher class with the property that K1(K2(a)) = K2(K1(a)) +// where K(a) is encryption with the key K. https://eprint.iacr.org/2008/356.pdf +// +// This class allows two parties to determine if they share the same value, +// without revealing the sensitive value to each other. +// +// This class also allows homomorphically re-encrypting an ElGamal ciphertext +// with an EC cipher key K. If the original ciphertext was an encryption of m, +// then the re-encrypted ciphertext is effectively an encryption of K(m). This +// re-encryption does not re-randomize the ciphertext, and so is only secure +// when the underlying messages "m" are pseudorandom. +// +// The encryption is performed over an elliptic curve. +// +// This class is not thread-safe. +// +// Security: The provided bit security is half the number of bits of the +// underlying curve. For example, using curve NID_secp224r1 gives 112 bit +// security. +// +// Example: To generate a cipher with a new private key for the named curve +// NID_secp224r1. The key can be securely stored and reused. +// #include <openssl/obj_mac.h> +// std::unique_ptr<ECCommutativeCipher> cipher = +// ECCommutativeCipher::CreateWithNewKey( +// NID_secp224r1, ECCommutativeCipher::HashType::SHA256); +// string key_bytes = cipher->GetPrivateKeyBytes(); +// +// Example: To generate a cipher with an existing private key for the named +// curve NID_secp224r1. +// #include <openssl/obj_mac.h> +// std::unique_ptr<ECCommutativeCipher> cipher = +// ECCommutativeCipher::CreateFromKey( +// NID_secp224r1, key_bytes, ECCommutativeCipher::HashType::SHA256); +// +// Example: To encrypt a message using a std::unique_ptr<ECCommutativeCipher> +// cipher generated as above. +// string encrypted_string = cipher->Encrypt("secret"); +// +// Example: To re-encrypt a message already encrypted by another party using a +// std::unique_ptr<ECCommutativeCipher> cipher generated as above. +// ::private_join_and_compute::StatusOr<string> double_encrypted_string = +// cipher->ReEncrypt(encrypted_string); +// +// Example: To decrypt a message that has already been encrypted by the same +// party using a std::unique_ptr<ECCommutativeCipher> cipher generated as +// above. +// ::private_join_and_compute::StatusOr<string> decrypted_string = +// cipher->Decrypt(encrypted_string); +// +// Example: To re-encrypt a message that has already been encrypted using a +// std::unique_ptr<CommutativeElGamal> ElGamal key: +// ::private_join_and_compute::StatusOr<std::pair<string, string>> double_encrypted_string = +// cipher->ReEncryptElGamalCiphertext(elgamal_ciphertext); + +class ECCommutativeCipher { + public: + // The hash function used by the ECCommutativeCipher. + enum HashType { + SHA256, + SHA512, + }; + + // Check for valid HashType. + static bool ValidateHashType(HashType hash_type); + + // ECCommutativeCipher is neither copyable nor assignable. + ECCommutativeCipher(const ECCommutativeCipher&) = delete; + ECCommutativeCipher& operator=(const ECCommutativeCipher&) = delete; + + // Creates an ECCommutativeCipher object with a new random private key. + // Use this method when the key is created for the first time or it needs to + // be refreshed. + // Returns INVALID_ARGUMENT status instead if the curve_id is not valid + // or INTERNAL status when crypto operations are not successful. + static ::private_join_and_compute::StatusOr<std::unique_ptr<ECCommutativeCipher>> + CreateWithNewKey(int curve_id, HashType hash_type); + + // Creates an ECCommutativeCipher object with the given private key. + // A new key should be created for each session and all values should be + // unique in one session because the encryption is deterministic. + // Use this when the key is stored securely to be used at different steps of + // the protocol in the same session or by multiple processes. + // Returns INVALID_ARGUMENT status instead if the private_key is not valid for + // the given curve or the curve_id is not valid. + // Returns INTERNAL status when crypto operations are not successful. + static ::private_join_and_compute::StatusOr<std::unique_ptr<ECCommutativeCipher>> + CreateFromKey(int curve_id, const std::string& key_bytes, HashType hash_type); + + // Encrypts a string with the private key to a point on the elliptic curve. + // + // To encrypt, the string is hashed to a point on the curve which is then + // multiplied with the private key. + // + // The resulting point is returned encoded in compressed form as defined in + // ANSI X9.62 ECDSA. + // + // Returns an INVALID_ARGUMENT error code if an error occurs. + ::private_join_and_compute::StatusOr<std::string> Encrypt(const std::string& plaintext) const; + + // Encrypts an encoded point with the private key. + // + // Returns an INVALID_ARGUMENT error code if the input is not a valid encoding + // of a point on this curve as defined in ANSI X9.62 ECDSA. + // + // The result is a point encoded in compressed form. + // + // This method can also be used to encrypt a value that has already been + // hashed to the curve. + ::private_join_and_compute::StatusOr<std::string> ReEncrypt( + const std::string& ciphertext) const; + + // Decrypts an encoded point with the private key. + // + // Returns an INVALID_ARGUMENT error code if the input is not a valid encoding + // of a point on this curve as defined in ANSI X9.62 ECDSA. + // + // The result is a point encoded in compressed form. + // + // If the input point was double-encrypted, once with this key and once with + // another key, then the result point is single-encrypted with the other key. + // + // If the input point was single encrypted with this key, then the result + // point is the original, unencrypted point. Note that this will not reverse + // hashing to the curve. + ::private_join_and_compute::StatusOr<std::string> Decrypt( + const std::string& ciphertext) const; + + // Returns the private key bytes so the key can be stored and reused. + std::string GetPrivateKeyBytes() const; + + private: + // Creates a new ECCommutativeCipher object with the given private key for + // the given EC group. + ECCommutativeCipher(std::unique_ptr<Context> context, ECGroup group, + BigNum private_key, HashType hash_type); + + // Encrypts a point by multiplying the point with the private key. + ::private_join_and_compute::StatusOr<ECPoint> Encrypt(const ECPoint& point) const; + + // Context used for storing temporary values to be reused across openssl + // function calls for better performance. + std::unique_ptr<Context> context_; + + // The EC Group representing the curve definition. + const ECGroup group_; + + // The private key used for encryption. + const BigNum private_key_; + + // The private key inverse, used for decryption. + const BigNum private_key_inverse_; + + // The hash function used by the cipher. + const HashType hash_type_; +}; + +} // namespace private_join_and_compute + +#endif // EC_COMMUTATIVE_CIPHER_H_
diff --git a/third_party/private-join-and-compute/src/crypto/ec_group.cc b/third_party/private-join-and-compute/src/crypto/ec_group.cc new file mode 100644 index 0000000..c4a4770 --- /dev/null +++ b/third_party/private-join-and-compute/src/crypto/ec_group.cc
@@ -0,0 +1,271 @@ +/* + * Copyright 2019 Google Inc. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "third_party/private-join-and-compute/src/crypto/ec_group.h" + +#include <algorithm> +#include <utility> + +#include "third_party/private-join-and-compute/src/crypto/ec_point.h" +#include "third_party/private-join-and-compute/src/crypto/openssl.inc" +#include "third_party/private-join-and-compute/src/util/status.inc" + +namespace private_join_and_compute { + +namespace { + +// Returns a group using the predefined underlying operations suggested by +// OpenSSL. +StatusOr<ECGroup::ECGroupPtr> CreateGroup(int curve_id) { + auto ec_group_ptr = EC_GROUP_new_by_curve_name(curve_id); + // If this fails, this is usually due to an invalid curve id. + if (ec_group_ptr == nullptr) { + return InvalidArgumentError( + "ECGroup::CreateGroup() - Could not create group. " + + OpenSSLErrorString()); + } + return ECGroup::ECGroupPtr(ec_group_ptr); +} + +// Returns the order of the group. For more information, see +// https://en.wikipedia.org/wiki/Elliptic-curve_cryptography#Domain_parameters. +StatusOr<BigNum> CreateOrder(const EC_GROUP* group, Context* context) { + BIGNUM* bn = BN_new(); + if (bn == nullptr) { + return InternalError( + "ECGroup::CreateOrder - Could not create BIGNUM. " + + OpenSSLErrorString()); + } + BigNum::BignumPtr order = BigNum::BignumPtr(bn); + if (EC_GROUP_get_order(group, order.get(), context->GetBnCtx()) != 1) { + return InternalError( + "ECGroup::CreateOrder - Could not get order. " + OpenSSLErrorString()); + } + return context->CreateBigNum(std::move(order)); +} + +// Returns the cofactor of the group. +StatusOr<BigNum> CreateCofactor(const EC_GROUP* group, Context* context) { + BIGNUM* bn = BN_new(); + if (bn == nullptr) { + return InternalError( + "ECGroup::CreateCofactor - Could not create BIGNUM. " + + OpenSSLErrorString()); + } + BigNum::BignumPtr cofactor = BigNum::BignumPtr(bn); + if (EC_GROUP_get_cofactor(group, cofactor.get(), context->GetBnCtx()) != 1) { + return InternalError( + "ECGroup::CreateCofactor - Could not get cofactor. " + + OpenSSLErrorString()); + } + return context->CreateBigNum(std::move(cofactor)); +} + +// Returns the parameters that define the curve. For more information, see +// https://en.wikipedia.org/wiki/Elliptic-curve_cryptography#Domain_parameters. +StatusOr<ECGroup::CurveParams> CreateCurveParams(const EC_GROUP* group, + Context* context) { + BIGNUM* bn1 = BN_new(); + BIGNUM* bn2 = BN_new(); + BIGNUM* bn3 = BN_new(); + if (bn1 == nullptr || bn2 == nullptr || bn3 == nullptr) { + return InternalError( + "ECGroup::CreateCurveParams - Could not create BIGNUM. " + + OpenSSLErrorString()); + } + BigNum::BignumPtr p = BigNum::BignumPtr(bn1); + BigNum::BignumPtr a = BigNum::BignumPtr(bn2); + BigNum::BignumPtr b = BigNum::BignumPtr(bn3); + if (EC_GROUP_get_curve_GFp(group, p.get(), a.get(), b.get(), + context->GetBnCtx()) != 1) { + return InternalError( + "ECGroup::CreateCurveParams - Could not get params. " + + OpenSSLErrorString()); + } + BigNum p_bn = context->CreateBigNum(std::move(p)); + if (!p_bn.IsPrime()) { + return InternalError( + "ECGroup::CreateCurveParams - p is not prime. " + OpenSSLErrorString()); + } + return ECGroup::CurveParams{std::move(p_bn), + context->CreateBigNum(std::move(a)), + context->CreateBigNum(std::move(b))}; +} + +// Returns (p - 1) / 2 where p is a curve-defining parameter. +BigNum GetPMinusOneOverTwo(const ECGroup::CurveParams& curve_params, + Context* context) { + return (curve_params.p - context->One()) / context->Two(); +} + +} // namespace + +ECGroup::ECGroup(Context* context, ECGroupPtr group, BigNum order, + BigNum cofactor, CurveParams curve_params, + BigNum p_minus_one_over_two) + : context_(context), + group_(std::move(group)), + order_(std::move(order)), + cofactor_(std::move(cofactor)), + curve_params_(std::move(curve_params)), + p_minus_one_over_two_(std::move(p_minus_one_over_two)) {} + +StatusOr<ECGroup> ECGroup::Create(int curve_id, Context* context) { + ASSIGN_OR_RETURN(ECGroupPtr g, CreateGroup(curve_id)); + ASSIGN_OR_RETURN(BigNum order, CreateOrder(g.get(), context)); + ASSIGN_OR_RETURN(BigNum cofactor, CreateCofactor(g.get(), context)); + ASSIGN_OR_RETURN(CurveParams params, CreateCurveParams(g.get(), context)); + BigNum p_minus_one_over_two = GetPMinusOneOverTwo(params, context); + return ECGroup(context, std::move(g), std::move(order), std::move(cofactor), + std::move(params), std::move(p_minus_one_over_two)); +} + +BigNum ECGroup::GeneratePrivateKey() const { + return context_->GenerateRandBetween(context_->One(), order_); +} + +Status ECGroup::CheckPrivateKey(const BigNum& priv_key) const { + if (context_->Zero() >= priv_key || priv_key >= order_) { + return InvalidArgumentError( + "The given key is out of bounds, needs to be in [1, order) instead."); + } + return OkStatus(); +} + +StatusOr<ECPoint> ECGroup::GetPointByHashingToCurveInternal( + const BigNum& x) const { + BigNum mod_x = x.Mod(curve_params_.p); + BigNum y2 = ComputeYSquare(mod_x); + if (IsSquare(y2)) { + BigNum sqrt = y2.ModSqrt(curve_params_.p); + if (sqrt.IsBitSet(0)) { + return CreateECPoint(mod_x, sqrt.ModNegate(curve_params_.p)); + } + return CreateECPoint(mod_x, sqrt); + } + return InternalError("Could not hash x to the curve."); +} + +StatusOr<ECPoint> ECGroup::GetPointByHashingToCurveSha256( + const std::string& m) const { + BigNum x = context_->RandomOracleSha256(m, curve_params_.p); + while (true) { + auto status_or_point = GetPointByHashingToCurveInternal(x); + if (status_or_point.ok()) { + return status_or_point; + } + x = context_->RandomOracleSha256(x.ToBytes(), curve_params_.p); + } +} + +StatusOr<ECPoint> ECGroup::GetPointByHashingToCurveSha512( + const std::string& m) const { + BigNum x = context_->RandomOracleSha512(m, curve_params_.p); + while (true) { + auto status_or_point = GetPointByHashingToCurveInternal(x); + if (status_or_point.ok()) { + return status_or_point; + } + x = context_->RandomOracleSha512(x.ToBytes(), curve_params_.p); + } +} + +BigNum ECGroup::ComputeYSquare(const BigNum& x) const { + return (x.Exp(context_->Three()) + curve_params_.a * x + curve_params_.b) + .Mod(curve_params_.p); +} + +bool ECGroup::IsValid(const ECPoint& point) const { + if (!IsOnCurve(point) || IsAtInfinity(point)) { + return false; + } + return true; +} + +bool ECGroup::IsOnCurve(const ECPoint& point) const { + return 1 == EC_POINT_is_on_curve(group_.get(), point.point_.get(), + context_->GetBnCtx()); +} + +bool ECGroup::IsAtInfinity(const ECPoint& point) const { + return 1 == EC_POINT_is_at_infinity(group_.get(), point.point_.get()); +} + +bool ECGroup::IsSquare(const BigNum& q) const { + return q.ModExp(p_minus_one_over_two_, curve_params_.p).IsOne(); +} + +StatusOr<ECPoint> ECGroup::GetFixedGenerator() const { + const EC_POINT* ssl_generator = EC_GROUP_get0_generator(group_.get()); + EC_POINT* dup_ssl_generator = EC_POINT_dup(ssl_generator, group_.get()); + if (dup_ssl_generator == nullptr) { + return InternalError(OpenSSLErrorString()); + } + return ECPoint(group_.get(), context_->GetBnCtx(), + ECPoint::ECPointPtr(dup_ssl_generator)); +} + +StatusOr<ECPoint> ECGroup::GetRandomGenerator() const { + ASSIGN_OR_RETURN(ECPoint generator, GetFixedGenerator()); + return generator.Mul(context_->GenerateRandBetween(context_->One(), order_)); +} + +StatusOr<ECPoint> ECGroup::CreateECPoint(const BigNum& x, + const BigNum& y) const { + ECPoint point = ECPoint(group_.get(), context_->GetBnCtx(), x, y); + if (!IsValid(point)) { + return InvalidArgumentError( + "ECGroup::CreateECPoint(x,y) - The point is not valid."); + } + return std::move(point); +} + +StatusOr<ECPoint> ECGroup::CreateECPoint(const std::string& bytes) const { + auto raw_ec_point_ptr = EC_POINT_new(group_.get()); + if (raw_ec_point_ptr == nullptr) { + return InternalError("ECGroup::CreateECPoint: Failed to create point."); + } + ECPoint::ECPointPtr point(raw_ec_point_ptr); + if (EC_POINT_oct2point(group_.get(), point.get(), + reinterpret_cast<const unsigned char*>(bytes.data()), + bytes.size(), context_->GetBnCtx()) != 1) { + return InvalidArgumentError( + "ECGroup::CreateECPoint(string) - Could not decode point.\n" + OpenSSLErrorString()); + } + + ECPoint ec_point(group_.get(), context_->GetBnCtx(), std::move(point)); + if (!IsValid(ec_point)) { + return InvalidArgumentError( + "ECGroup::CreateECPoint(string) - Decoded point is not valid."); + } + return std::move(ec_point); +} + +StatusOr<ECPoint> ECGroup::GetPointAtInfinity() const { + EC_POINT* new_point = EC_POINT_new(group_.get()); + if (new_point == nullptr) { + return InternalError( + "ECGroup::GetPointAtInfinity() - Could not create new point."); + } + ECPoint::ECPointPtr point(new_point); + if (EC_POINT_set_to_infinity(group_.get(), point.get()) != 1) { + return InternalError( + "ECGroup::GetPointAtInfinity() - Could not get point at infinity."); + } + ECPoint ec_point(group_.get(), context_->GetBnCtx(), std::move(point)); + return std::move(ec_point); +} + +} // namespace private_join_and_compute
diff --git a/third_party/private-join-and-compute/src/crypto/ec_group.h b/third_party/private-join-and-compute/src/crypto/ec_group.h new file mode 100644 index 0000000..a1884fb --- /dev/null +++ b/third_party/private-join-and-compute/src/crypto/ec_group.h
@@ -0,0 +1,149 @@ +/* + * Copyright 2019 Google Inc. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef CRYPTO_EC_GROUP_H_ +#define CRYPTO_EC_GROUP_H_ + +#include <memory> +#include <string> + +#include "third_party/private-join-and-compute/src/crypto/big_num.h" +#include "third_party/private-join-and-compute/src/crypto/context.h" +#include "third_party/private-join-and-compute/src/crypto/openssl.inc" +#include "third_party/private-join-and-compute/src/util/status.inc" + +namespace private_join_and_compute { + +class ECPoint; + +// Wrapper class for openssl EC_GROUP. +class ECGroup { + public: + // Deletes a EC_GROUP. + class ECGroupDeleter { + public: + void operator()(EC_GROUP* group) { EC_GROUP_free(group); } + }; + typedef std::unique_ptr<EC_GROUP, ECGroupDeleter> ECGroupPtr; + + // Constructs a new ECGroup object for the given named curve id. + // See openssl header obj_mac.h for the available built-in curves. + // Use a well-known prime curve such as NID_secp224r1 recommended by NIST. + // Returns INTERNAL error code if there is a failure in crypto operations. + // Security: this function is secure only for prime order curves. + // (All supported curves in BoringSSL have prime order.) + static StatusOr<ECGroup> Create(int curve_id, Context* context); + + // Generates a new private key. The private key is a cryptographically strong + // pseudo-random number in the range (0, order). + BigNum GeneratePrivateKey() const; + + // Verifies that the random key is a valid number in the range (0, order). + // Returns Status::OK if the key is valid, otherwise returns INVALID_ARGUMENT. + Status CheckPrivateKey(const BigNum& priv_key) const; + + // Hashes m to a point on the elliptic curve y^2 = x^3 + ax + b over a + // prime field using SHA256 with "try-and-increment" method. + // See https://crypto.stanford.edu/~dabo/papers/bfibe.pdf, Section 5.2. + // Returns an INVALID_ARGUMENT error code if an error occurs. + // + // Security: The number of operations required to hash a string depends on the + // string, which could lead to a timing attack. + // Security: This function is only secure for curves of prime order. + StatusOr<ECPoint> GetPointByHashingToCurveSha256(const std::string& m) const; + + // Hashes m to a point on the elliptic curve y^2 = x^3 + ax + b over a + // prime field using SHA512. + // Returns an INVALID_ARGUMENT error code if an error occurs. + // + // Security: The number of operations required to hash a string depends on the + // string, which could lead to a timing attack. + StatusOr<ECPoint> GetPointByHashingToCurveSha512(const std::string& m) const; + + // Returns y^2 for the given x. The returned value is computed as x^3 + ax + b + // mod p, where a and b are the parameters of the curve. + BigNum ComputeYSquare(const BigNum& x) const; + + // Returns a fixed generator for this group. + // Returns an INTERNAL error code if it fails. + StatusOr<ECPoint> GetFixedGenerator() const; + + // Returns a random generator for this group. + // Returns an INTERNAL error code if it fails. + StatusOr<ECPoint> GetRandomGenerator() const; + + // Creates an ECPoint from the given string. + // Returns an INTERNAL error code if creating the point fails. + // Returns an INVALID_ARGUMENT error code if the created point is not in this + // group or if it is the point at infinity. + StatusOr<ECPoint> CreateECPoint(const std::string& bytes) const; + + // The parameters describing an elliptic curve given by the equation + // y^2 = x^3 + a * x + b over a prime field Fp. + struct CurveParams { + BigNum p; + BigNum a; + BigNum b; + }; + + // Returns the order. + const BigNum& GetOrder() const { return order_; } + + // Returns the cofactor. + const BigNum& GetCofactor() const { return cofactor_; } + + // Creates an ECPoint which is the identity. + StatusOr<ECPoint> GetPointAtInfinity() const; + + private: + ECGroup(Context* context, ECGroupPtr group, BigNum order, BigNum cofactor, + CurveParams curve_params, BigNum p_minus_one_over_two); + + // Creates an ECPoint object with the given x, y affine coordinates. + // Returns an INVALID_ARGUMENT error code if the point (x, y) is not in this + // group or if it is the point at infinity. + StatusOr<ECPoint> CreateECPoint(const BigNum& x, const BigNum& y) const; + + // Returns true if q is a quadratic residue modulo curve_params_.p_. + bool IsSquare(const BigNum& q) const; + + // Checks if the given point is valid. Returns false if the point is not in + // the group or if it is the point is at infinity. + bool IsValid(const ECPoint& point) const; + + // Returns true if the given point is in the group. + bool IsOnCurve(const ECPoint& point) const; + + // Returns true if the given point is at infinity. + bool IsAtInfinity(const ECPoint& point) const; + + Context* context_; + ECGroupPtr group_; + // The order of this group. + BigNum order_; + // The cofactor of this group. + BigNum cofactor_; + // The parameters of the curve. These values are used to hash a number to a + // point on the curve. + CurveParams curve_params_; + // Constant used to evaluate if a number is a quadratic residue. + BigNum p_minus_one_over_two_; + + StatusOr<ECPoint> GetPointByHashingToCurveInternal(const BigNum& x) const; +}; + +} // namespace private_join_and_compute + +#endif // CRYPTO_EC_GROUP_H_
diff --git a/third_party/private-join-and-compute/src/crypto/ec_point.cc b/third_party/private-join-and-compute/src/crypto/ec_point.cc new file mode 100644 index 0000000..b1ca558d --- /dev/null +++ b/third_party/private-join-and-compute/src/crypto/ec_point.cc
@@ -0,0 +1,119 @@ +/* + * Copyright 2019 Google Inc. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "third_party/private-join-and-compute/src/crypto/ec_point.h" + +#include <vector> + +#include "third_party/private-join-and-compute/src/chromium_patch.h" +#include "third_party/private-join-and-compute/src/crypto/big_num.h" +#include "third_party/private-join-and-compute/src/crypto/context.h" +#include "third_party/private-join-and-compute/src/crypto/openssl.inc" +#include "third_party/private-join-and-compute/src/util/status.inc" + +namespace private_join_and_compute { + +ECPoint::ECPoint(const EC_GROUP* group, BN_CTX* bn_ctx) + : bn_ctx_(bn_ctx), group_(group) { + point_ = ECPointPtr(CHECK_NOTNULL(EC_POINT_new(group_))); +} + +ECPoint::ECPoint(const EC_GROUP* group, BN_CTX* bn_ctx, const BigNum& x, + const BigNum& y) + : ECPoint::ECPoint(group, bn_ctx) { + CRYPTO_CHECK(1 == EC_POINT_set_affine_coordinates_GFp( + group_, point_.get(), x.GetConstBignumPtr(), + y.GetConstBignumPtr(), bn_ctx_)); +} + +ECPoint::ECPoint(const EC_GROUP* group, BN_CTX* bn_ctx, ECPointPtr point) + : ECPoint::ECPoint(group, bn_ctx) { + point_ = std::move(point); +} + +StatusOr<std::string> ECPoint::ToBytesCompressed() const { + int length = EC_POINT_point2oct( + group_, point_.get(), POINT_CONVERSION_COMPRESSED, nullptr, 0, bn_ctx_); + std::vector<unsigned char> bytes(length); + if (0 == EC_POINT_point2oct(group_, point_.get(), POINT_CONVERSION_COMPRESSED, + bytes.data(), length, bn_ctx_)) { + return InternalError( + "EC_POINT_point2oct failed:" + OpenSSLErrorString()); + } + return std::string(reinterpret_cast<char*>(bytes.data()), bytes.size()); +} + +StatusOr<std::string> ECPoint::ToBytesUnCompressed() const { + int length = EC_POINT_point2oct( + group_, point_.get(), POINT_CONVERSION_UNCOMPRESSED, nullptr, 0, bn_ctx_); + std::vector<unsigned char> bytes(length); + if (0 == EC_POINT_point2oct(group_, point_.get(), + POINT_CONVERSION_UNCOMPRESSED, bytes.data(), + length, bn_ctx_)) { + return InternalError( + "EC_POINT_point2oct failed:" + OpenSSLErrorString()); + } + return std::string(reinterpret_cast<char*>(bytes.data()), bytes.size()); +} + +StatusOr<ECPoint> ECPoint::Mul(const BigNum& scalar) const { + ECPoint r = ECPoint(group_, bn_ctx_); + if (1 != EC_POINT_mul(group_, r.point_.get(), nullptr, point_.get(), + scalar.GetConstBignumPtr(), bn_ctx_)) { + return InternalError( + "EC_POINT_mul failed:" + OpenSSLErrorString()); + } + return std::move(r); +} + +StatusOr<ECPoint> ECPoint::Add(const ECPoint& point) const { + ECPoint r = ECPoint(group_, bn_ctx_); + if (1 != EC_POINT_add(group_, r.point_.get(), point_.get(), + point.point_.get(), bn_ctx_)) { + return InternalError( + "EC_POINT_add failed:" + OpenSSLErrorString()); + } + return std::move(r); +} + +StatusOr<ECPoint> ECPoint::Clone() const { + ECPoint r = ECPoint(group_, bn_ctx_); + if (1 != EC_POINT_copy(r.point_.get(), point_.get())) { + return InternalError( + "EC_POINT_copy failed:" + OpenSSLErrorString()); + } + return std::move(r); +} + +StatusOr<ECPoint> ECPoint::Inverse() const { + // Create a copy of this. + ASSIGN_OR_RETURN(ECPoint inv, Clone()); + // Invert the copy in-place. + if (1 != EC_POINT_invert(group_, inv.point_.get(), bn_ctx_)) { + return InternalError( + "EC_POINT_invert failed:" + OpenSSLErrorString()); + } + return std::move(inv); +} + +bool ECPoint::IsPointAtInfinity() const { + return EC_POINT_is_at_infinity(group_, point_.get()); +} + +bool ECPoint::CompareTo(const ECPoint& point) const { + return 0 == EC_POINT_cmp(group_, point_.get(), point.point_.get(), bn_ctx_); +} + +} // namespace private_join_and_compute
diff --git a/third_party/private-join-and-compute/src/crypto/ec_point.h b/third_party/private-join-and-compute/src/crypto/ec_point.h new file mode 100644 index 0000000..0fab463c --- /dev/null +++ b/third_party/private-join-and-compute/src/crypto/ec_point.h
@@ -0,0 +1,105 @@ +/* + * Copyright 2019 Google Inc. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef CRYPTO_EC_POINT_H_ +#define CRYPTO_EC_POINT_H_ + +#include <memory> +#include <string> + +#include "third_party/private-join-and-compute/src/crypto/openssl.inc" +#include "third_party/private-join-and-compute/src/util/status.inc" + +namespace private_join_and_compute { + +class BigNum; +class ECGroup; + +// Wrapper class for openssl EC_POINT. +class ECPoint { + public: + // Deletes an EC_POINT. + class ECPointDeleter { + public: + void operator()(EC_POINT* point) { EC_POINT_clear_free(point); } + }; + typedef std::unique_ptr<EC_POINT, ECPointDeleter> ECPointPtr; + + // ECPoint is movable. + ECPoint(ECPoint&& that) = default; + ECPoint& operator=(ECPoint&& that) = default; + + // ECPoint is not copyable. Use Clone to copy, instead. + explicit ECPoint(const ECPoint& that) = delete; + ECPoint& operator=(const ECPoint& that) = delete; + + // Converts this point to octet string in compressed form as defined in ANSI + // X9.62 ECDSA. + StatusOr<std::string> ToBytesCompressed() const; + + // Allows faster conversions than ToBytesCompressed but doubles the size of + // the serialized point. + StatusOr<std::string> ToBytesUnCompressed() const; + + // Returns an ECPoint whose value is (this * scalar). + // Returns an INTERNAL error code if it fails. + StatusOr<ECPoint> Mul(const BigNum& scalar) const; + + // Returns an ECPoint whose value is (this + point). + // Returns an INTERNAL error code if it fails. + StatusOr<ECPoint> Add(const ECPoint& point) const; + + // Returns an ECPoint whose value is (- this), the additive inverse of this. + // Returns an INTERNAL error code if it fails. + StatusOr<ECPoint> Inverse() const; + + // Returns "true" if the value of this ECPoint is the point-at-infinity. + // (The point-at-infinity is the additive unit in the EC group). + bool IsPointAtInfinity() const; + + // Returns true if this equals point, false otherwise. + bool CompareTo(const ECPoint& point) const; + + // Returns an ECPoint that is a copy of this. + StatusOr<ECPoint> Clone() const; + + private: + // Creates an ECPoint on the given group; + ECPoint(const EC_GROUP* group, BN_CTX* bn_ctx); + + // Creates an ECPoint on the given group from the given EC_POINT; + ECPoint(const EC_GROUP* group, BN_CTX* bn_ctx, ECPointPtr point); + + // Creates an ECPoint object with the given x, y affine coordinates. + ECPoint(const EC_GROUP* group, BN_CTX* bn_ctx, const BigNum& x, + const BigNum& y); + + BN_CTX* bn_ctx_; + const EC_GROUP* group_; + ECPointPtr point_; + + // ECGroup is a factory for ECPoint. + friend class ECGroup; +}; + +inline bool operator==(const ECPoint& a, const ECPoint& b) { + return a.CompareTo(b); +} + +inline bool operator!=(const ECPoint& a, const ECPoint& b) { return !(a == b); } + +} // namespace private_join_and_compute + +#endif // CRYPTO_EC_POINT_H_
diff --git a/third_party/private-join-and-compute/src/crypto/openssl.inc b/third_party/private-join-and-compute/src/crypto/openssl.inc new file mode 100644 index 0000000..8daa6489 --- /dev/null +++ b/third_party/private-join-and-compute/src/crypto/openssl.inc
@@ -0,0 +1,29 @@ +/* + * Copyright 2019 Google Inc. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +// Contains all the OpenSSL includes we use. + +#include <openssl/aead.h> +#include <openssl/bn.h> +#include <openssl/buffer.h> +#include <openssl/crypto.h> +#include <openssl/ec.h> +#include <openssl/err.h> +#include <openssl/evp.h> +#include <openssl/hmac.h> +#include <openssl/obj_mac.h> +#include <openssl/ossl_typ.h> +#include <openssl/rand.h> +#include <openssl/sha.h>
diff --git a/third_party/private-join-and-compute/src/util/LICENSE b/third_party/private-join-and-compute/src/util/LICENSE new file mode 100644 index 0000000..7a4a3ea --- /dev/null +++ b/third_party/private-join-and-compute/src/util/LICENSE
@@ -0,0 +1,202 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. \ No newline at end of file
diff --git a/third_party/private-join-and-compute/src/util/canonical_errors.cc b/third_party/private-join-and-compute/src/util/canonical_errors.cc new file mode 100644 index 0000000..3c57bf4 --- /dev/null +++ b/third_party/private-join-and-compute/src/util/canonical_errors.cc
@@ -0,0 +1,40 @@ +/* + * Copyright 2019 Google Inc. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "third_party/private-join-and-compute/src/util/canonical_errors.h" + +#include <string> + +#include "third_party/private-join-and-compute/src/util/status.h" + +namespace private_join_and_compute { + +Status InternalError(const std::string& message) { + return Status(private_join_and_compute::StatusCode::kInternal, message); +} + +Status InvalidArgumentError(const std::string& message) { + return Status(private_join_and_compute::StatusCode::kInvalidArgument, message); +} + +bool IsInternal(const Status& status) { + return status.code() == private_join_and_compute::StatusCode::kInternal; +} + +bool IsInvalidArgument(const Status& status) { + return status.code() == private_join_and_compute::StatusCode::kInvalidArgument; +} + +} // namespace private_join_and_compute
diff --git a/third_party/private-join-and-compute/src/util/canonical_errors.h b/third_party/private-join-and-compute/src/util/canonical_errors.h new file mode 100644 index 0000000..1577c7c --- /dev/null +++ b/third_party/private-join-and-compute/src/util/canonical_errors.h
@@ -0,0 +1,33 @@ +/* + * Copyright 2019 Google Inc. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef UTIL_CANONICAL_ERRORS_H_ +#define UTIL_CANONICAL_ERRORS_H_ + +#include <string> + +#include "third_party/private-join-and-compute/src/util/status.h" + +namespace private_join_and_compute { + +Status InternalError(const std::string& message); +Status InvalidArgumentError(const std::string& message); + +bool IsInternal(const Status& status); +bool IsInvalidArgument(const Status& status); + +} // namespace private_join_and_compute + +#endif // UTIL_CANONICAL_ERRORS_H_
diff --git a/third_party/private-join-and-compute/src/util/status.cc b/third_party/private-join-and-compute/src/util/status.cc new file mode 100644 index 0000000..263d5af --- /dev/null +++ b/third_party/private-join-and-compute/src/util/status.cc
@@ -0,0 +1,68 @@ +/* + * Copyright 2019 Google Inc. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "third_party/private-join-and-compute/src/util/status.h" + +#include <sstream> +#include <utility> + +namespace private_join_and_compute { + +Status::Status() : code_(private_join_and_compute::StatusCode::kOk), message_("") {} + +Status::Status(private_join_and_compute::StatusCode error, std::string error_message) + : code_(error), message_(std::move(error_message)) { + if (code_ == private_join_and_compute::StatusCode::kOk) { + message_.clear(); + } +} + +Status::Status(const Status& other) + : code_(other.code_), message_(other.message_) {} + +Status& Status::operator=(const Status& other) { + code_ = other.code_; + message_ = other.message_; + return *this; +} + +std::string Status::ToString() const { + if (code_ == private_join_and_compute::StatusCode::kOk) { + return "OK"; + } + std::ostringstream stringStream; + stringStream << code_ << ": " << message_; + return stringStream.str(); +} + +Status Annotate(const Status& s, const std::string& msg) { + if (s.ok() || msg.empty()) return s; + + std::string new_msg; + + if (s.message().empty()) { + new_msg = msg; + } else { + new_msg = s.message() + "; " + msg; + } + return Status(s.code(), new_msg); +} + +extern std::ostream& operator<<(std::ostream& os, const Status& other) { + os << other.ToString(); + return os; +} + +} // namespace private_join_and_compute
diff --git a/third_party/private-join-and-compute/src/util/status.h b/third_party/private-join-and-compute/src/util/status.h new file mode 100644 index 0000000..944af0b --- /dev/null +++ b/third_party/private-join-and-compute/src/util/status.h
@@ -0,0 +1,102 @@ +/* + * Copyright 2019 Google Inc. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef UTIL_STATUS_H_ +#define UTIL_STATUS_H_ + +#include <string> + +namespace private_join_and_compute { +enum StatusCode { + kOk = 0, + kCancelled = 1, + kUnknown = 2, + kInvalidArgument = 3, + kDeadlineExceeded = 4, + kNotFound = 5, + kAlreadyExists = 6, + kPermissionDenied = 7, + kResourceExhausted = 8, + kFailedPrecondition = 9, + kAborted = 10, + kOutOfRange = 11, + kUnimplemented = 12, + kInternal = 13, + kUnavailable = 14, + kDataLoss = 15, + kUnauthenticated = 16, + kDoNotUseReservedForFutureExpansionUseDefaultInSwitchInstead_ = 20 +}; + +// A Status is a combination of an error code and a string message (for non-OK +// error codes). +class Status { + public: + // Creates an OK status + Status(); + + // Make a Status from the specified error and message. + Status(private_join_and_compute::StatusCode error, std::string error_message); + + Status(const Status& other); + Status& operator=(const Status& other); + + // Some pre-defined Status objects + static Status OK() { + return Status(); + } + static Status UNKNOWN() { + return Status(private_join_and_compute::StatusCode::kUnknown, ""); + } + + // Accessors + bool ok() const { return code_ == private_join_and_compute::StatusCode::kOk; } + int error_code() const { return code_; } + private_join_and_compute::StatusCode code() const { return code_; } + const std::string& message() const { return message_; } + + bool operator==(const Status& x) const; + bool operator!=(const Status& x) const; + + // NoOp + void IgnoreError() const {} + + std::string ToString() const; + + private: + private_join_and_compute::StatusCode code_; + std::string message_; +}; + +inline bool Status::operator==(const Status& other) const { + return (this->code_ == other.code_) && (this->message_ == other.message_); +} + +inline bool Status::operator!=(const Status& other) const { + return !(*this == other); +} + +// Returns a Status that is identical to 's' except that the error_message() +// has been augmented by adding 'msg' to the end of the original error +// message. +Status Annotate(const Status& s, const std::string& msg); + +extern std::ostream& operator<<(std::ostream& os, const Status& other); + +inline Status OkStatus() { return Status(); } + +} // namespace private_join_and_compute + +#endif // UTIL_STATUS_H_
diff --git a/third_party/private-join-and-compute/src/util/status.inc b/third_party/private-join-and-compute/src/util/status.inc new file mode 100644 index 0000000..87aa9df --- /dev/null +++ b/third_party/private-join-and-compute/src/util/status.inc
@@ -0,0 +1,19 @@ +/* + * Copyright 2019 Google Inc. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "third_party/private-join-and-compute/src/util/canonical_errors.h" +#include "third_party/private-join-and-compute/src/util/status.h" +#include "third_party/private-join-and-compute/src/util/statusor.h" +#include "third_party/private-join-and-compute/src/util/status_macros.h"
diff --git a/third_party/private-join-and-compute/src/util/status_macros.h b/third_party/private-join-and-compute/src/util/status_macros.h new file mode 100644 index 0000000..7c0f162 --- /dev/null +++ b/third_party/private-join-and-compute/src/util/status_macros.h
@@ -0,0 +1,45 @@ +/* + * Copyright 2019 Google Inc. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef UTIL_STATUS_MACROS_H_ +#define UTIL_STATUS_MACROS_H_ + +#include "third_party/private-join-and-compute/src/chromium_patch.h" +#include "third_party/private-join-and-compute/src/util/status.h" +#include "third_party/private-join-and-compute/src/util/statusor.h" + +// Helper macro that checks if the right hand side (rexpression) evaluates to a +// StatusOr with Status OK, and if so assigns the value to the value on the left +// hand side (lhs), otherwise returns the error status. Example: +// ASSIGN_OR_RETURN(lhs, rexpression); +#define ASSIGN_OR_RETURN(lhs, rexpr) \ + PRIVACY_BLINDERS_ASSIGN_OR_RETURN_IMPL_( \ + PRIVACY_BLINDERS_STATUS_MACROS_IMPL_CONCAT_(status_or_value, __LINE__), \ + lhs, rexpr) + +// Internal helper. +#define PRIVACY_BLINDERS_ASSIGN_OR_RETURN_IMPL_(statusor, lhs, rexpr) \ + auto statusor = (rexpr); \ + if (UNLIKELY(!statusor.ok())) { \ + return std::move(statusor).status(); \ + } \ + lhs = std::move(statusor).ValueOrDie() + +// Internal helper for concatenating macro values. +#define PRIVACY_BLINDERS_STATUS_MACROS_IMPL_CONCAT_INNER_(x, y) x##y +#define PRIVACY_BLINDERS_STATUS_MACROS_IMPL_CONCAT_(x, y) \ + PRIVACY_BLINDERS_STATUS_MACROS_IMPL_CONCAT_INNER_(x, y) + +#endif // UTIL_STATUS_MACROS_H_
diff --git a/third_party/private-join-and-compute/src/util/statusor.cc b/third_party/private-join-and-compute/src/util/statusor.cc new file mode 100644 index 0000000..08eb1f0 --- /dev/null +++ b/third_party/private-join-and-compute/src/util/statusor.cc
@@ -0,0 +1,49 @@ +/* + * Copyright 2019 Google Inc. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "third_party/private-join-and-compute/src/util/statusor.h" + +#include "third_party/private-join-and-compute/src/chromium_patch.h" +#include "third_party/private-join-and-compute/src/util/status.h" + +namespace private_join_and_compute { +namespace internal { + +static const char* kInvalidStatusCtorArgMessage = + "Status::OK is not a valid constructor argument to StatusOr<T>"; +static const char* kNullObjectCtorArgMessage = + "nullptr is not a valid constructor argument to StatusOr<T*>"; + +Status StatusOrHelper::HandleInvalidStatusCtorArg() { + LOG(DFATAL) << kInvalidStatusCtorArgMessage; + // In optimized builds, we will fall back to private_join_and_compute::StatusCode::kInternal. + return Status(::private_join_and_compute::StatusCode::kInternal, + kInvalidStatusCtorArgMessage); +} + +Status StatusOrHelper::HandleNullObjectCtorArg() { + LOG(DFATAL) << kNullObjectCtorArgMessage; + // In optimized builds, we will fall back to + // ::private_join_and_compute::StatusCode::kInternal. + return Status(::private_join_and_compute::StatusCode::kInternal, kNullObjectCtorArgMessage); +} + +void StatusOrHelper::Crash(const Status& status) { + LOG(FATAL) << "Attempting to fetch value instead of handling error " + << status; +} + +} // namespace internal +} // namespace private_join_and_compute
diff --git a/third_party/private-join-and-compute/src/util/statusor.h b/third_party/private-join-and-compute/src/util/statusor.h new file mode 100644 index 0000000..a1666d5 --- /dev/null +++ b/third_party/private-join-and-compute/src/util/statusor.h
@@ -0,0 +1,262 @@ +/* + * Copyright 2019 Google Inc. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +// StatusOr<T> is the union (w/o using Union) of a Status object and a T object. +// StatusOr models the concept of an object that is either a usable value, or an +// error Status explaining why such a value is not present. To this end, +// StatusOr<T> does not allow its Status value to be Status::OK. Furthermore, +// the value of a StatusOr<T*> must not be null. This is enforced by a debug +// check in most cases, but even when it is not, clients must not set the value +// to null. +// +// The primary use-case for StatusOr<T> is as the return value of a function +// which may fail. +// +// Example client usage for a StatusOr<T>, where T is not a pointer: +// +// StatusOr<float> result = DoBigCalculationThatCouldFail(); +// if (result.ok()) { +// float answer = result.ValueOrDie(); +// printf("Big calculation yielded: %f", answer); +// } else { +// LOG(ERROR) << result.status(); +// } +// +// Example client usage for a StatusOr<T*>: +// +// StatusOr<Foo*> result = FooFactory::MakeNewFoo(arg); +// if (result.ok()) { +// std::unique_ptr<Foo> foo(result.ValueOrDie()); +// foo->DoSomethingCool(); +// } else { +// LOG(ERROR) << result.status(); +// } +// +// Example client usage for a StatusOr<std::unique_ptr<T>>: +// +// StatusOr<std::unique_ptr<Foo>> result = FooFactory::MakeNewFoo(arg); +// if (result.ok()) { +// std::unique_ptr<Foo> foo = std::move(result.ValueOrDie()); +// foo->DoSomethingCool(); +// } else { +// LOG(ERROR) << result.status(); +// } +// +// Example factory implementation returning StatusOr<T*>: +// +// StatusOr<Foo*> FooFactory::MakeNewFoo(int arg) { +// if (arg <= 0) { +// return Status(::private_join_and_compute::StatusCode::kInvalidArgument, +// "Arg must be positive"); +// } else { +// return new Foo(arg); +// } +// } +// + +#ifndef UTIL_STATUSOR_H_ +#define UTIL_STATUSOR_H_ + +#include <memory> +#include <new> +#include <utility> + +#include "third_party/private-join-and-compute/src/util/status.h" // IWYU pragma: export // for Status + +namespace private_join_and_compute { + + template <typename T> + class StatusOr { + public: + // Construct a new StatusOr with Status::UNKNOWN status + StatusOr(); + + // Construct a new StatusOr with the given non-ok status. After calling + // this constructor, calls to ValueOrDie() will CHECK-fail. + // + // NOTE: Not explicit - we want to use StatusOr<T> as a return + // value, so it is convenient and sensible to be able to do 'return + // Status()' when the return type is StatusOr<T>. + // + // REQUIRES: status != Status::OK. This requirement is DCHECKed. + // In optimized builds, passing Status::OK here will have the effect + // of passing PosixErrorSpace::EINVAL as a fallback. + StatusOr(const Status& status); // NOLINT - no explicit + + // Construct a new StatusOr with the given value. If T is a plain pointer, + // value must not be nullptr. After calling this constructor, calls to + // ValueOrDie() will succeed, and calls to status() will return OK. + // + // NOTE: Not explicit - we want to use StatusOr<T> as a return type + // so it is convenient and sensible to be able to do 'return T()' + // when the return type is StatusOr<T>. + // + // REQUIRES: if T is a plain pointer, value != nullptr. This requirement is + // DCHECKed. In optimized builds, passing a nullptr pointer here will have + // the effect of passing ::private_join_and_compute::StatusCode::kInternal as a fallback. + StatusOr(const T& value); // NOLINT - no explicit + + // Copy constructor. + StatusOr(const StatusOr& other); + + // Assignment operator. + StatusOr& operator=(const StatusOr& other); + + // Move constructor and move-assignment operator. + StatusOr(StatusOr&& other) = default; + StatusOr& operator=(StatusOr&& other) = default; + + // Rvalue-reference overloads of the other constructors and assignment + // operators, to support move-only types and avoid unnecessary copying. + StatusOr(T&& value); // NOLINT - no explicit + + // Returns a reference to our status. If this contains a T, then + // returns Status::OK. + const Status& status() const; + + // Returns this->status().ok() + bool ok() const; + + // Returns a reference to our current value, or CHECK-fails if !this->ok(). + const T& ValueOrDie() const&; + T& ValueOrDie() &; + const T&& ValueOrDie() const&&; + T&& ValueOrDie() &&; + + // Ignores any errors. This method does nothing except potentially suppress + // complaints from any tools that are checking that errors are not dropped on + // the floor. + void IgnoreError() const {} + + private: + // absl::variant<Status, T> variant_; + Status status_; + std::unique_ptr<T> value_; +}; + +//////////////////////////////////////////////////////////////////////////////// +// Implementation details for StatusOr<T> + +namespace internal { + +class StatusOrHelper { + public: + // Move type-agnostic error handling to the .cc. + static Status HandleInvalidStatusCtorArg(); + static Status HandleNullObjectCtorArg(); + static void Crash(const Status& status); + + // Customized behavior for StatusOr<T> vs. StatusOr<T*> + template <typename T> + struct Specialize; +}; + +template <typename T> +struct StatusOrHelper::Specialize { + // For non-pointer T, a reference can never be nullptr. + static inline bool IsValueNull(const T& t) { return false; } +}; + +template <typename T> +struct StatusOrHelper::Specialize<T*> { + static inline bool IsValueNull(const T* t) { return t == nullptr; } +}; + +} // namespace internal + +template <typename T> +inline StatusOr<T>::StatusOr() : status_(Status::UNKNOWN()), value_(nullptr) {} + +template <typename T> +inline StatusOr<T>::StatusOr(const Status& status) + : status_(status), value_(nullptr) { + if (status.ok()) { + status_ = internal::StatusOrHelper::HandleInvalidStatusCtorArg(); + } +} + +template <typename T> +inline StatusOr<T>::StatusOr(const T& value) + : status_(Status::OK()), value_(new T(value)) { + if (internal::StatusOrHelper::Specialize<T>::IsValueNull(*value_)) { + status_ = internal::StatusOrHelper::HandleNullObjectCtorArg(); + } +} + +template <typename T> +inline StatusOr<T>::StatusOr(const StatusOr& other) + : status_(other.status_), value_(new T(*other.value_)) {} + +template <typename T> +inline StatusOr<T>& StatusOr<T>::operator=(const StatusOr<T>& other) { + status_ = other.status_; + value_.reset(new T(*other.value_)); + return *this; +} + + +template <typename T> +inline StatusOr<T>::StatusOr(T&& value) + : status_(Status::OK()), value_(new T(std::forward<T>(value))) { + if (internal::StatusOrHelper::Specialize<T>::IsValueNull(*value_)) { + status_ = internal::StatusOrHelper::HandleNullObjectCtorArg(); + } +} + +template <typename T> +inline const Status& StatusOr<T>::status() const { + return status_; +} + +template <typename T> +inline bool StatusOr<T>::ok() const { + return status_.ok(); +} + +template <typename T> +inline const T& StatusOr<T>::ValueOrDie() const& { + if (value_ == nullptr) { + internal::StatusOrHelper::Crash(status()); + } + return *value_; +} + +template <typename T> +inline T& StatusOr<T>::ValueOrDie() & { + if (value_ == nullptr) { + internal::StatusOrHelper::Crash(status()); + } + return *value_; +} + +template <typename T> +inline const T&& StatusOr<T>::ValueOrDie() const&& { + if (value_ == nullptr) { + internal::StatusOrHelper::Crash(status()); + } + return std::move(*value_); +} + +template <typename T> +inline T&& StatusOr<T>::ValueOrDie() && { + if (value_ == nullptr) { + internal::StatusOrHelper::Crash(status()); + } + return std::move(*value_); +} + +} // namespace private_join_and_compute + +#endif // UTIL_STATUSOR_H_
diff --git a/tools/clang/scripts/build.py b/tools/clang/scripts/build.py index 4637e56d..b83e374 100755 --- a/tools/clang/scripts/build.py +++ b/tools/clang/scripts/build.py
@@ -245,16 +245,6 @@ args.gcc_toolchain = gcc_dir -def SetMacXcodePath(): - """Set DEVELOPER_DIR to the path to hermetic Xcode.app on Mac OS X.""" - if sys.platform != 'darwin': - return - - xcode_path = os.path.join(CHROMIUM_DIR, 'build', 'mac_files', 'Xcode.app') - if os.path.exists(xcode_path): - os.environ['DEVELOPER_DIR'] = xcode_path - - def VerifyVersionOfBuiltClangMatchesVERSION(): """Checks that `clang --version` outputs RELEASE_VERSION. If this fails, update.RELEASE_VERSION is out-of-date and needs to be updated (possibly @@ -413,10 +403,6 @@ WriteStampFile('', STAMP_FILE) WriteStampFile('', FORCE_HEAD_REVISION_FILE) - # DEVELOPER_DIR needs to be set when Xcode isn't in a standard location - # and xcode-select wasn't run. - SetMacXcodePath() - AddCMakeToPath(args) DeleteChromeToolsShim()
diff --git a/tools/metrics/histograms/histograms.xml b/tools/metrics/histograms/histograms.xml index 6c7bf63..9e7e6221 100644 --- a/tools/metrics/histograms/histograms.xml +++ b/tools/metrics/histograms/histograms.xml
@@ -98735,6 +98735,52 @@ <summary>True when a service worker times out 5 mins after request.</summary> </histogram> +<histogram name="PaymentRequest.TimeToCheckout.Completed" units="ms"> + <owner>sahel@chromium.org</owner> + <summary> + Records the time between a payment request .show() and its completion. + </summary> +</histogram> + +<histogram name="PaymentRequest.TimeToCheckout.Completed.Shown" units="ms"> +<!-- Name completed by histogram_suffixes name="PaymentRequestCompletedInstrument" --> + + <owner>sahel@chromium.org</owner> + <summary> + Records the time between a payment request .show() and its completion when + payment sheet is shown. + </summary> +</histogram> + +<histogram name="PaymentRequest.TimeToCheckout.Completed.SkippedShow" + units="ms"> +<!-- Name completed by histogram_suffixes name="PaymentRequestCompletedInstrument" --> + + <owner>sahel@chromium.org</owner> + <summary> + Records the time between a payment request .show() and its completion when + payment sheet is skipped. + </summary> +</histogram> + +<histogram name="PaymentRequest.TimeToCheckout.OtherAborted" units="ms"> + <owner>sahel@chromium.org</owner> + <summary> + Records the time between a payment request .show() and its termination by + any factors other than the user (e.g. merchant). + </summary> +</histogram> + +<histogram name="PaymentRequest.TimeToCheckout.UserAborted" units="ms"> +<!-- Name completed by histogram_suffixes name="PaymentRequestPaymentSheetShowStatus" --> + + <owner>sahel@chromium.org</owner> + <summary> + Records the time between a payment request .show() and its termination by + user. + </summary> +</histogram> + <histogram name="PaymentRequest.TransactionAmount.Completed" enum="PaymentRequestTransactionSize"> <owner>sahel@chromium.org</owner> @@ -166869,6 +166915,18 @@ <affected-histogram name="PasswordManager.FillingAssistance"/> </histogram_suffixes> +<histogram_suffixes name="PaymentRequestCompletedInstrument" separator="."> + <suffix name="BasicCard" + label="Request is completed using basic card method."/> + <suffix name="Google" + label="Request is completed using Google payment instrument."/> + <suffix name="Other" + label="Request is completed using other payment instruments."/> + <affected-histogram name="PaymentRequest.TimeToCheckout.Completed.Shown"/> + <affected-histogram + name="PaymentRequest.TimeToCheckout.Completed.SkippedShow"/> +</histogram_suffixes> + <histogram_suffixes name="PaymentRequestOutcome" separator="."> <suffix name="Completed" label="The Payment Request was completed"/> <suffix name="OtherAborted" @@ -166899,6 +166957,14 @@ name="PaymentRequest.NumberOfSuggestionsShown.ShippingAddress"/> </histogram_suffixes> +<histogram_suffixes name="PaymentRequestPaymentSheetShowStatus" separator="."> + <suffix name="BeforeShow" + label="Request is terminated before request.show()."/> + <suffix name="Shown" label="Payment sheet is shown."/> + <suffix name="SkippedShow" label="Payment sheet is skipped."/> + <affected-histogram name="PaymentRequest.TimeToCheckout.UserAborted"/> +</histogram_suffixes> + <histogram_suffixes name="PaymentRequestSection" separator="."> <suffix name="ContactInfo" label="For the contact info section of a Payment Request"/>
diff --git a/tools/traffic_annotation/bin/README.md b/tools/traffic_annotation/bin/README.md index 86b3073..bf22c1a 100644 --- a/tools/traffic_annotation/bin/README.md +++ b/tools/traffic_annotation/bin/README.md
@@ -74,5 +74,5 @@ The following two lines will be updated by the above script, and the modified README should be committed along with the updated .sha1 checksums. -CLANG_REVISION = '360094' -LASTCHANGE=ecda211dff8f3722704938f87637e0df657d15f1-refs/heads/master@{#659930} +CLANG_REVISION = 'f7e52fbdb5a7af8ea0808e98458b497125a5eca1' +LASTCHANGE=960750f9b8c7d487a37d9b63c4a0a5193cf96a14-refs/heads/master@{#685530}
diff --git a/tools/traffic_annotation/bin/linux64/traffic_annotation_auditor.sha1 b/tools/traffic_annotation/bin/linux64/traffic_annotation_auditor.sha1 index 36278a7b..c5c7d71 100644 --- a/tools/traffic_annotation/bin/linux64/traffic_annotation_auditor.sha1 +++ b/tools/traffic_annotation/bin/linux64/traffic_annotation_auditor.sha1
@@ -1 +1 @@ -73004f4964def13577f9d060d77908d51c30d521 \ No newline at end of file +1629fd24682e3c8f9d75b39c5f3e8ef94b706d3f \ No newline at end of file
diff --git a/tools/traffic_annotation/bin/win32/traffic_annotation_auditor.exe.sha1 b/tools/traffic_annotation/bin/win32/traffic_annotation_auditor.exe.sha1 index 8e82538..acc69746 100644 --- a/tools/traffic_annotation/bin/win32/traffic_annotation_auditor.exe.sha1 +++ b/tools/traffic_annotation/bin/win32/traffic_annotation_auditor.exe.sha1
@@ -1 +1 @@ -e3c00e2607fbe0d5758e60bc42c6802feacdea08 \ No newline at end of file +f39cb780904d05e8ccd443bb2c59efdf030c26b8 \ No newline at end of file
diff --git a/ui/base/clipboard/clipboard.cc b/ui/base/clipboard/clipboard.cc index c16ec5c..cac83b2a 100644 --- a/ui/base/clipboard/clipboard.cc +++ b/ui/base/clipboard/clipboard.cc
@@ -114,11 +114,11 @@ } switch (type) { - case ObjectType::CBF_TEXT: + case ObjectType::kText: WriteText(&(params[0].front()), params[0].size()); break; - case ObjectType::CBF_HTML: + case ObjectType::kHtml: if (params.size() == 2) { if (params[1].empty()) return; @@ -129,20 +129,20 @@ } break; - case ObjectType::CBF_RTF: + case ObjectType::kRtf: WriteRTF(&(params[0].front()), params[0].size()); break; - case ObjectType::CBF_BOOKMARK: + case ObjectType::kBookmark: WriteBookmark(&(params[0].front()), params[0].size(), &(params[1].front()), params[1].size()); break; - case ObjectType::CBF_WEBKIT: + case ObjectType::kWebkit: WriteWebSmartPaste(); break; - case ObjectType::CBF_SMBITMAP: { + case ObjectType::kBitmap: { // Usually, the params are just UTF-8 strings. However, for images, // ScopedClipboardWriter actually sizes the buffer to sizeof(SkBitmap*), // aliases the contents of the vector to a SkBitmap**, and writes the @@ -152,7 +152,7 @@ break; } - case ObjectType::CBF_DATA: + case ObjectType::kData: WriteData(ClipboardFormatType::Deserialize( std::string(&(params[0].front()), params[0].size())), &(params[1].front()), params[1].size());
diff --git a/ui/base/clipboard/clipboard.h b/ui/base/clipboard/clipboard.h index 7897d74f..3c727a4 100644 --- a/ui/base/clipboard/clipboard.h +++ b/ui/base/clipboard/clipboard.h
@@ -165,7 +165,7 @@ // designation is shared across all OSes. The system-specific designation // is defined by ClipboardFormatType. A single ObjectType might be represented // by several system-specific ClipboardFormatTypes. For example, on Linux the - // CBF_TEXT ObjectType maps to "text/plain", "STRING", and several other + // kText ObjectType maps to "text/plain", "STRING", and several other // formats. On windows it maps to CF_UNICODETEXT. // // The order below is the order in which data will be written to the @@ -175,13 +175,13 @@ // the image, and the image's alt text. Having the types follow this order // maximizes the amount of data that can be extracted by various programs. enum class ObjectType { - CBF_SMBITMAP, // Bitmap from shared memory. - CBF_HTML, - CBF_RTF, - CBF_BOOKMARK, - CBF_TEXT, - CBF_WEBKIT, - CBF_DATA, // Arbitrary block of bytes. + kBitmap, // Bitmap from shared memory. + kHtml, + kRtf, + kBookmark, + kText, + kWebkit, + kData, // Arbitrary block of bytes. }; // ObjectMap is a map from ObjectType to associated data. @@ -189,20 +189,20 @@ // table summarizes what kind of data is stored for each key. // * indicates an optional argument. // - // Key Arguments Type + // Key Arguments Type // ------------------------------------- - // CBF_SMBITMAP bitmap A pointer to a SkBitmap. The caller must ensure - // the SkBitmap remains live for the duration of - // the WriteObjects call. - // CBF_HTML html char array - // url* char array - // CBF_RTF data byte array - // CBF_BOOKMARK html char array - // url char array - // CBF_TEXT text char array - // CBF_WEBKIT none empty vector - // CBF_DATA format char array - // data byte array + // kBitmap bitmap A pointer to a SkBitmap. The caller must ensure + // the SkBitmap remains live for the duration of + // the WriteObjects call. + // kHtml html char array + // url* char array + // kRtf data byte array + // kBookmark html char array + // url char array + // kText text char array + // kWebkit none empty vector + // kData format char array + // data byte array using ObjectMapParam = std::vector<char>; using ObjectMapParams = std::vector<ObjectMapParam>; using ObjectMap = base::flat_map<ObjectType, ObjectMapParams>;
diff --git a/ui/base/clipboard/clipboard_x11.cc b/ui/base/clipboard/clipboard_x11.cc index 20dbbc1..b89dc85 100644 --- a/ui/base/clipboard/clipboard_x11.cc +++ b/ui/base/clipboard/clipboard_x11.cc
@@ -686,7 +686,7 @@ x11_details_->TakeOwnershipOfSelection(type); if (type == ClipboardType::kCopyPaste) { - auto text_iter = objects.find(ObjectType::CBF_TEXT); + auto text_iter = objects.find(ObjectType::kText); if (text_iter != objects.end()) { x11_details_->CreateNewClipboardData(); const ObjectMapParams& params_vector = text_iter->second;
diff --git a/ui/base/clipboard/scoped_clipboard_writer.cc b/ui/base/clipboard/scoped_clipboard_writer.cc index 3a85270..7e2baa3 100644 --- a/ui/base/clipboard/scoped_clipboard_writer.cc +++ b/ui/base/clipboard/scoped_clipboard_writer.cc
@@ -28,7 +28,7 @@ Clipboard::ObjectMapParams parameters; parameters.push_back( Clipboard::ObjectMapParam(utf8_text.begin(), utf8_text.end())); - objects_[Clipboard::ObjectType::CBF_TEXT] = parameters; + objects_[Clipboard::ObjectType::kText] = parameters; } void ScopedClipboardWriter::WriteHTML(const base::string16& markup, @@ -44,14 +44,14 @@ source_url.end())); } - objects_[Clipboard::ObjectType::CBF_HTML] = parameters; + objects_[Clipboard::ObjectType::kHtml] = parameters; } void ScopedClipboardWriter::WriteRTF(const std::string& rtf_data) { Clipboard::ObjectMapParams parameters; parameters.push_back(Clipboard::ObjectMapParam(rtf_data.begin(), rtf_data.end())); - objects_[Clipboard::ObjectType::CBF_RTF] = parameters; + objects_[Clipboard::ObjectType::kRtf] = parameters; } void ScopedClipboardWriter::WriteBookmark(const base::string16& bookmark_title, @@ -65,7 +65,7 @@ parameters.push_back(Clipboard::ObjectMapParam(utf8_markup.begin(), utf8_markup.end())); parameters.push_back(Clipboard::ObjectMapParam(url.begin(), url.end())); - objects_[Clipboard::ObjectType::CBF_BOOKMARK] = parameters; + objects_[Clipboard::ObjectType::kBookmark] = parameters; } void ScopedClipboardWriter::WriteHyperlink(const base::string16& anchor_text, @@ -83,7 +83,7 @@ } void ScopedClipboardWriter::WriteWebSmartPaste() { - objects_[Clipboard::ObjectType::CBF_WEBKIT] = Clipboard::ObjectMapParams(); + objects_[Clipboard::ObjectType::kWebkit] = Clipboard::ObjectMapParams(); } void ScopedClipboardWriter::WriteImage(const SkBitmap& bitmap) { @@ -100,7 +100,7 @@ *reinterpret_cast<SkBitmap**>(&*packed_pointer.begin()) = bitmap_pointer; Clipboard::ObjectMapParams parameters; parameters.push_back(packed_pointer); - objects_[Clipboard::ObjectType::CBF_SMBITMAP] = parameters; + objects_[Clipboard::ObjectType::kBitmap] = parameters; } void ScopedClipboardWriter::WritePickledData( @@ -118,7 +118,7 @@ Clipboard::ObjectMapParams parameters; parameters.push_back(format_parameter); parameters.push_back(data_parameter); - objects_[Clipboard::ObjectType::CBF_DATA] = parameters; + objects_[Clipboard::ObjectType::kData] = parameters; } void ScopedClipboardWriter::WriteData(const std::string& type, @@ -128,7 +128,7 @@ Clipboard::ObjectMapParams parameters; parameters.push_back(type_parameter); parameters.push_back(data_parameter); - objects_[Clipboard::ObjectType::CBF_DATA] = parameters; + objects_[Clipboard::ObjectType::kData] = parameters; } void ScopedClipboardWriter::Reset() {
diff --git a/ui/file_manager/file_manager/foreground/elements/files_message_unittest.html b/ui/file_manager/file_manager/foreground/elements/files_message_unittest.html new file mode 100644 index 0000000..254f306b --- /dev/null +++ b/ui/file_manager/file_manager/foreground/elements/files_message_unittest.html
@@ -0,0 +1,5 @@ +<!DOCTYPE html> + +<link rel="import" href="chrome://file_manager_test/file_manager/foreground/elements/files_message.html"> + +<script src="files_message_unittest.js"> </script>
diff --git a/ui/file_manager/file_manager/foreground/elements/files_tooltip_unittest.html b/ui/file_manager/file_manager/foreground/elements/files_tooltip_unittest.html new file mode 100644 index 0000000..3d60e5f --- /dev/null +++ b/ui/file_manager/file_manager/foreground/elements/files_tooltip_unittest.html
@@ -0,0 +1,42 @@ +<!DOCTYPE html> +<style type="text/css"> + button { + display: flex; + height: 32px; + margin: 30px; + width: 32px; + } + + #container { + display: flex; + justify-content: space-between; + } + + files-tooltip { + background: yellow; + box-sizing: border-box; + position: absolute; + text-align: center; + width: 100px; + } +</style> + +<script src="chrome://file_manager_test/base/js/test_error_reporting.js"> </script> + +<link rel="import" href="chrome://file_manager_test/file_manager/foreground/elements/files_tooltip.html"> + +<script src="files_tooltip_unittest.js"> </script> +<body> + <!-- Targets for tooltip testing. --> + <div id="container"> + <button id="chocolate" aria-label="Chocolate!"></button> + <button id="cherries" aria-label="Cherries!"></button> + </div> + + <!-- Button without a tooltip. --> + <button id="other"></button> + + <!-- Polymer files tooltip element. --> + <files-tooltip></files-tooltip> + +</body>
diff --git a/ui/file_manager/file_manager/foreground/elements/files_tooltip_unittest.js b/ui/file_manager/file_manager/foreground/elements/files_tooltip_unittest.js new file mode 100644 index 0000000..62d63f5 --- /dev/null +++ b/ui/file_manager/file_manager/foreground/elements/files_tooltip_unittest.js
@@ -0,0 +1,124 @@ +// Copyright 2015 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +/** @type {Element} */ +let chocolateButton; + +/** @type {Element} */ +let cherriesButton; + +/** @type {Element} */ +let otherButton; + +/** @type {FilesTooltip|Element} */ +let tooltip; + +function setUp() { + chocolateButton = document.querySelector('#chocolate'); + cherriesButton = document.querySelector('#cherries'); + otherButton = document.querySelector('#other'); + + tooltip = document.querySelector('files-tooltip'); + tooltip.addTargets([chocolateButton, cherriesButton]); +} + +function waitForMutation(target) { + return new Promise((fulfill, reject) => { + const observer = new MutationObserver(mutations => { + observer.disconnect(); + fulfill(); + }); + observer.observe(target, {attributes: true}); + }); +} + +function testFocus(callback) { + chocolateButton.focus(); + + return reportPromise( + waitForMutation(tooltip) + .then(() => { + const label = tooltip.shadowRoot.querySelector('#label'); + assertEquals('Chocolate!', label.textContent.trim()); + assertTrue(!!tooltip.getAttribute('visible')); + assertEquals('4px', tooltip.style.left); + assertEquals('70px', tooltip.style.top); + + cherriesButton.focus(); + return waitForMutation(tooltip); + }) + .then(() => { + const label = tooltip.shadowRoot.querySelector('#label'); + assertEquals('Cherries!', label.textContent.trim()); + assertTrue(!!tooltip.getAttribute('visible')); + const expectedLeft = + document.body.offsetWidth - tooltip.offsetWidth + 'px'; + assertEquals(expectedLeft, tooltip.style.left); + assertEquals('70px', tooltip.style.top); + + otherButton.focus(); + return waitForMutation(tooltip); + }) + .then(() => { + assertFalse(!!tooltip.getAttribute('visible')); + }), + callback); +} + +function testHover(callback) { + chocolateButton.dispatchEvent(new MouseEvent('mouseover')); + + return reportPromise( + waitForMutation(tooltip) + .then(() => { + const label = tooltip.shadowRoot.querySelector('#label'); + assertEquals('Chocolate!', label.textContent.trim()); + assertTrue(!!tooltip.getAttribute('visible')); + assertEquals('4px', tooltip.style.left); + assertEquals('70px', tooltip.style.top); + + chocolateButton.dispatchEvent(new MouseEvent('mouseout')); + cherriesButton.dispatchEvent(new MouseEvent('mouseover')); + return waitForMutation(tooltip); + }) + .then(() => { + const label = tooltip.shadowRoot.querySelector('#label'); + assertEquals('Cherries!', label.textContent.trim()); + assertTrue(!!tooltip.getAttribute('visible')); + const expectedLeft = + document.body.offsetWidth - tooltip.offsetWidth + 'px'; + assertEquals(expectedLeft, tooltip.style.left); + assertEquals('70px', tooltip.style.top); + + cherriesButton.dispatchEvent(new MouseEvent('mouseout')); + return waitForMutation(tooltip); + }) + .then(() => { + assertFalse(!!tooltip.getAttribute('visible')); + }), + callback); +} + +function testClickHides(callback) { + chocolateButton.dispatchEvent(new MouseEvent('mouseover', {bubbles: true})); + + return reportPromise( + waitForMutation(tooltip) + .then(() => { + const label = tooltip.shadowRoot.querySelector('#label'); + assertEquals('Chocolate!', label.textContent.trim()); + assertTrue(!!tooltip.getAttribute('visible')); + + // Hiding here is synchronous. Dispatch the event asynchronously, so + // the mutation observer is started before hiding. + setTimeout(() => { + document.body.dispatchEvent(new MouseEvent('mousedown')); + }); + return waitForMutation(tooltip); + }) + .then(() => { + assertFalse(!!tooltip.getAttribute('visible')); + }), + callback); +}
diff --git a/ui/gfx/BUILD.gn b/ui/gfx/BUILD.gn index a4995a8..153c4d3 100644 --- a/ui/gfx/BUILD.gn +++ b/ui/gfx/BUILD.gn
@@ -44,6 +44,8 @@ "geometry_skia_export.h", "rrect_f.cc", "rrect_f.h", + "rrect_f_builder.cc", + "rrect_f_builder.h", "skia_util.cc", "skia_util.h", "transform.cc",
diff --git a/ui/gfx/mojom/rrect_f_mojom_traits.h b/ui/gfx/mojom/rrect_f_mojom_traits.h index 46c4b22..77d7b875 100644 --- a/ui/gfx/mojom/rrect_f_mojom_traits.h +++ b/ui/gfx/mojom/rrect_f_mojom_traits.h
@@ -8,6 +8,7 @@ #include "ui/gfx/geometry/mojom/geometry_mojom_traits.h" #include "ui/gfx/mojom/rrect_f.mojom-shared.h" #include "ui/gfx/rrect_f.h" +#include "ui/gfx/rrect_f_builder.h" namespace mojo { @@ -83,14 +84,17 @@ if (!data.ReadRect(&rect)) return false; if (type <= gfx::RRectF::Type::kRect) { - *out = gfx::RRectF(rect); + *out = gfx::RRectFBuilder().set_rect(rect).Build(); return true; } gfx::Vector2dF upper_left; if (!data.ReadUpperLeft(&upper_left)) return false; if (type <= gfx::RRectF::Type::kSimple) { - *out = gfx::RRectF(rect, upper_left.x(), upper_left.y()); + *out = gfx::RRectFBuilder() + .set_rect(rect) + .set_radius(upper_left.x(), upper_left.y()) + .Build(); return true; } gfx::Vector2dF upper_right; @@ -101,9 +105,13 @@ !data.ReadLowerLeft(&lower_left)) { return false; } - *out = gfx::RRectF(rect, upper_left.x(), upper_left.y(), upper_right.x(), - upper_right.y(), lower_right.x(), lower_right.y(), - lower_left.x(), lower_left.y()); + *out = gfx::RRectFBuilder() + .set_rect(rect) + .set_upper_left(upper_left.x(), upper_left.y()) + .set_upper_right(upper_right.x(), upper_right.y()) + .set_lower_right(lower_right.x(), lower_right.y()) + .set_lower_left(lower_left.x(), lower_left.y()) + .Build(); return true; } };
diff --git a/ui/gfx/rrect_f_builder.cc b/ui/gfx/rrect_f_builder.cc new file mode 100644 index 0000000..c5f559a --- /dev/null +++ b/ui/gfx/rrect_f_builder.cc
@@ -0,0 +1,18 @@ +// Copyright 2019 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "ui/gfx/rrect_f_builder.h" + +namespace gfx { + +RRectFBuilder::RRectFBuilder() = default; +RRectFBuilder::RRectFBuilder(RRectFBuilder&& other) = default; + +RRectF RRectFBuilder::Build() { + return RRectF(x_, y_, width_, height_, upper_left_x_, upper_left_y_, + upper_right_x_, upper_right_y_, lower_right_x_, lower_right_y_, + lower_left_x_, lower_left_y_); +} + +} // namespace gfx
diff --git a/ui/gfx/rrect_f_builder.h b/ui/gfx/rrect_f_builder.h new file mode 100644 index 0000000..3cb5ef9 --- /dev/null +++ b/ui/gfx/rrect_f_builder.h
@@ -0,0 +1,130 @@ +// Copyright 2019 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef UI_GFX_RRECT_F_BUILDER_H_ +#define UI_GFX_RRECT_F_BUILDER_H_ + +#include "ui/gfx/rrect_f.h" + +namespace gfx { + +// RRectFBuilder is implemented to make the parameter setting easier for RRectF. +// +// For example: To build an RRectF at point(40, 50) with size(60,70), +// with corner radii {(1, 2),(3, 4),(5, 6),(7, 8)}, use: +// +// RRectF a = RRectFBuilder() +// .set_origin(40, 50) +// .set_size(60, 70) +// .set_upper_left(1, 2) +// .set_upper_right(3, 4) +// .set_lower_right(5, 6) +// .set_lower_left(7, 8) +// .Build(); +class GEOMETRY_SKIA_EXPORT RRectFBuilder { + public: + RRectFBuilder(); + RRectFBuilder(RRectFBuilder&& other); + ~RRectFBuilder() = default; + + RRectFBuilder&& set_origin(float x, float y) { + x_ = x; + y_ = y; + return std::move(*this); + } + RRectFBuilder&& set_origin(const PointF& origin) { + x_ = origin.x(); + y_ = origin.y(); + return std::move(*this); + } + + RRectFBuilder&& set_size(float width, float height) { + width_ = width; + height_ = height; + return std::move(*this); + } + RRectFBuilder&& set_size(const SizeF& size) { + width_ = size.width(); + height_ = size.height(); + return std::move(*this); + } + + RRectFBuilder&& set_rect(const gfx::RectF& rect) { + x_ = rect.x(); + y_ = rect.y(); + width_ = rect.width(); + height_ = rect.height(); + return std::move(*this); + } + template <class T> + void set_rect(const T&) = delete; // To avoid implicit conversion. + + RRectFBuilder&& set_radius(float radius) { + set_upper_left(radius, radius); + set_upper_right(radius, radius); + set_lower_right(radius, radius); + set_lower_left(radius, radius); + return std::move(*this); + } + RRectFBuilder&& set_radius(float x_rad, float y_rad) { + set_upper_left(x_rad, y_rad); + set_upper_right(x_rad, y_rad); + set_lower_right(x_rad, y_rad); + set_lower_left(x_rad, y_rad); + return std::move(*this); + } + + RRectFBuilder&& set_upper_left(float upper_left_x, float upper_left_y) { + upper_left_x_ = upper_left_x; + upper_left_y_ = upper_left_y; + return std::move(*this); + } + RRectFBuilder&& set_upper_right(float upper_right_x, float upper_right_y) { + upper_right_x_ = upper_right_x; + upper_right_y_ = upper_right_y; + return std::move(*this); + } + RRectFBuilder&& set_lower_right(float lower_right_x, float lower_right_y) { + lower_right_x_ = lower_right_x; + lower_right_y_ = lower_right_y; + return std::move(*this); + } + RRectFBuilder&& set_lower_left(float lower_left_x, float lower_left_y) { + lower_left_x_ = lower_left_x; + lower_left_y_ = lower_left_y; + return std::move(*this); + } + + RRectFBuilder&& set_corners(const gfx::RoundedCornersF& corners) { + upper_left_x_ = corners.upper_left(); + upper_left_y_ = corners.upper_left(); + upper_right_x_ = corners.upper_right(); + upper_right_y_ = corners.upper_right(); + lower_right_x_ = corners.lower_right(); + lower_right_y_ = corners.lower_right(); + lower_left_x_ = corners.lower_left(); + lower_left_y_ = corners.lower_left(); + return std::move(*this); + } + + RRectF Build(); + + private: + float x_ = 0.f; + float y_ = 0.f; + float width_ = 0.f; + float height_ = 0.f; + float upper_left_x_ = 0.f; + float upper_left_y_ = 0.f; + float upper_right_x_ = 0.f; + float upper_right_y_ = 0.f; + float lower_right_x_ = 0.f; + float lower_right_y_ = 0.f; + float lower_left_x_ = 0.f; + float lower_left_y_ = 0.f; +}; + +} // namespace gfx + +#endif // UI_GFX_RRECT_F_BUILDER_H_
diff --git a/ui/gfx/rrect_f_unittest.cc b/ui/gfx/rrect_f_unittest.cc index 6bc842c2c..3630c02 100644 --- a/ui/gfx/rrect_f_unittest.cc +++ b/ui/gfx/rrect_f_unittest.cc
@@ -5,6 +5,7 @@ #include "ui/gfx/rrect_f.h" #include "base/stl_util.h" #include "testing/gtest/include/gtest/gtest.h" +#include "ui/gfx/rrect_f_builder.h" namespace gfx { @@ -270,4 +271,134 @@ ASSERT_EQ(b, RRectF(37, 47, 66, 76, 8)); } +// The following tests(started with "Build*") are for RRectFBuilder. All +// different tests are to make sure that existing RRectF definitions can be +// implemented with RRectFBuilder. +TEST(RRectFTest, BuildFromRectF) { + RectF a = RectF(); + RRectF b(a); + RRectF c = RRectFBuilder().set_rect(a).Build(); + EXPECT_EQ(b, c); + + a = RectF(60, 70); + b = RRectF(a); + c = RRectFBuilder().set_rect(a).Build(); + EXPECT_EQ(b, c); + + a = RectF(40, 50, 60, 70); + b = RRectF(a); + c = RRectFBuilder().set_rect(a).Build(); + EXPECT_EQ(b, c); +} + +TEST(RRectFTest, BuildFromRadius) { + RRectF a(40, 50, 60, 70, 15); + RRectF b = RRectFBuilder() + .set_origin(40, 50) + .set_size(60, 70) + .set_radius(15) + .Build(); + EXPECT_EQ(a, b); + + a = RRectF(40, 50, 60, 70, 15, 25); + b = RRectFBuilder() + .set_origin(40, 50) + .set_size(60, 70) + .set_radius(15, 25) + .Build(); + EXPECT_EQ(a, b); + + const PointF p(40, 50); + const SizeF s(60, 70); + b = RRectFBuilder().set_origin(p).set_size(s).set_radius(15, 25).Build(); + EXPECT_EQ(a, b); +} + +TEST(RRectFTest, BuildFromRectFWithRadius) { + RectF a(40, 50, 60, 70); + RRectF b(a, 15); + RRectF c = RRectFBuilder().set_rect(a).set_radius(15).Build(); + EXPECT_EQ(b, c); + + b = RRectF(a, 15, 25); + c = RRectFBuilder().set_rect(a).set_radius(15, 25).Build(); + EXPECT_EQ(b, c); +} + +TEST(RRectFTest, BuildFromCorners) { + RRectF a(40, 50, 60, 70, 1, 2, 3, 4, 5, 6, 7, 8); + RRectF b = RRectFBuilder() + .set_origin(40, 50) + .set_size(60, 70) + .set_upper_left(1, 2) + .set_upper_right(3, 4) + .set_lower_right(5, 6) + .set_lower_left(7, 8) + .Build(); + EXPECT_EQ(a, b); +} + +TEST(RRectFTest, BuildFromRectFWithCorners) { + RectF a(40, 50, 60, 70); + RRectF b(a, 1, 2, 3, 4, 5, 6, 7, 8); + RRectF c = RRectFBuilder() + .set_rect(a) + .set_upper_left(1, 2) + .set_upper_right(3, 4) + .set_lower_right(5, 6) + .set_lower_left(7, 8) + .Build(); + EXPECT_EQ(b, c); +} + +TEST(RRectFTest, BuildFromRoundedCornersF) { + RectF a(40, 50, 60, 70); + RoundedCornersF corners(1.5f, 2.5f, 3.5f, 4.5f); + RRectF b(a, corners); + RRectF c = RRectFBuilder().set_rect(a).set_corners(corners).Build(); + EXPECT_EQ(b, c); +} + +// In the following tests(*CornersHigherThanSize), we test whether the corner +// radii gets truncated in case of being greater than the width/height. +TEST(RRectFTest, BuildFromCornersHigherThanSize) { + RRectF a(0, 0, 20, 10, 12, 2, 8, 4, 14, 6, 6, 8); + RRectF b = RRectFBuilder() + .set_origin(0, 0) + .set_size(20, 10) + .set_upper_left(48, 8) + .set_upper_right(32, 16) + .set_lower_right(56, 24) + .set_lower_left(24, 32) + .Build(); + EXPECT_EQ(a, b); +} + +TEST(RRectFTest, BuildFromRectFWithCornersHigherThanSize) { + RectF a(0, 0, 20, 10); + RRectF b(a, 12, 2, 8, 4, 14, 6, 6, 8); + RRectF c = RRectFBuilder() + .set_rect(a) + .set_upper_left(48, 8) + .set_upper_right(32, 16) + .set_lower_right(56, 24) + .set_lower_left(24, 32) + .Build(); + EXPECT_EQ(b, c); +} + +// In this test, we set the radius first but then change the value of the +// corners. +TEST(RRectFTest, BuildFromRadiusAndCorners) { + RRectF a(40, 50, 60, 70, 1, 2, 3, 4, 15, 25, 15, 25); + RRectF b = RRectFBuilder() + .set_origin(40, 50) + .set_size(60, 70) + .set_radius(15, 25) + .set_upper_left(1, 2) + .set_upper_right(3, 4) + .Build(); + EXPECT_EQ(a, b); +} + } // namespace gfx
diff --git a/ui/gfx/text_elider_unittest.cc b/ui/gfx/text_elider_unittest.cc index c87c8f21..655c7d1 100644 --- a/ui/gfx/text_elider_unittest.cc +++ b/ui/gfx/text_elider_unittest.cc
@@ -13,11 +13,11 @@ #include "base/files/file_path.h" #include "base/i18n/rtl.h" -#include "base/message_loop/message_loop.h" #include "base/run_loop.h" #include "base/stl_util.h" #include "base/strings/string_util.h" #include "base/strings/utf_string_conversions.h" +#include "base/test/scoped_task_environment.h" #include "build/build_config.h" #include "testing/gtest/include/gtest/gtest.h" #include "ui/gfx/font.h" @@ -294,7 +294,8 @@ TEST(TextEliderTest, ElideTextAtomicSequences) { #if defined(OS_WIN) // Needed to bypass DCHECK in GetFallbackFont. - base::MessageLoopForUI message_loop; + base::test::ScopedTaskEnvironment scoped_task_environment( + base::test::ScopedTaskEnvironment::MainThreadType::UI); #endif const FontList font_list; // The below is 'MUSICAL SYMBOL G CLEF' (U+1D11E), which is represented in
diff --git a/url/url_canon_unittest.cc b/url/url_canon_unittest.cc index 5a487ca..f1f6258 100644 --- a/url/url_canon_unittest.cc +++ b/url/url_canon_unittest.cc
@@ -7,6 +7,7 @@ #include "base/stl_util.h" #include "base/strings/utf_string_conversions.h" +#include "base/test/gtest_util.h" #include "testing/gtest/include/gtest/gtest.h" #include "url/third_party/mozilla/url_parse.h" #include "url/url_canon.h" @@ -123,26 +124,15 @@ } } -#if defined(GTEST_HAS_DEATH_TEST) -// TODO(mattm): Can't run this in debug mode for now, since the DCHECK will -// cause the Chromium stack trace dialog to appear and hang the test. -// See http://crbug.com/49580. -#if defined(NDEBUG) && !defined(DCHECK_ALWAYS_ON) -#define MAYBE_DoAppendUTF8Invalid DoAppendUTF8Invalid -#else -#define MAYBE_DoAppendUTF8Invalid DISABLED_DoAppendUTF8Invalid -#endif -TEST(URLCanonTest, MAYBE_DoAppendUTF8Invalid) { +TEST(URLCanonTest, DoAppendUTF8Invalid) { std::string out_str; StdStringCanonOutput output(&out_str); // Invalid code point (too large). - ASSERT_DEBUG_DEATH({ + EXPECT_DCHECK_DEATH({ AppendUTF8Value(0x110000, &output); output.Complete(); - EXPECT_EQ("", out_str); - }, ""); + }); } -#endif // defined(GTEST_HAS_DEATH_TEST) TEST(URLCanonTest, UTF) { // Low-level test that we handle reading, canonicalization, and writing