diff options
Diffstat (limited to 'chromium/chrome/browser/ui/webui/settings')
42 files changed, 2193 insertions, 1136 deletions
diff --git a/chromium/chrome/browser/ui/webui/settings/about_handler.cc b/chromium/chrome/browser/ui/webui/settings/about_handler.cc index c372368a1e0..5a4b72f32cd 100644 --- a/chromium/chrome/browser/ui/webui/settings/about_handler.cc +++ b/chromium/chrome/browser/ui/webui/settings/about_handler.cc @@ -25,6 +25,7 @@ #include "base/values.h" #include "build/build_config.h" #include "chrome/browser/browser_process.h" +#include "chrome/browser/chrome_content_browser_client.h" #include "chrome/browser/obsolete_system/obsolete_system.h" #include "chrome/browser/ui/browser.h" #include "chrome/browser/ui/browser_commands.h" @@ -32,7 +33,6 @@ #include "chrome/browser/ui/chrome_pages.h" #include "chrome/browser/upgrade_detector/upgrade_detector.h" #include "chrome/common/channel_info.h" -#include "chrome/common/chrome_content_client.h" #include "chrome/common/pref_names.h" #include "chrome/common/url_constants.h" #include "chrome/grit/chromium_strings.h" @@ -47,7 +47,6 @@ #include "content/public/browser/web_contents.h" #include "content/public/browser/web_ui.h" #include "content/public/browser/web_ui_data_source.h" -#include "content/public/common/user_agent.h" #include "ui/base/l10n/l10n_util.h" #include "v8/include/v8-version-string.h" @@ -64,7 +63,7 @@ #include "chrome/browser/ui/webui/chromeos/image_source.h" #include "chrome/browser/ui/webui/help/help_utils_chromeos.h" #include "chrome/browser/ui/webui/help/version_updater_chromeos.h" -#include "chromeos/chromeos_switches.h" +#include "chromeos/constants/chromeos_switches.h" #include "chromeos/dbus/power_manager_client.h" #include "chromeos/dbus/util/version_loader.h" #include "chromeos/network/network_state.h" @@ -354,7 +353,6 @@ AboutHandler* AboutHandler::Create(content::WebUIDataSource* html_source, html_source->AddString("aboutUserAgent", GetUserAgent()); html_source->AddString("aboutJsEngineVersion", V8_VERSION_STRING); - html_source->AddString("aboutBlinkVersion", content::GetWebKitVersion()); html_source->AddString("endOfLifeMessage", l10n_util::GetStringUTF16(IDS_EOL_NOTIFICATION_EOL)); html_source->AddString("endOfLifeLearnMoreURL", diff --git a/chromium/chrome/browser/ui/webui/settings/accessibility_main_handler.cc b/chromium/chrome/browser/ui/webui/settings/accessibility_main_handler.cc new file mode 100644 index 00000000000..9c8dbc4e0fd --- /dev/null +++ b/chromium/chrome/browser/ui/webui/settings/accessibility_main_handler.cc @@ -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. + +#include "chrome/browser/ui/webui/settings/accessibility_main_handler.h" + +#include "base/bind.h" +#include "base/values.h" +#include "chrome/browser/accessibility/accessibility_state_utils.h" +#include "chrome/browser/profiles/profile.h" +#include "chrome/browser/renderer_context_menu/accessibility_labels_bubble_model.h" +#include "chrome/browser/ui/confirm_bubble.h" +#include "content/public/browser/render_view_host.h" +#include "content/public/browser/render_widget_host.h" +#include "content/public/browser/render_widget_host_view.h" +#include "content/public/browser/web_contents.h" +#include "content/public/browser/web_ui.h" +#if !defined(OS_CHROMEOS) +#include "content/public/browser/browser_accessibility_state.h" +#endif // !defined(OS_CHROMEOS) + +namespace settings { + +AccessibilityMainHandler::AccessibilityMainHandler() { +#if defined(OS_CHROMEOS) + accessibility_subscription_ = + chromeos::AccessibilityManager::Get()->RegisterCallback( + base::BindRepeating( + &AccessibilityMainHandler::OnAccessibilityStatusChanged, + base::Unretained(this))); +#endif // defined(OS_CHROMEOS) +} + +AccessibilityMainHandler::~AccessibilityMainHandler() {} + +void AccessibilityMainHandler::RegisterMessages() { + web_ui()->RegisterMessageCallback( + "getScreenReaderState", + base::BindRepeating(&AccessibilityMainHandler::HandleGetScreenReaderState, + base::Unretained(this))); + web_ui()->RegisterMessageCallback( + "confirmA11yImageLabels", + base::BindRepeating( + &AccessibilityMainHandler::HandleCheckAccessibilityImageLabels, + base::Unretained(this))); +} + +void AccessibilityMainHandler::OnAXModeAdded(ui::AXMode mode) { + HandleGetScreenReaderState(nullptr); +} + +void AccessibilityMainHandler::HandleGetScreenReaderState( + const base::ListValue* args) { + base::Value result(accessibility_state_utils::IsScreenReaderEnabled()); + AllowJavascript(); + FireWebUIListener("screen-reader-state-changed", result); +} + +void AccessibilityMainHandler::HandleCheckAccessibilityImageLabels( + const base::ListValue* args) { + // When the user tries to enable the feature, show the modal dialog. The + // dialog will disable the feature again if it is not accepted. + content::WebContents* web_contents = web_ui()->GetWebContents(); + content::RenderWidgetHostView* view = + web_contents->GetRenderViewHost()->GetWidget()->GetView(); + gfx::Rect rect = view->GetViewBounds(); + auto model = std::make_unique<AccessibilityLabelsBubbleModel>( + Profile::FromWebUI(web_ui()), web_contents); + chrome::ShowConfirmBubble( + web_contents->GetTopLevelNativeWindow(), view->GetNativeView(), + gfx::Point(rect.CenterPoint().x(), rect.y()), std::move(model)); +} + +#if defined(OS_CHROMEOS) +void AccessibilityMainHandler::OnAccessibilityStatusChanged( + const chromeos::AccessibilityStatusEventDetails& details) { + if (details.notification_type == + chromeos::ACCESSIBILITY_TOGGLE_SPOKEN_FEEDBACK) { + HandleGetScreenReaderState(nullptr); + } +} +#endif // defined(OS_CHROMEOS) + +} // namespace settings diff --git a/chromium/chrome/browser/ui/webui/settings/accessibility_main_handler.h b/chromium/chrome/browser/ui/webui/settings/accessibility_main_handler.h new file mode 100644 index 00000000000..966daba4148 --- /dev/null +++ b/chromium/chrome/browser/ui/webui/settings/accessibility_main_handler.h @@ -0,0 +1,57 @@ +// 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_WEBUI_SETTINGS_ACCESSIBILITY_MAIN_HANDLER_H_ +#define CHROME_BROWSER_UI_WEBUI_SETTINGS_ACCESSIBILITY_MAIN_HANDLER_H_ + +#include "base/macros.h" +#include "chrome/browser/ui/webui/settings/settings_page_ui_handler.h" +#include "ui/accessibility/ax_mode.h" +#include "ui/accessibility/ax_mode_observer.h" +#if defined(OS_CHROMEOS) +#include "chrome/browser/chromeos/accessibility/accessibility_manager.h" +#endif // defined(OS_CHROMEOS) + +namespace base { +class ListValue; +} + +namespace settings { + +// Settings handler for the main accessibility settings page, +// chrome://settings/accessibility. +class AccessibilityMainHandler : public ::settings::SettingsPageUIHandler, + public ui::AXModeObserver { + public: + AccessibilityMainHandler(); + ~AccessibilityMainHandler() override; + + // SettingsPageUIHandler implementation. + void RegisterMessages() override; + void OnJavascriptAllowed() override {} + void OnJavascriptDisallowed() override {} + + // AXModeObserver implementation. + void OnAXModeAdded(ui::AXMode mode) override; + + void HandleGetScreenReaderState(const base::ListValue* args); + void HandleCheckAccessibilityImageLabels(const base::ListValue* args); + + private: +#if defined(OS_CHROMEOS) + void OnAccessibilityStatusChanged( + const chromeos::AccessibilityStatusEventDetails& details); + + std::unique_ptr<chromeos::AccessibilityStatusSubscription> + accessibility_subscription_; +#else + +#endif // defined(OS_CHROMEOS) + + DISALLOW_COPY_AND_ASSIGN(AccessibilityMainHandler); +}; + +} // namespace settings + +#endif // CHROME_BROWSER_UI_WEBUI_SETTINGS_ACCESSIBILITY_MAIN_HANDLER_H_ diff --git a/chromium/chrome/browser/ui/webui/settings/chrome_cleanup_handler.cc b/chromium/chrome/browser/ui/webui/settings/chrome_cleanup_handler.cc index 95f0eff69a1..e28dfbf7dd9 100644 --- a/chromium/chrome/browser/ui/webui/settings/chrome_cleanup_handler.cc +++ b/chromium/chrome/browser/ui/webui/settings/chrome_cleanup_handler.cc @@ -105,14 +105,7 @@ std::string IdleReasonToString( } // namespace ChromeCleanupHandler::ChromeCleanupHandler(Profile* profile) - : controller_(ChromeCleanerController::GetInstance()), profile_(profile) { - DCHECK(g_browser_process->local_state()); - logs_enabled_pref_.Init(g_browser_process->local_state()); - logs_enabled_pref_.Add( - prefs::kSwReporterReportingEnabled, - base::BindRepeating(&ChromeCleanupHandler::OnLogsEnabledPrefChanged, - base::Unretained(this))); -} + : controller_(ChromeCleanerController::GetInstance()), profile_(profile) {} ChromeCleanupHandler::~ChromeCleanupHandler() { controller_->RemoveObserver(this); @@ -133,10 +126,6 @@ void ChromeCleanupHandler::RegisterMessages() { base::BindRepeating(&ChromeCleanupHandler::HandleRestartComputer, base::Unretained(this))); web_ui()->RegisterMessageCallback( - "setLogsUploadPermission", - base::BindRepeating(&ChromeCleanupHandler::HandleSetLogsUploadPermission, - base::Unretained(this))); - web_ui()->RegisterMessageCallback( "startCleanup", base::BindRepeating(&ChromeCleanupHandler::HandleStartCleanup, base::Unretained(this))); @@ -202,18 +191,6 @@ void ChromeCleanupHandler::OnRebootRequired() { FireWebUIListener("chrome-cleanup-on-reboot-required"); } -void ChromeCleanupHandler::OnLogsEnabledChanged(bool logs_enabled) { - FireWebUIListener("chrome-cleanup-upload-permission-change", - base::Value(controller_->IsReportingManagedByPolicy()), - base::Value(logs_enabled)); -} - -void ChromeCleanupHandler::OnLogsEnabledPrefChanged() { - bool is_enabled = controller_->IsReportingAllowedByPolicy(); - controller_->SetLogsEnabled(is_enabled); - OnLogsEnabledChanged(is_enabled); -} - void ChromeCleanupHandler::HandleRegisterChromeCleanerObserver( const base::ListValue* args) { DCHECK_EQ(0U, args->GetSize()); @@ -223,9 +200,6 @@ void ChromeCleanupHandler::HandleRegisterChromeCleanerObserver( base::UserMetricsAction("SoftwareReporter.CleanupWebui_Shown")); AllowJavascript(); - // Send the current logs upload state. - OnLogsEnabledChanged(controller_->logs_enabled()); - FireWebUIListener("chrome-cleanup-enabled-change", base::Value(controller_->IsAllowedByPolicy())); } @@ -239,9 +213,9 @@ void ChromeCleanupHandler::HandleStartScanning(const base::ListValue* args) { CHECK(controller_->IsAllowedByPolicy()); // The state is propagated to all open tabs and should be consistent. - DCHECK_EQ(controller_->logs_enabled(), allow_logs_upload); + DCHECK_EQ(controller_->logs_enabled(profile_), allow_logs_upload); - controller_->RequestUserInitiatedScan(); + controller_->RequestUserInitiatedScan(profile_); base::RecordAction( base::UserMetricsAction("SoftwareReporter.CleanupWebui_StartScanning")); @@ -256,30 +230,13 @@ void ChromeCleanupHandler::HandleRestartComputer(const base::ListValue* args) { controller_->Reboot(); } -void ChromeCleanupHandler::HandleSetLogsUploadPermission( - const base::ListValue* args) { - CHECK_EQ(1U, args->GetSize()); - bool allow_logs_upload = false; - args->GetBoolean(0, &allow_logs_upload); - - if (allow_logs_upload) { - base::RecordAction(base::UserMetricsAction( - "SoftwareReporter.CleanupWebui_LogsUploadEnabled")); - } else { - base::RecordAction(base::UserMetricsAction( - "SoftwareReporter.CleanupWebui_LogsUploadDisabled")); - } - - controller_->SetLogsEnabled(allow_logs_upload); -} - void ChromeCleanupHandler::HandleStartCleanup(const base::ListValue* args) { CHECK_EQ(1U, args->GetSize()); bool allow_logs_upload = false; args->GetBoolean(0, &allow_logs_upload); // The state is propagated to all open tabs and should be consistent. - DCHECK_EQ(controller_->logs_enabled(), allow_logs_upload); + DCHECK_EQ(controller_->logs_enabled(profile_), allow_logs_upload); safe_browsing::RecordCleanupStartedHistogram( safe_browsing::CLEANUP_STARTED_FROM_PROMPT_IN_SETTINGS); diff --git a/chromium/chrome/browser/ui/webui/settings/chrome_cleanup_handler.h b/chromium/chrome/browser/ui/webui/settings/chrome_cleanup_handler.h index 237e11484a1..fffa41c1e9e 100644 --- a/chromium/chrome/browser/ui/webui/settings/chrome_cleanup_handler.h +++ b/chromium/chrome/browser/ui/webui/settings/chrome_cleanup_handler.h @@ -10,7 +10,7 @@ #include "base/files/file_path.h" #include "base/macros.h" #include "chrome/browser/safe_browsing/chrome_cleaner/chrome_cleaner_controller_win.h" -#include "chrome/browser/safe_browsing/chrome_cleaner/chrome_cleaner_scanner_results.h" +#include "chrome/browser/safe_browsing/chrome_cleaner/chrome_cleaner_scanner_results_win.h" #include "chrome/browser/ui/webui/settings/settings_page_ui_handler.h" #include "components/prefs/pref_change_registrar.h" @@ -43,12 +43,8 @@ class ChromeCleanupHandler const safe_browsing::ChromeCleanerScannerResults& reported_results) override; void OnRebootRequired() override; - void OnLogsEnabledChanged(bool logs_enabled) override; private: - // Called when prefs::kSwReporterReportingEnabled changes. - void OnLogsEnabledPrefChanged(); - // Callback for the "registerChromeCleanerObserver" message. This registers // this object as an observer of the Chrome Cleanup global state and // and retrieves the current cleanup state. @@ -62,10 +58,6 @@ class ChromeCleanupHandler // system restart. void HandleRestartComputer(const base::ListValue* args); - // Callback for the "setLogsUploadPermission" message to keep track of - // whether the user opted-out of logs upload or not. - void HandleSetLogsUploadPermission(const base::ListValue* args); - // Callback for the "startCleanup" message to start removing unwanted // software from the user's computer. void HandleStartCleanup(const base::ListValue* args); @@ -92,7 +84,6 @@ class ChromeCleanupHandler safe_browsing::ChromeCleanerController* controller_; Profile* profile_; - PrefChangeRegistrar logs_enabled_pref_; DISALLOW_COPY_AND_ASSIGN(ChromeCleanupHandler); }; diff --git a/chromium/chrome/browser/ui/webui/settings/chromeos/OWNERS b/chromium/chrome/browser/ui/webui/settings/chromeos/OWNERS index a74cbcbbbe0..f42990c5d35 100644 --- a/chromium/chrome/browser/ui/webui/settings/chromeos/OWNERS +++ b/chromium/chrome/browser/ui/webui/settings/chromeos/OWNERS @@ -1,3 +1,3 @@ -per-file multidevice_handler*=file://chromeos/services/multidevice_setup/OWNERS +per-file multidevice_handler*=file://chromeos/components/multidevice/OWNERS # COMPONENT: UI>Settings diff --git a/chromium/chrome/browser/ui/webui/settings/chromeos/account_manager_handler.cc b/chromium/chrome/browser/ui/webui/settings/chromeos/account_manager_handler.cc index ba2d1822086..7efa92b655c 100644 --- a/chromium/chrome/browser/ui/webui/settings/chromeos/account_manager_handler.cc +++ b/chromium/chrome/browser/ui/webui/settings/chromeos/account_manager_handler.cc @@ -13,14 +13,19 @@ #include "base/values.h" #include "chrome/browser/chromeos/profiles/profile_helper.h" #include "chrome/browser/profiles/profile.h" +#include "chrome/browser/ui/webui/chromeos/account_manager_welcome_dialog.h" #include "chrome/browser/ui/webui/settings/settings_page_ui_handler.h" #include "chrome/browser/ui/webui/signin/inline_login_handler_dialog_chromeos.h" #include "chromeos/account_manager/account_manager.h" #include "chromeos/account_manager/account_manager_factory.h" #include "components/signin/core/browser/account_tracker_service.h" #include "components/user_manager/user.h" +#include "google_apis/gaia/google_service_auth_error.h" #include "third_party/skia/include/core/SkBitmap.h" +#include "ui/base/resource/resource_bundle.h" #include "ui/base/webui/web_ui_util.h" +#include "ui/chromeos/resources/grit/ui_chromeos_resources.h" +#include "ui/gfx/image/image_skia.h" namespace chromeos { namespace settings { @@ -51,9 +56,11 @@ AccountManager::AccountKey GetAccountKeyFromJsCallback( AccountManagerUIHandler::AccountManagerUIHandler( AccountManager* account_manager, - AccountTrackerService* account_tracker_service) + AccountTrackerService* account_tracker_service, + identity::IdentityManager* identity_manager) : account_manager_(account_manager), account_tracker_service_(account_tracker_service), + identity_manager_(identity_manager), account_mapper_util_(account_tracker_service_), account_manager_observer_(this), account_tracker_service_observer_(this), @@ -74,13 +81,23 @@ void AccountManagerUIHandler::RegisterMessages() { base::BindRepeating(&AccountManagerUIHandler::HandleAddAccount, weak_factory_.GetWeakPtr())); web_ui()->RegisterMessageCallback( + "reauthenticateAccount", + base::BindRepeating(&AccountManagerUIHandler::HandleReauthenticateAccount, + weak_factory_.GetWeakPtr())); + web_ui()->RegisterMessageCallback( "removeAccount", base::BindRepeating(&AccountManagerUIHandler::HandleRemoveAccount, weak_factory_.GetWeakPtr())); + web_ui()->RegisterMessageCallback( + "showWelcomeDialogIfRequired", + base::BindRepeating( + &AccountManagerUIHandler::HandleShowWelcomeDialogIfRequired, + weak_factory_.GetWeakPtr())); } void AccountManagerUIHandler::HandleGetAccounts(const base::ListValue* args) { AllowJavascript(); + CHECK(!args->GetList().empty()); base::Value callback_id = args->GetList()[0].Clone(); @@ -110,21 +127,32 @@ void AccountManagerUIHandler::GetAccountsCallbackHandler( account_tracker_service_->FindAccountInfoByGaiaId(account_key.id); DCHECK(!account_info.IsEmpty()); - if (account_info.full_name.empty()) { - // Account info has not been fully fetched yet from GAIA. Ignore this - // account. - continue; - } - base::DictionaryValue account; account.SetString("id", account_key.id); account.SetInteger("accountType", account_key.account_type); account.SetBoolean("isDeviceAccount", false); + + const std::string oauth_account_id = + account_mapper_util_.AccountKeyToOAuthAccountId(account_key); + account.SetBoolean( + "isSignedIn", + identity_manager_->HasAccountWithRefreshToken(oauth_account_id) && + !identity_manager_ + ->HasAccountWithRefreshTokenInPersistentErrorState( + oauth_account_id)); account.SetString("fullName", account_info.full_name); account.SetString("email", account_info.email); - gfx::Image icon = - account_tracker_service_->GetAccountImage(account_info.account_id); - account.SetString("pic", webui::GetBitmapDataUrl(icon.AsBitmap())); + if (!account_info.account_image.IsEmpty()) { + account.SetString("pic", webui::GetBitmapDataUrl( + account_info.account_image.AsBitmap())); + } else { + gfx::ImageSkia default_icon = + *ui::ResourceBundle::GetSharedInstance().GetImageSkiaNamed( + IDR_LOGIN_DEFAULT_USER); + account.SetString("pic", + webui::GetBitmapDataUrl( + default_icon.GetRepresentation(1.0f).GetBitmap())); + } if (account_mapper_util_.IsEqual(account_key, device_account_id)) { device_account = std::move(account); @@ -148,6 +176,16 @@ void AccountManagerUIHandler::HandleAddAccount(const base::ListValue* args) { InlineLoginHandlerDialogChromeOS::Show(); } +void AccountManagerUIHandler::HandleReauthenticateAccount( + const base::ListValue* args) { + AllowJavascript(); + + std::string account_email; + args->GetList()[0].GetAsString(&account_email); + + InlineLoginHandlerDialogChromeOS::Show(account_email); +} + void AccountManagerUIHandler::HandleRemoveAccount(const base::ListValue* args) { AllowJavascript(); @@ -169,6 +207,11 @@ void AccountManagerUIHandler::HandleRemoveAccount(const base::ListValue* args) { account_manager_->RemoveAccount(account_key); } +void AccountManagerUIHandler::HandleShowWelcomeDialogIfRequired( + const base::ListValue* args) { + chromeos::AccountManagerWelcomeDialog::ShowIfRequired(); +} + void AccountManagerUIHandler::OnJavascriptAllowed() { account_manager_observer_.Add(account_manager_); account_tracker_service_observer_.Add(account_tracker_service_); @@ -204,9 +247,11 @@ void AccountManagerUIHandler::OnAccountUpdated(const AccountInfo& info) { RefreshUI(); } -void AccountManagerUIHandler::OnAccountImageUpdated( - const std::string& account_id, - const gfx::Image& image) { +void AccountManagerUIHandler::OnAccountUpdateFailed( + const std::string& account_id) { + // An account fetch failed for |account_id|, but we must display the account + // anyways (if it was not being displayed already) so that users do not think + // that their account has suddenly disappeared. RefreshUI(); } diff --git a/chromium/chrome/browser/ui/webui/settings/chromeos/account_manager_handler.h b/chromium/chrome/browser/ui/webui/settings/chromeos/account_manager_handler.h index ce57798fd97..2b2a1918f4e 100644 --- a/chromium/chrome/browser/ui/webui/settings/chromeos/account_manager_handler.h +++ b/chromium/chrome/browser/ui/webui/settings/chromeos/account_manager_handler.h @@ -15,6 +15,7 @@ #include "chrome/browser/ui/webui/settings/settings_page_ui_handler.h" #include "chromeos/account_manager/account_manager.h" #include "components/signin/core/browser/account_tracker_service.h" +#include "services/identity/public/cpp/identity_manager.h" namespace chromeos { namespace settings { @@ -26,7 +27,8 @@ class AccountManagerUIHandler : public ::settings::SettingsPageUIHandler, // Accepts non-owning pointers to |AccountManager| and // |AccountTrackerService|. Both of these must outlive |this| instance. AccountManagerUIHandler(AccountManager* account_manager, - AccountTrackerService* account_tracker_service); + AccountTrackerService* account_tracker_service, + identity::IdentityManager* identity_manager); ~AccountManagerUIHandler() override; // WebUIMessageHandler implementation. @@ -42,8 +44,7 @@ class AccountManagerUIHandler : public ::settings::SettingsPageUIHandler, // |AccountTrackerService::Observer| overrides. void OnAccountUpdated(const AccountInfo& info) override; - void OnAccountImageUpdated(const std::string& account_id, - const gfx::Image& image) override; + void OnAccountUpdateFailed(const std::string& account_id) override; void OnAccountRemoved(const AccountInfo& account_key) override; private: @@ -53,9 +54,15 @@ class AccountManagerUIHandler : public ::settings::SettingsPageUIHandler, // WebUI "addAccount" message callback. void HandleAddAccount(const base::ListValue* args); + // WebUI "reauthenticateAccount" message callback. + void HandleReauthenticateAccount(const base::ListValue* args); + // WebUI "removeAccount" message callback. void HandleRemoveAccount(const base::ListValue* args); + // WebUI "showWelcomeDialogIfRequired" message callback. + void HandleShowWelcomeDialogIfRequired(const base::ListValue* args); + // |AccountManager::GetAccounts| callback. void GetAccountsCallbackHandler( base::Value callback_id, @@ -70,6 +77,9 @@ class AccountManagerUIHandler : public ::settings::SettingsPageUIHandler, // A non-owning pointer to |AccountTrackerService|. AccountTrackerService* const account_tracker_service_; + // A non-owning pointer to |IdentityManager|. + identity::IdentityManager* const identity_manager_; + chromeos::AccountMapperUtil account_mapper_util_; // An observer for |AccountManager|. Automatically deregisters when |this| is diff --git a/chromium/chrome/browser/ui/webui/settings/chromeos/change_picture_handler.cc b/chromium/chrome/browser/ui/webui/settings/chromeos/change_picture_handler.cc index fc2a1758546..a9e5e26cfa4 100644 --- a/chromium/chrome/browser/ui/webui/settings/chromeos/change_picture_handler.cc +++ b/chromium/chrome/browser/ui/webui/settings/chromeos/change_picture_handler.cc @@ -14,6 +14,7 @@ #include "base/metrics/histogram_macros.h" #include "base/no_destructor.h" #include "base/path_service.h" +#include "base/stl_util.h" #include "base/strings/string_util.h" #include "base/strings/utf_string_conversions.h" #include "base/values.h" @@ -184,7 +185,7 @@ void ChangePictureHandler::HandlePhotoTaken(const base::ListValue* args) { std::string raw_data; base::StringPiece url(image_url); const char kDataUrlPrefix[] = "data:image/png;base64,"; - const size_t kDataUrlPrefixLength = arraysize(kDataUrlPrefix) - 1; + const size_t kDataUrlPrefixLength = base::size(kDataUrlPrefix) - 1; if (!url.starts_with(kDataUrlPrefix) || !base::Base64Decode(url.substr(kDataUrlPrefixLength), &raw_data)) { LOG(WARNING) << "Invalid image URL"; diff --git a/chromium/chrome/browser/ui/webui/settings/chromeos/cups_printers_handler.cc b/chromium/chrome/browser/ui/webui/settings/chromeos/cups_printers_handler.cc index cb6f001014e..7932d706c9e 100644 --- a/chromium/chrome/browser/ui/webui/settings/chromeos/cups_printers_handler.cc +++ b/chromium/chrome/browser/ui/webui/settings/chromeos/cups_printers_handler.cc @@ -213,6 +213,43 @@ bool IsValidUriChange(const Printer& existing_printer, return existing_printer.uri() == new_printer.uri(); } +// Assumes |info| is a dictionary. +void SetPpdReference(const Printer::PpdReference& ppd_ref, base::Value* info) { + if (!ppd_ref.user_supplied_ppd_url.empty()) { + info->SetKey("ppdRefUserSuppliedPpdUrl", + base::Value(ppd_ref.user_supplied_ppd_url)); + } else if (!ppd_ref.effective_make_and_model.empty()) { + info->SetKey("ppdRefEffectiveMakeAndModel", + base::Value(ppd_ref.effective_make_and_model)); + } else { // Must be autoconf, shouldn't be possible + NOTREACHED() << "Succeeded in PPD matching without emm"; + } +} + +Printer::PpdReference GetPpdReference(const base::Value* info) { + const char ppd_ref_pathname[] = "printerPpdReference"; + auto* user_supplied_ppd_url = + info->FindPath({ppd_ref_pathname, "userSuppliedPPDUrl"}); + auto* effective_make_and_model = + info->FindPath({ppd_ref_pathname, "effectiveMakeAndModel"}); + auto* autoconf = info->FindPath({ppd_ref_pathname, "autoconf"}); + + if (user_supplied_ppd_url != nullptr) { + DCHECK(!effective_make_and_model && !autoconf); + return Printer::PpdReference{user_supplied_ppd_url->GetString(), "", false}; + } + + if (effective_make_and_model != nullptr) { + DCHECK(!user_supplied_ppd_url && !autoconf); + return Printer::PpdReference{"", effective_make_and_model->GetString(), + false}; + } + + // Otherwise it must be autoconf + DCHECK(autoconf && autoconf->GetBool()); + return Printer::PpdReference{"", "", true}; +} + } // namespace CupsPrintersHandler::CupsPrintersHandler(content::WebUI* webui) @@ -470,11 +507,42 @@ void CupsPrintersHandler::OnAutoconfQueried(const std::string& callback_id, PRINTER_LOG(DEBUG) << "Resolved printer information: make_and_model(" << make_and_model << ") autoconf(" << ipp_everywhere << ")"; - base::DictionaryValue info; - info.SetString("manufacturer", make); - info.SetString("model", model); - info.SetString("makeAndModel", make_and_model); - info.SetBoolean("autoconf", ipp_everywhere); + + // Bundle printer metadata + base::Value info(base::Value::Type::DICTIONARY); + info.SetKey("manufacturer", base::Value(make)); + info.SetKey("model", base::Value(model)); + info.SetKey("makeAndModel", base::Value(make_and_model)); + info.SetKey("autoconf", base::Value(ipp_everywhere)); + + if (ipp_everywhere) { + info.SetKey("ppdReferenceResolved", base::Value(true)); + ResolveJavascriptCallback(base::Value(callback_id), info); + return; + } + + PpdProvider::PrinterSearchData ppd_search_data; + ppd_search_data.make_and_model.push_back(make_and_model); + + // Try to resolve the PPD matching. + ppd_provider_->ResolvePpdReference( + ppd_search_data, + base::BindOnce(&CupsPrintersHandler::OnPpdResolved, + weak_factory_.GetWeakPtr(), callback_id, std::move(info))); +} + +void CupsPrintersHandler::OnPpdResolved(const std::string& callback_id, + base::Value info, + PpdProvider::CallbackResultCode res, + const Printer::PpdReference& ppd_ref) { + if (res != PpdProvider::CallbackResultCode::SUCCESS) { + info.SetKey("ppdReferenceResolved", base::Value(false)); + ResolveJavascriptCallback(base::Value(callback_id), info); + return; + } + + SetPpdReference(ppd_ref, &info); + info.SetKey("ppdReferenceResolved", base::Value(true)); ResolveJavascriptCallback(base::Value(callback_id), info); } @@ -503,8 +571,7 @@ void CupsPrintersHandler::HandleAddCupsPrinter(const base::ListValue* args) { return; } - auto optional = printer->GetUriComponents(); - if (!optional.has_value()) { + if (!printer->GetUriComponents().has_value()) { // If the returned optional does not contain a value then it means that the // printer's uri was not able to be parsed successfully. PRINTER_LOG(ERROR) << "Failed to parse printer URI"; @@ -536,12 +603,13 @@ void CupsPrintersHandler::HandleAddCupsPrinter(const base::ListValue* args) { std::string printer_ppd_path; printer_dict->GetString("printerPPDPath", &printer_ppd_path); - bool autoconf = false; - printer_dict->GetBoolean("printerAutoconf", &autoconf); + // Checks whether a resolved PPD Reference is available. + bool ppd_ref_resolved = false; + printer_dict->GetBoolean("printerPpdReferenceResolved", &ppd_ref_resolved); // Verify that the printer is autoconf or a valid ppd path is present. - if (autoconf) { - printer->mutable_ppd_reference()->autoconf = true; + if (ppd_ref_resolved) { + *printer->mutable_ppd_reference() = GetPpdReference(printer_dict); } else if (!printer_ppd_path.empty()) { RecordPpdSource(kUser); GURL tmp = net::FilePathToFileURL(base::FilePath(printer_ppd_path)); @@ -558,7 +626,7 @@ void CupsPrintersHandler::HandleAddCupsPrinter(const base::ListValue* args) { bool found = false; for (const auto& resolved_printer : resolved_printers_[ppd_manufacturer]) { if (resolved_printer.name == ppd_model) { - *(printer->mutable_ppd_reference()) = resolved_printer.ppd_ref; + *printer->mutable_ppd_reference() = resolved_printer.ppd_ref; found = true; break; } @@ -884,8 +952,7 @@ void CupsPrintersHandler::HandleAddDiscoveredPrinter( return; } - auto optional = printer->GetUriComponents(); - if (!optional.has_value()) { + if (!printer->GetUriComponents().has_value()) { PRINTER_LOG(DEBUG) << "Could not parse uri"; // The printer uri was not parsed successfully. Fail the add. FireWebUIListener("on-add-cups-printer", base::Value(false), diff --git a/chromium/chrome/browser/ui/webui/settings/chromeos/cups_printers_handler.h b/chromium/chrome/browser/ui/webui/settings/chromeos/cups_printers_handler.h index 741b87e13db..f6b4aa1b81a 100644 --- a/chromium/chrome/browser/ui/webui/settings/chromeos/cups_printers_handler.h +++ b/chromium/chrome/browser/ui/webui/settings/chromeos/cups_printers_handler.h @@ -78,6 +78,12 @@ class CupsPrintersHandler : public ::settings::SettingsPageUIHandler, const std::string& make_and_model, bool ipp_everywhere); + // Callback for PPD matching attempts; + void OnPpdResolved(const std::string& callback_id, + base::Value info, + PpdProvider::CallbackResultCode res, + const Printer::PpdReference& ppd_ref); + void HandleAddCupsPrinter(const base::ListValue* args); // Handles the result of adding a printer which the user specified the diff --git a/chromium/chrome/browser/ui/webui/settings/chromeos/date_time_handler.cc b/chromium/chrome/browser/ui/webui/settings/chromeos/date_time_handler.cc index 901d006207d..779d2504b25 100644 --- a/chromium/chrome/browser/ui/webui/settings/chromeos/date_time_handler.cc +++ b/chromium/chrome/browser/ui/webui/settings/chromeos/date_time_handler.cc @@ -12,7 +12,7 @@ #include "chrome/browser/chromeos/system/timezone_resolver_manager.h" #include "chrome/browser/chromeos/system/timezone_util.h" #include "chrome/common/pref_names.h" -#include "chromeos/chromeos_switches.h" +#include "chromeos/constants/chromeos_switches.h" #include "chromeos/dbus/dbus_thread_manager.h" #include "chromeos/dbus/system_clock_client.h" #include "chromeos/settings/timezone_settings.h" @@ -154,7 +154,7 @@ void DateTimeHandler::HandleShowSetDateTimeUI(const base::ListValue* args) { // Make sure the clock status hasn't changed since the button was clicked. if (!DBusThreadManager::Get()->GetSystemClockClient()->CanSetTime()) return; - SetTimeDialog::ShowDialogInParent( + SetTimeDialog::ShowDialog( web_ui()->GetWebContents()->GetTopLevelNativeWindow()); } diff --git a/chromium/chrome/browser/ui/webui/settings/chromeos/device_keyboard_handler.cc b/chromium/chrome/browser/ui/webui/settings/chromeos/device_keyboard_handler.cc index 15f648a7215..8daed6d7f45 100644 --- a/chromium/chrome/browser/ui/webui/settings/chromeos/device_keyboard_handler.cc +++ b/chromium/chrome/browser/ui/webui/settings/chromeos/device_keyboard_handler.cc @@ -11,7 +11,7 @@ #include "base/values.h" #include "chrome/browser/ui/ash/ksv/keyboard_shortcut_viewer_util.h" #include "chrome/browser/ui/ash/tablet_mode_client.h" -#include "chromeos/chromeos_switches.h" +#include "chromeos/constants/chromeos_switches.h" #include "content/public/browser/web_ui.h" #include "content/public/common/service_manager_connection.h" #include "services/service_manager/public/cpp/connector.h" @@ -86,10 +86,13 @@ void KeyboardHandler::OnJavascriptDisallowed() { observer_.RemoveAll(); } -void KeyboardHandler::OnKeyboardDeviceConfigurationChanged() { - AllowJavascript(); - UpdateShowKeys(); - UpdateKeyboards(); +void KeyboardHandler::OnInputDeviceConfigurationChanged( + uint8_t input_device_types) { + if (input_device_types & ui::InputDeviceEventObserver::kKeyboard) { + AllowJavascript(); + UpdateShowKeys(); + UpdateKeyboards(); + } } void KeyboardHandler::HandleInitialize(const base::ListValue* args) { diff --git a/chromium/chrome/browser/ui/webui/settings/chromeos/device_keyboard_handler.h b/chromium/chrome/browser/ui/webui/settings/chromeos/device_keyboard_handler.h index 6b071f0e217..84b01082a20 100644 --- a/chromium/chrome/browser/ui/webui/settings/chromeos/device_keyboard_handler.h +++ b/chromium/chrome/browser/ui/webui/settings/chromeos/device_keyboard_handler.h @@ -52,7 +52,7 @@ class KeyboardHandler void OnJavascriptDisallowed() override; // ui::InputDeviceEventObserver implementation. - void OnKeyboardDeviceConfigurationChanged() override; + void OnInputDeviceConfigurationChanged(uint8_t input_device_types) override; private: // Initializes the page with the current keyboard information. diff --git a/chromium/chrome/browser/ui/webui/settings/chromeos/device_keyboard_handler_unittest.cc b/chromium/chrome/browser/ui/webui/settings/chromeos/device_keyboard_handler_unittest.cc index 04ddbb99df5..2b828787676 100644 --- a/chromium/chrome/browser/ui/webui/settings/chromeos/device_keyboard_handler_unittest.cc +++ b/chromium/chrome/browser/ui/webui/settings/chromeos/device_keyboard_handler_unittest.cc @@ -10,7 +10,7 @@ #include "base/logging.h" #include "base/macros.h" #include "base/observer_list.h" -#include "chromeos/chromeos_switches.h" +#include "chromeos/constants/chromeos_switches.h" #include "content/public/test/test_web_ui.h" #include "services/ws/public/cpp/input_devices/input_device_client_test_api.h" #include "testing/gtest/include/gtest/gtest.h" diff --git a/chromium/chrome/browser/ui/webui/settings/chromeos/device_power_handler.cc b/chromium/chrome/browser/ui/webui/settings/chromeos/device_power_handler.cc index e7a3a9f34fa..4f0138fc90a 100644 --- a/chromium/chrome/browser/ui/webui/settings/chromeos/device_power_handler.cc +++ b/chromium/chrome/browser/ui/webui/settings/chromeos/device_power_handler.cc @@ -392,9 +392,7 @@ void PowerHandler::SendPowerManagementSettings(bool force) { dict.SetInteger(kLidClosedBehaviorKey, lid_closed_behavior); dict.SetBoolean(kLidClosedControlledKey, lid_closed_controlled); dict.SetBoolean(kHasLidKey, has_lid); - CallJavascriptFunction("cr.webUIListenerCallback", - base::Value(kPowerManagementSettingsChangedName), - dict); + FireWebUIListener(kPowerManagementSettingsChangedName, dict); last_idle_behavior_ = idle_behavior; last_idle_controlled_ = idle_controlled; diff --git a/chromium/chrome/browser/ui/webui/settings/chromeos/device_storage_handler.cc b/chromium/chrome/browser/ui/webui/settings/chromeos/device_storage_handler.cc index a846c92fd02..8553ff4c95e 100644 --- a/chromium/chrome/browser/ui/webui/settings/chromeos/device_storage_handler.cc +++ b/chromium/chrome/browser/ui/webui/settings/chromeos/device_storage_handler.cc @@ -15,7 +15,6 @@ #include "chrome/browser/browser_process.h" #include "chrome/browser/browsing_data/browsing_data_appcache_helper.h" #include "chrome/browser/browsing_data/browsing_data_cache_storage_helper.h" -#include "chrome/browser/browsing_data/browsing_data_channel_id_helper.h" #include "chrome/browser/browsing_data/browsing_data_cookie_helper.h" #include "chrome/browser/browsing_data/browsing_data_database_helper.h" #include "chrome/browser/browsing_data/browsing_data_file_system_helper.h" @@ -103,6 +102,11 @@ void StorageHandler::RegisterMessages() { base::Unretained(this))); } +void StorageHandler::OnJavascriptDisallowed() { + // Ensure that pending callbacks do not complete and cause JS to be evaluated. + weak_ptr_factory_.InvalidateWeakPtrs(); +} + void StorageHandler::HandleUpdateStorageInfo(const base::ListValue* args) { AllowJavascript(); @@ -249,7 +253,6 @@ void StorageHandler::UpdateBrowsingDataSize() { storage_partition->GetIndexedDBContext()), BrowsingDataFileSystemHelper::Create( storage_partition->GetFileSystemContext()), - BrowsingDataChannelIDHelper::Create(profile_->GetRequestContext()), new BrowsingDataServiceWorkerHelper( storage_partition->GetServiceWorkerContext()), new BrowsingDataCacheStorageHelper( @@ -290,10 +293,8 @@ void StorageHandler::OnGetBrowsingDataSize(bool is_site_data, int64_t size) { } void StorageHandler::UpdateAndroidSize() { - if (!arc::IsArcPlayStoreEnabledForProfile(profile_) || - arc::IsArcOptInVerificationDisabled()) { + if (!arc::IsArcPlayStoreEnabledForProfile(profile_)) return; - } if (updating_android_size_) return; diff --git a/chromium/chrome/browser/ui/webui/settings/chromeos/device_storage_handler.h b/chromium/chrome/browser/ui/webui/settings/chromeos/device_storage_handler.h index 7021667406a..64c8c6f6833 100644 --- a/chromium/chrome/browser/ui/webui/settings/chromeos/device_storage_handler.h +++ b/chromium/chrome/browser/ui/webui/settings/chromeos/device_storage_handler.h @@ -44,7 +44,7 @@ class StorageHandler : public ::settings::SettingsPageUIHandler { // SettingsPageUIHandler implementation. void RegisterMessages() override; void OnJavascriptAllowed() override {} - void OnJavascriptDisallowed() override {} + void OnJavascriptDisallowed() override; private: // Handlers of JS messages. diff --git a/chromium/chrome/browser/ui/webui/settings/chromeos/fingerprint_handler.cc b/chromium/chrome/browser/ui/webui/settings/chromeos/fingerprint_handler.cc index 7058fb6c087..7ddc716d6c6 100644 --- a/chromium/chrome/browser/ui/webui/settings/chromeos/fingerprint_handler.cc +++ b/chromium/chrome/browser/ui/webui/settings/chromeos/fingerprint_handler.cc @@ -124,7 +124,7 @@ void FingerprintHandler::OnJavascriptDisallowed() { void FingerprintHandler::OnRestarted() {} -void FingerprintHandler::OnEnrollScanDone(uint32_t scan_result, +void FingerprintHandler::OnEnrollScanDone(device::mojom::ScanResult scan_result, bool enroll_session_complete, int percent_complete) { VLOG(1) << "Receive fingerprint enroll scan result. scan_result=" @@ -132,7 +132,7 @@ void FingerprintHandler::OnEnrollScanDone(uint32_t scan_result, << ", enroll_session_complete=" << enroll_session_complete << ", percent_complete=" << percent_complete; auto scan_attempt = std::make_unique<base::DictionaryValue>(); - scan_attempt->SetInteger("result", scan_result); + scan_attempt->SetInteger("result", static_cast<int>(scan_result)); scan_attempt->SetBoolean("isComplete", enroll_session_complete); scan_attempt->SetInteger("percentComplete", percent_complete); @@ -140,7 +140,7 @@ void FingerprintHandler::OnEnrollScanDone(uint32_t scan_result, } void FingerprintHandler::OnAuthScanDone( - uint32_t scan_result, + device::mojom::ScanResult scan_result, const base::flat_map<std::string, std::vector<std::string>>& matches) { VLOG(1) << "Receive fingerprint auth scan result. scan_result=" << scan_result; @@ -164,7 +164,7 @@ void FingerprintHandler::OnAuthScanDone( } auto fingerprint_attempt = std::make_unique<base::DictionaryValue>(); - fingerprint_attempt->SetInteger("result", scan_result); + fingerprint_attempt->SetInteger("result", static_cast<int>(scan_result)); fingerprint_attempt->Set("indexes", std::move(fingerprint_ids)); FireWebUIListener("on-fingerprint-attempt-received", *fingerprint_attempt); diff --git a/chromium/chrome/browser/ui/webui/settings/chromeos/fingerprint_handler.h b/chromium/chrome/browser/ui/webui/settings/chromeos/fingerprint_handler.h index db0c60aec42..e4d6c7e1fad 100644 --- a/chromium/chrome/browser/ui/webui/settings/chromeos/fingerprint_handler.h +++ b/chromium/chrome/browser/ui/webui/settings/chromeos/fingerprint_handler.h @@ -38,14 +38,13 @@ class FingerprintHandler : public ::settings::SettingsPageUIHandler, void OnJavascriptAllowed() override; void OnJavascriptDisallowed() override; - private: // device::mojom::FingerprintObserver: void OnRestarted() override; - void OnEnrollScanDone(uint32_t scan_result, + void OnEnrollScanDone(device::mojom::ScanResult scan_result, bool enroll_session_complete, int percent_complete) override; void OnAuthScanDone( - uint32_t scan_result, + device::mojom::ScanResult scan_result, const base::flat_map<std::string, std::vector<std::string>>& matches) override; void OnSessionFailed() override; @@ -53,6 +52,7 @@ class FingerprintHandler : public ::settings::SettingsPageUIHandler, // session_manager::SessionManagerObserver: void OnSessionStateChanged() override; + private: void HandleGetFingerprintsList(const base::ListValue* args); void HandleGetNumFingerprints(const base::ListValue* args); void HandleStartEnroll(const base::ListValue* args); diff --git a/chromium/chrome/browser/ui/webui/settings/chromeos/google_assistant_handler.cc b/chromium/chrome/browser/ui/webui/settings/chromeos/google_assistant_handler.cc index ee3fc39b648..dc187325511 100644 --- a/chromium/chrome/browser/ui/webui/settings/chromeos/google_assistant_handler.cc +++ b/chromium/chrome/browser/ui/webui/settings/chromeos/google_assistant_handler.cc @@ -10,9 +10,10 @@ #include "ash/public/interfaces/constants.mojom.h" #include "base/bind.h" #include "base/values.h" -#include "chrome/browser/chromeos/arc/voice_interaction/arc_voice_interaction_framework_service.h" #include "chrome/browser/profiles/profile.h" -#include "chromeos/chromeos_switches.h" +#include "chrome/browser/ui/webui/chromeos/assistant_optin/assistant_optin_ui.h" +#include "chromeos/constants/chromeos_switches.h" +#include "components/arc/arc_prefs.h" #include "components/arc/arc_service_manager.h" #include "content/public/browser/browser_context.h" #include "services/service_manager/public/cpp/connector.h" @@ -22,7 +23,7 @@ namespace chromeos { namespace settings { GoogleAssistantHandler::GoogleAssistantHandler(Profile* profile) - : profile_(profile) {} + : profile_(profile), weak_factory_(this) {} GoogleAssistantHandler::~GoogleAssistantHandler() {} @@ -31,52 +32,19 @@ void GoogleAssistantHandler::OnJavascriptDisallowed() {} void GoogleAssistantHandler::RegisterMessages() { web_ui()->RegisterMessageCallback( - "setGoogleAssistantEnabled", - base::BindRepeating( - &GoogleAssistantHandler::HandleSetGoogleAssistantEnabled, - base::Unretained(this))); - web_ui()->RegisterMessageCallback( - "setGoogleAssistantContextEnabled", - base::BindRepeating( - &GoogleAssistantHandler::HandleSetGoogleAssistantContextEnabled, - base::Unretained(this))); - web_ui()->RegisterMessageCallback( "showGoogleAssistantSettings", base::BindRepeating( &GoogleAssistantHandler::HandleShowGoogleAssistantSettings, base::Unretained(this))); web_ui()->RegisterMessageCallback( - "turnOnGoogleAssistant", - base::BindRepeating(&GoogleAssistantHandler::HandleTurnOnGoogleAssistant, + "retrainAssistantVoiceModel", + base::BindRepeating(&GoogleAssistantHandler::HandleRetrainVoiceModel, base::Unretained(this))); } -void GoogleAssistantHandler::HandleSetGoogleAssistantEnabled( - const base::ListValue* args) { - CHECK_EQ(1U, args->GetSize()); - bool enabled; - CHECK(args->GetBoolean(0, &enabled)); - - auto* service = - arc::ArcVoiceInteractionFrameworkService::GetForBrowserContext(profile_); - if (service) - service->SetVoiceInteractionEnabled(enabled, base::BindOnce([](bool) {})); -} - -void GoogleAssistantHandler::HandleSetGoogleAssistantContextEnabled( - const base::ListValue* args) { - CHECK_EQ(1U, args->GetSize()); - bool enabled; - CHECK(args->GetBoolean(0, &enabled)); - - auto* service = - arc::ArcVoiceInteractionFrameworkService::GetForBrowserContext(profile_); - if (service) - service->SetVoiceInteractionContextEnabled(enabled); -} - void GoogleAssistantHandler::HandleShowGoogleAssistantSettings( const base::ListValue* args) { + CHECK_EQ(0U, args->GetSize()); if (chromeos::switches::IsAssistantEnabled()) { // Opens Google Assistant settings. service_manager::Connector* connector = @@ -84,21 +52,23 @@ void GoogleAssistantHandler::HandleShowGoogleAssistantSettings( ash::mojom::AssistantControllerPtr assistant_controller; connector->BindInterface(ash::mojom::kServiceName, &assistant_controller); assistant_controller->OpenAssistantSettings(); - return; } - - auto* service = - arc::ArcVoiceInteractionFrameworkService::GetForBrowserContext(profile_); - if (service) - service->ShowVoiceInteractionSettings(); } -void GoogleAssistantHandler::HandleTurnOnGoogleAssistant( +void GoogleAssistantHandler::HandleRetrainVoiceModel( const base::ListValue* args) { - auto* service = - arc::ArcVoiceInteractionFrameworkService::GetForBrowserContext(profile_); - if (service) - service->StartSessionFromUserInteraction(gfx::Rect()); + CHECK_EQ(0U, args->GetSize()); + chromeos::AssistantOptInDialog::Show( + ash::mojom::FlowType::SPEAKER_ID_ENROLLMENT, base::DoNothing()); +} + +void GoogleAssistantHandler::BindAssistantSettingsManager() { + DCHECK(!settings_manager_.is_bound()); + + // Set up settings mojom. + service_manager::Connector* connector = + content::BrowserContext::GetConnectorFor(profile_); + connector->BindInterface(assistant::mojom::kServiceName, &settings_manager_); } } // namespace settings diff --git a/chromium/chrome/browser/ui/webui/settings/chromeos/google_assistant_handler.h b/chromium/chrome/browser/ui/webui/settings/chromeos/google_assistant_handler.h index 8ae9aab037c..d99ede18195 100644 --- a/chromium/chrome/browser/ui/webui/settings/chromeos/google_assistant_handler.h +++ b/chromium/chrome/browser/ui/webui/settings/chromeos/google_assistant_handler.h @@ -7,6 +7,8 @@ #include "base/macros.h" #include "chrome/browser/ui/webui/settings/settings_page_ui_handler.h" +#include "chromeos/services/assistant/public/mojom/settings.mojom.h" +#include "mojo/public/cpp/bindings/binding.h" class Profile; @@ -23,17 +25,23 @@ class GoogleAssistantHandler : public ::settings::SettingsPageUIHandler { void OnJavascriptDisallowed() override; private: - // WebUI call to enable the Google Assistant. - void HandleSetGoogleAssistantEnabled(const base::ListValue* args); - // WebUI call to enable context for the Google Assistant. - void HandleSetGoogleAssistantContextEnabled(const base::ListValue* args); // WebUI call to launch into the Google Assistant app settings. void HandleShowGoogleAssistantSettings(const base::ListValue* args); - // WebUI call to launch assistant runtime flow. - void HandleTurnOnGoogleAssistant(const base::ListValue* args); + // WebUI call to retrain Assistant voice model. + void HandleRetrainVoiceModel(const base::ListValue* args); + + // Bind to assistant settings manager. + void BindAssistantSettingsManager(); + + // Callback for deleting voice model. + void DeleteVoiceModelCallback(); Profile* const profile_; + assistant::mojom::AssistantSettingsManagerPtr settings_manager_; + + base::WeakPtrFactory<GoogleAssistantHandler> weak_factory_; + DISALLOW_COPY_AND_ASSIGN(GoogleAssistantHandler); }; diff --git a/chromium/chrome/browser/ui/webui/settings/chromeos/multidevice_handler.cc b/chromium/chrome/browser/ui/webui/settings/chromeos/multidevice_handler.cc index aaf9de111c8..31a51283808 100644 --- a/chromium/chrome/browser/ui/webui/settings/chromeos/multidevice_handler.cc +++ b/chromium/chrome/browser/ui/webui/settings/chromeos/multidevice_handler.cc @@ -8,13 +8,13 @@ #include "base/bind_helpers.h" #include "base/logging.h" #include "base/values.h" +#include "chrome/browser/chromeos/android_sms/android_sms_pairing_state_tracker_impl.h" #include "chrome/browser/chromeos/android_sms/android_sms_urls.h" #include "chrome/browser/chromeos/login/quick_unlock/quick_unlock_factory.h" #include "chrome/browser/chromeos/login/quick_unlock/quick_unlock_storage.h" -#include "chrome/browser/chromeos/multidevice_setup/android_sms_app_helper_delegate_impl.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/ui/webui/chromeos/multidevice_setup/multidevice_setup_dialog.h" -#include "chromeos/components/proximity_auth/logging/logging.h" +#include "chromeos/components/multidevice/logging/logging.h" #include "chromeos/components/proximity_auth/proximity_auth_pref_names.h" #include "chromeos/services/multidevice_setup/public/cpp/prefs.h" #include "components/content_settings/core/common/content_settings_pattern.h" @@ -34,6 +34,7 @@ const char kPageContentDataBetterTogetherStateKey[] = "betterTogetherState"; const char kPageContentDataInstantTetheringStateKey[] = "instantTetheringState"; const char kPageContentDataMessagesStateKey[] = "messagesState"; const char kPageContentDataSmartLockStateKey[] = "smartLockState"; +const char kIsAndroidSmsPairingComplete[] = "isAndroidSmsPairingComplete"; constexpr char kAndroidSmsInfoOriginKey[] = "origin"; constexpr char kAndroidSmsInfoEnabledKey[] = "enabled"; @@ -51,12 +52,16 @@ void OnRetrySetHostNowResult(bool success) { MultideviceHandler::MultideviceHandler( PrefService* prefs, multidevice_setup::MultiDeviceSetupClient* multidevice_setup_client, - std::unique_ptr<multidevice_setup::AndroidSmsAppHelperDelegate> - android_sms_app_helper) + multidevice_setup::AndroidSmsPairingStateTracker* + android_sms_pairing_state_tracker, + android_sms::AndroidSmsAppManager* android_sms_app_manager) : prefs_(prefs), multidevice_setup_client_(multidevice_setup_client), - android_sms_app_helper_(std::move(android_sms_app_helper)), + android_sms_pairing_state_tracker_(android_sms_pairing_state_tracker), + android_sms_app_manager_(android_sms_app_manager), multidevice_setup_observer_(this), + android_sms_pairing_state_tracker_observer_(this), + android_sms_app_manager_observer_(this), callback_weak_ptr_factory_(this) { RegisterPrefChangeListeners(); } @@ -109,12 +114,28 @@ void MultideviceHandler::RegisterMessages() { void MultideviceHandler::OnJavascriptAllowed() { if (multidevice_setup_client_) multidevice_setup_observer_.Add(multidevice_setup_client_); + + if (android_sms_pairing_state_tracker_) { + android_sms_pairing_state_tracker_observer_.Add( + android_sms_pairing_state_tracker_); + } + + if (android_sms_app_manager_) + android_sms_app_manager_observer_.Add(android_sms_app_manager_); } void MultideviceHandler::OnJavascriptDisallowed() { if (multidevice_setup_client_) multidevice_setup_observer_.Remove(multidevice_setup_client_); + if (android_sms_pairing_state_tracker_) { + android_sms_pairing_state_tracker_observer_.Remove( + android_sms_pairing_state_tracker_); + } + + if (android_sms_app_manager_) + android_sms_app_manager_observer_.Remove(android_sms_app_manager_); + // Ensure that pending callbacks do not complete and cause JS to be evaluated. callback_weak_ptr_factory_.InvalidateWeakPtrs(); } @@ -133,6 +154,16 @@ void MultideviceHandler::OnFeatureStatesChanged( NotifyAndroidSmsInfoChange(); } +void MultideviceHandler::OnPairingStateChanged() { + UpdatePageContent(); + NotifyAndroidSmsInfoChange(); +} + +void MultideviceHandler::OnInstalledAppUrlChanged() { + UpdatePageContent(); + NotifyAndroidSmsInfoChange(); +} + void MultideviceHandler::UpdatePageContent() { std::unique_ptr<base::DictionaryValue> page_content_dictionary = GeneratePageContentDataDictionary(); @@ -214,7 +245,7 @@ void MultideviceHandler::HandleRetryPendingHostSetup( void MultideviceHandler::HandleSetUpAndroidSms(const base::ListValue* args) { DCHECK(args->empty()); - android_sms_app_helper_->SetUpAndLaunchAndroidSmsApp(); + android_sms_app_manager_->SetUpAndLaunchAndroidSmsApp(); } void MultideviceHandler::HandleGetSmartLockSignInEnabled( @@ -261,12 +292,16 @@ void MultideviceHandler::HandleGetSmartLockSignInAllowed( std::unique_ptr<base::DictionaryValue> MultideviceHandler::GenerateAndroidSmsInfo() { + base::Optional<GURL> app_url; + if (android_sms_app_manager_) + app_url = android_sms_app_manager_->GetCurrentAppUrl(); + if (!app_url) + app_url = android_sms::GetAndroidMessagesURL(); + auto android_sms_info = std::make_unique<base::DictionaryValue>(); android_sms_info->SetString( kAndroidSmsInfoOriginKey, - ContentSettingsPattern::FromURLNoWildcard( - chromeos::android_sms::GetAndroidMessagesURL()) - .ToString()); + ContentSettingsPattern::FromURLNoWildcard(*app_url).ToString()); chromeos::multidevice_setup::mojom::FeatureState messages_state = multidevice_setup_client_->GetFeatureState( @@ -332,6 +367,12 @@ MultideviceHandler::GeneratePageContentDataDictionary() { host_status_with_device.second->name()); } + page_content_dictionary->SetBoolean( + kIsAndroidSmsPairingComplete, + android_sms_pairing_state_tracker_ + ? android_sms_pairing_state_tracker_->IsAndroidSmsPairingComplete() + : false); + return page_content_dictionary; } diff --git a/chromium/chrome/browser/ui/webui/settings/chromeos/multidevice_handler.h b/chromium/chrome/browser/ui/webui/settings/chromeos/multidevice_handler.h index f585da37302..efb5ac7c6e9 100644 --- a/chromium/chrome/browser/ui/webui/settings/chromeos/multidevice_handler.h +++ b/chromium/chrome/browser/ui/webui/settings/chromeos/multidevice_handler.h @@ -8,10 +8,12 @@ #include "base/macros.h" #include "base/memory/weak_ptr.h" #include "base/scoped_observer.h" +#include "chrome/browser/chromeos/android_sms/android_sms_app_manager.h" +#include "chrome/browser/chromeos/android_sms/android_sms_service_factory.h" #include "chrome/browser/ui/webui/settings/settings_page_ui_handler.h" +#include "chromeos/components/multidevice/remote_device_ref.h" #include "chromeos/services/multidevice_setup/public/cpp/multidevice_setup_client.h" #include "chromeos/services/multidevice_setup/public/mojom/multidevice_setup.mojom.h" -#include "components/cryptauth/remote_device_ref.h" #include "components/prefs/pref_change_registrar.h" class PrefService; @@ -22,22 +24,21 @@ class DictionaryValue; namespace chromeos { -namespace multidevice_setup { -class AndroidSmsAppHelperDelegate; -} // namespace multidevice_setup - namespace settings { // Chrome "Multidevice" (a.k.a. "Connected Devices") settings page UI handler. class MultideviceHandler : public ::settings::SettingsPageUIHandler, - public multidevice_setup::MultiDeviceSetupClient::Observer { + public multidevice_setup::MultiDeviceSetupClient::Observer, + public multidevice_setup::AndroidSmsPairingStateTracker::Observer, + public android_sms::AndroidSmsAppManager::Observer { public: MultideviceHandler( PrefService* prefs, multidevice_setup::MultiDeviceSetupClient* multidevice_setup_client, - std::unique_ptr<multidevice_setup::AndroidSmsAppHelperDelegate> - android_sms_app_helper); + multidevice_setup::AndroidSmsPairingStateTracker* + android_sms_pairing_state_tracker, + android_sms::AndroidSmsAppManager* android_sms_app_manager); ~MultideviceHandler() override; protected: @@ -57,6 +58,12 @@ class MultideviceHandler const multidevice_setup::MultiDeviceSetupClient::FeatureStatesMap& feature_states_map) override; + // multidevice_setup::AndroidSmsPairingStateTracker::Observer: + void OnPairingStateChanged() override; + + // android_sms::AndroidSmsAppManager::Observer: + void OnInstalledAppUrlChanged() override; + // Sends the most recent PageContentData dictionary to the WebUI page as an // update (e.g., not due to a getPageContent() request). void UpdatePageContent(); @@ -104,12 +111,19 @@ class MultideviceHandler GetFeatureStatesMap(); multidevice_setup::MultiDeviceSetupClient* multidevice_setup_client_; - std::unique_ptr<multidevice_setup::AndroidSmsAppHelperDelegate> - android_sms_app_helper_; + multidevice_setup::AndroidSmsPairingStateTracker* + android_sms_pairing_state_tracker_; + android_sms::AndroidSmsAppManager* android_sms_app_manager_; ScopedObserver<multidevice_setup::MultiDeviceSetupClient, multidevice_setup::MultiDeviceSetupClient::Observer> multidevice_setup_observer_; + ScopedObserver<multidevice_setup::AndroidSmsPairingStateTracker, + multidevice_setup::AndroidSmsPairingStateTracker::Observer> + android_sms_pairing_state_tracker_observer_; + ScopedObserver<android_sms::AndroidSmsAppManager, + android_sms::AndroidSmsAppManager::Observer> + android_sms_app_manager_observer_; // Used to cancel callbacks when JavaScript becomes disallowed. base::WeakPtrFactory<MultideviceHandler> callback_weak_ptr_factory_; diff --git a/chromium/chrome/browser/ui/webui/settings/chromeos/multidevice_handler_unittest.cc b/chromium/chrome/browser/ui/webui/settings/chromeos/multidevice_handler_unittest.cc index 82e27cd59e4..8af51c05725 100644 --- a/chromium/chrome/browser/ui/webui/settings/chromeos/multidevice_handler_unittest.cc +++ b/chromium/chrome/browser/ui/webui/settings/chromeos/multidevice_handler_unittest.cc @@ -8,10 +8,11 @@ #include "base/macros.h" #include "chrome/browser/chromeos/android_sms/android_sms_urls.h" -#include "chromeos/services/multidevice_setup/public/cpp/fake_android_sms_app_helper_delegate.h" +#include "chrome/browser/chromeos/android_sms/fake_android_sms_app_manager.h" +#include "chromeos/components/multidevice/remote_device_test_util.h" +#include "chromeos/services/multidevice_setup/public/cpp/fake_android_sms_pairing_state_tracker.h" #include "chromeos/services/multidevice_setup/public/cpp/fake_multidevice_setup_client.h" #include "components/content_settings/core/common/content_settings_pattern.h" -#include "components/cryptauth/remote_device_test_util.h" #include "components/prefs/testing_pref_service.h" #include "content/public/test/test_web_ui.h" #include "testing/gtest/include/gtest/gtest.h" @@ -27,11 +28,13 @@ class TestMultideviceHandler : public MultideviceHandler { TestMultideviceHandler( PrefService* prefs, multidevice_setup::MultiDeviceSetupClient* multidevice_setup_client, - std::unique_ptr<multidevice_setup::AndroidSmsAppHelperDelegate> - android_sms_app_helper) + multidevice_setup::AndroidSmsPairingStateTracker* + android_sms_pairing_state_tracker, + android_sms::AndroidSmsAppManager* android_sms_app_manager) : MultideviceHandler(prefs, multidevice_setup_client, - std::move(android_sms_app_helper)) {} + android_sms_pairing_state_tracker, + android_sms_app_manager) {} ~TestMultideviceHandler() override = default; // Make public for testing. @@ -56,7 +59,7 @@ GenerateDefaultFeatureStatesMap() { void VerifyPageContentDict( const base::Value* value, multidevice_setup::mojom::HostStatus expected_host_status, - const base::Optional<cryptauth::RemoteDeviceRef>& expected_host_device, + const base::Optional<multidevice::RemoteDeviceRef>& expected_host_device, const multidevice_setup::MultiDeviceSetupClient::FeatureStatesMap& feature_states_map) { const base::DictionaryValue* page_content_dict; @@ -107,7 +110,7 @@ void VerifyPageContentDict( class MultideviceHandlerTest : public testing::Test { protected: MultideviceHandlerTest() - : test_device_(cryptauth::CreateRemoteDeviceRefForTest()) {} + : test_device_(multidevice::CreateRemoteDeviceRefForTest()) {} ~MultideviceHandlerTest() override = default; // testing::Test: @@ -116,16 +119,17 @@ class MultideviceHandlerTest : public testing::Test { fake_multidevice_setup_client_ = std::make_unique<multidevice_setup::FakeMultiDeviceSetupClient>(); - auto fake_android_sms_app_helper_delegate = - std::make_unique<multidevice_setup::FakeAndroidSmsAppHelperDelegate>(); - fake_android_sms_app_helper_delegate_ = - fake_android_sms_app_helper_delegate.get(); + fake_android_sms_pairing_state_tracker_ = std::make_unique< + multidevice_setup::FakeAndroidSmsPairingStateTracker>(); + fake_android_sms_app_manager_ = + std::make_unique<android_sms::FakeAndroidSmsAppManager>(); prefs_.reset(new TestingPrefServiceSimple()); handler_ = std::make_unique<TestMultideviceHandler>( prefs_.get(), fake_multidevice_setup_client_.get(), - std::move(fake_android_sms_app_helper_delegate)); + fake_android_sms_pairing_state_tracker_.get(), + fake_android_sms_app_manager_.get()); handler_->set_web_ui(test_web_ui_.get()); handler_->RegisterMessages(); handler_->AllowJavascript(); @@ -158,7 +162,7 @@ class MultideviceHandlerTest : public testing::Test { fake_multidevice_setup_client()->num_remove_host_device_called()); } - void CallGetAndroidSmsInfo(bool enabled) { + void CallGetAndroidSmsInfo(bool expected_enabled, const GURL& expected_url) { size_t call_data_count_before_call = test_web_ui()->call_data().size(); base::ListValue args; @@ -172,16 +176,16 @@ class MultideviceHandlerTest : public testing::Test { EXPECT_EQ("cr.webUIResponse", call_data.function_name()); EXPECT_EQ("handlerFunctionName", call_data.arg1()->GetString()); ASSERT_TRUE(call_data.arg2()->GetBool()); - EXPECT_EQ(ContentSettingsPattern::FromURLNoWildcard( - chromeos::android_sms::GetAndroidMessagesURL()) - .ToString(), - call_data.arg3()->FindKey("origin")->GetString()); - EXPECT_EQ(enabled, call_data.arg3()->FindKey("enabled")->GetBool()); + EXPECT_EQ( + ContentSettingsPattern::FromURLNoWildcard(expected_url).ToString(), + call_data.arg3()->FindKey("origin")->GetString()); + EXPECT_EQ(expected_enabled, + call_data.arg3()->FindKey("enabled")->GetBool()); } void SimulateHostStatusUpdate( multidevice_setup::mojom::HostStatus host_status, - const base::Optional<cryptauth::RemoteDeviceRef>& host_device) { + const base::Optional<multidevice::RemoteDeviceRef>& host_device) { size_t call_data_count_before_call = test_web_ui()->call_data().size(); fake_multidevice_setup_client_->SetHostStatusWithDevice( @@ -214,6 +218,22 @@ class MultideviceHandlerTest : public testing::Test { VerifyPageContent(call_data.arg2()); } + void SimulatePairingStateUpdate(bool is_android_sms_pairing_complete) { + size_t call_data_count_before_call = test_web_ui()->call_data().size(); + + fake_android_sms_pairing_state_tracker_->SetPairingComplete( + is_android_sms_pairing_complete); + EXPECT_EQ(call_data_count_before_call + 2u, + test_web_ui()->call_data().size()); + + const content::TestWebUI::CallData& call_data = + CallDataAtIndex(call_data_count_before_call); + EXPECT_EQ("cr.webUIListenerCallback", call_data.function_name()); + EXPECT_EQ("settings.updateMultidevicePageContentData", + call_data.arg1()->GetString()); + VerifyPageContent(call_data.arg2()); + } + void CallRetryPendingHostSetup(bool success) { base::ListValue empty_args; test_web_ui()->HandleReceivedMessage("retryPendingHostSetup", &empty_args); @@ -267,12 +287,11 @@ class MultideviceHandlerTest : public testing::Test { return fake_multidevice_setup_client_.get(); } - multidevice_setup::FakeAndroidSmsAppHelperDelegate* - fake_android_sms_app_helper_delegate() { - return fake_android_sms_app_helper_delegate_; + android_sms::FakeAndroidSmsAppManager* fake_android_sms_app_manager() { + return fake_android_sms_app_manager_.get(); } - const cryptauth::RemoteDeviceRef test_device_; + const multidevice::RemoteDeviceRef test_device_; private: void VerifyPageContent(const base::Value* value) { @@ -286,14 +305,17 @@ class MultideviceHandlerTest : public testing::Test { std::unique_ptr<content::TestWebUI> test_web_ui_; std::unique_ptr<multidevice_setup::FakeMultiDeviceSetupClient> fake_multidevice_setup_client_; - std::unique_ptr<TestMultideviceHandler> handler_; + std::unique_ptr<multidevice_setup::FakeAndroidSmsPairingStateTracker> + fake_android_sms_pairing_state_tracker_; multidevice_setup::MultiDeviceSetupClient::HostStatusWithDevice host_status_with_device_; multidevice_setup::MultiDeviceSetupClient::FeatureStatesMap feature_states_map_; - multidevice_setup::FakeAndroidSmsAppHelperDelegate* - fake_android_sms_app_helper_delegate_; + std::unique_ptr<android_sms::FakeAndroidSmsAppManager> + fake_android_sms_app_manager_; + + std::unique_ptr<TestMultideviceHandler> handler_; DISALLOW_COPY_AND_ASSIGN(MultideviceHandlerTest); }; @@ -323,6 +345,8 @@ TEST_F(MultideviceHandlerTest, PageContentData) { feature_states_map[multidevice_setup::mojom::Feature::kBetterTogetherSuite] = multidevice_setup::mojom::FeatureState::kDisabledByUser; SimulateFeatureStatesUpdate(feature_states_map); + + SimulatePairingStateUpdate(/*is_android_sms_pairing_complete=*/true); } TEST_F(MultideviceHandlerTest, RetryPendingHostSetup) { @@ -331,11 +355,11 @@ TEST_F(MultideviceHandlerTest, RetryPendingHostSetup) { } TEST_F(MultideviceHandlerTest, SetUpAndroidSms) { - EXPECT_FALSE(fake_android_sms_app_helper_delegate()->HasInstalledApp()); - EXPECT_FALSE(fake_android_sms_app_helper_delegate()->HasLaunchedApp()); + EXPECT_FALSE(fake_android_sms_app_manager()->has_installed_app()); + EXPECT_FALSE(fake_android_sms_app_manager()->has_launched_app()); CallSetUpAndroidSms(); - EXPECT_TRUE(fake_android_sms_app_helper_delegate()->HasInstalledApp()); - EXPECT_TRUE(fake_android_sms_app_helper_delegate()->HasLaunchedApp()); + EXPECT_TRUE(fake_android_sms_app_manager()->has_installed_app()); + EXPECT_TRUE(fake_android_sms_app_manager()->has_launched_app()); } TEST_F(MultideviceHandlerTest, SetFeatureEnabledState) { @@ -358,7 +382,9 @@ TEST_F(MultideviceHandlerTest, RemoveHostDevice) { TEST_F(MultideviceHandlerTest, GetAndroidSmsInfo) { // Check that getAndroidSmsInfo returns correct value. - CallGetAndroidSmsInfo(false /* enabled */); + CallGetAndroidSmsInfo(false /* expected_enabled */, + android_sms::GetAndroidMessagesURL( + true /* use_install_url */) /* expected_url */); // Change messages feature state and assert that the change // callback is fired. @@ -369,13 +395,28 @@ TEST_F(MultideviceHandlerTest, GetAndroidSmsInfo) { size_t call_data_count_before_call = test_web_ui()->call_data().size(); SimulateFeatureStatesUpdate(feature_states_map); - const content::TestWebUI::CallData& call_data = + const content::TestWebUI::CallData& call_data_1 = CallDataAtIndex(call_data_count_before_call + 1); - EXPECT_EQ("cr.webUIListenerCallback", call_data.function_name()); - EXPECT_EQ("settings.onAndroidSmsInfoChange", call_data.arg1()->GetString()); + EXPECT_EQ("cr.webUIListenerCallback", call_data_1.function_name()); + EXPECT_EQ("settings.onAndroidSmsInfoChange", call_data_1.arg1()->GetString()); // Check that getAndroidSmsInfo returns update value. - CallGetAndroidSmsInfo(true /* enabled */); + CallGetAndroidSmsInfo(true /* enabled */, android_sms::GetAndroidMessagesURL( + true) /* expected_url */); + + // Now, update the installed URL. This should have resulted in another call. + fake_android_sms_app_manager()->SetInstalledAppUrl( + android_sms::GetAndroidMessagesURL(true /* use_install_url */, + android_sms::PwaDomain::kStaging)); + const content::TestWebUI::CallData& call_data_2 = + CallDataAtIndex(call_data_count_before_call + 4); + EXPECT_EQ("cr.webUIListenerCallback", call_data_2.function_name()); + EXPECT_EQ("settings.onAndroidSmsInfoChange", call_data_2.arg1()->GetString()); + CallGetAndroidSmsInfo( + true /* enabled */, + android_sms::GetAndroidMessagesURL( + true /* use_install_url */, + android_sms::PwaDomain::kStaging) /* expected_url */); } } // namespace settings diff --git a/chromium/chrome/browser/ui/webui/settings/font_handler.cc b/chromium/chrome/browser/ui/webui/settings/font_handler.cc index ffb8f495ab7..1406eb7ae8a 100644 --- a/chromium/chrome/browser/ui/webui/settings/font_handler.cc +++ b/chromium/chrome/browser/ui/webui/settings/font_handler.cc @@ -108,10 +108,8 @@ const extensions::Extension* FontHandler::GetAdvancedFontSettingsExtension() { } void FontHandler::NotifyAdvancedFontSettingsAvailability() { - CallJavascriptFunction( - "cr.webUIListenerCallback", - base::Value("advanced-font-settings-installed"), - base::Value(GetAdvancedFontSettingsExtension() != nullptr)); + FireWebUIListener("advanced-font-settings-installed", + base::Value(GetAdvancedFontSettingsExtension() != nullptr)); } void FontHandler::OnExtensionLoaded(content::BrowserContext*, diff --git a/chromium/chrome/browser/ui/webui/settings/md_settings_localized_strings_provider.cc b/chromium/chrome/browser/ui/webui/settings/md_settings_localized_strings_provider.cc index ab6b01e39cf..b06ae469370 100644 --- a/chromium/chrome/browser/ui/webui/settings/md_settings_localized_strings_provider.cc +++ b/chromium/chrome/browser/ui/webui/settings/md_settings_localized_strings_provider.cc @@ -22,6 +22,7 @@ #include "chrome/browser/signin/account_consistency_mode_manager.h" #include "chrome/browser/sync/profile_sync_service_factory.h" #include "chrome/browser/ui/passwords/manage_passwords_view_utils.h" +#include "chrome/browser/ui/webui/localized_string.h" #include "chrome/browser/ui/webui/policy_indicator_localized_strings_provider.h" #include "chrome/common/chrome_features.h" #include "chrome/common/chrome_switches.h" @@ -58,15 +59,18 @@ #include "ash/public/interfaces/voice_interaction_controller.mojom.h" #include "base/system/sys_info.h" #include "chrome/browser/chromeos/arc/arc_util.h" +#include "chrome/browser/chromeos/crostini/crostini_util.h" #include "chrome/browser/chromeos/ownership/owner_settings_service_chromeos.h" #include "chrome/browser/chromeos/ownership/owner_settings_service_chromeos_factory.h" #include "chrome/browser/chromeos/policy/browser_policy_connector_chromeos.h" #include "chrome/browser/chromeos/profiles/profile_helper.h" +#include "chrome/browser/ui/webui/chromeos/assistant_optin/assistant_optin_utils.h" #include "chrome/browser/ui/webui/chromeos/bluetooth_dialog_localized_strings_provider.h" #include "chrome/browser/ui/webui/chromeos/network_element_localized_strings_provider.h" #include "chrome/browser/ui/webui/chromeos/smb_shares/smb_shares_localized_strings_provider.h" -#include "chromeos/chromeos_features.h" -#include "chromeos/chromeos_switches.h" +#include "chromeos/constants/chromeos_features.h" +#include "chromeos/constants/chromeos_switches.h" +#include "chromeos/services/assistant/public/features.h" #include "chromeos/services/multidevice_setup/public/cpp/url_provider.h" #include "chromeos/strings/grit/chromeos_strings.h" #include "components/user_manager/user_manager.h" @@ -84,10 +88,9 @@ #if defined(GOOGLE_CHROME_BUILD) #include "base/metrics/field_trial_params.h" #include "base/strings/strcat.h" -#include "base/strings/utf_string_conversions.h" #include "chrome/grit/chrome_unscaled_resources.h" #include "ui/base/resource/resource_bundle.h" -#endif +#endif // defined(GOOGLE_CHROME_BUILD) #endif // defined(OS_WIN) #if defined(USE_NSS_CERTS) @@ -101,11 +104,6 @@ namespace { // the following name. These names must be kept in sync. constexpr char kLocalizedStringsFile[] = "strings.js"; -struct LocalizedString { - const char* name; - int id; -}; - #if defined(OS_CHROMEOS) // Generates a Google Help URL which includes a "board type" parameter. Some // help pages need to be adjusted depending on the type of CrOS device that is @@ -116,17 +114,8 @@ base::string16 GetHelpUrlWithBoard(const std::string& original_url) { } #endif -void AddLocalizedStringsBulk(content::WebUIDataSource* html_source, - LocalizedString localized_strings[], - size_t num_strings) { - for (size_t i = 0; i < num_strings; i++) { - html_source->AddLocalizedString(localized_strings[i].name, - localized_strings[i].id); - } -} - void AddCommonStrings(content::WebUIDataSource* html_source, Profile* profile) { - LocalizedString localized_strings[] = { + static constexpr LocalizedString kLocalizedStrings[] = { {"add", IDS_ADD}, {"advancedPageTitle", IDS_SETTINGS_ADVANCED}, {"back", IDS_ACCNAME_BACK}, @@ -163,8 +152,8 @@ void AddCommonStrings(content::WebUIDataSource* html_source, Profile* profile) { {"notValidWebAddressForContentType", IDS_SETTINGS_NOT_VALID_WEB_ADDRESS_FOR_CONTENT_TYPE}, }; - AddLocalizedStringsBulk(html_source, localized_strings, - arraysize(localized_strings)); + AddLocalizedStringsBulk(html_source, kLocalizedStrings, + base::size(kLocalizedStrings)); html_source->AddBoolean( "isGuest", @@ -179,9 +168,12 @@ void AddCommonStrings(content::WebUIDataSource* html_source, Profile* profile) { } void AddA11yStrings(content::WebUIDataSource* html_source) { - LocalizedString localized_strings[] = { + static constexpr LocalizedString kLocalizedStrings[] = { {"a11yPageTitle", IDS_SETTINGS_ACCESSIBILITY}, {"a11yWebStore", IDS_SETTINGS_ACCESSIBILITY_WEB_STORE}, + {"accessibleImageLabelsTitle", IDS_SETTINGS_ACCESSIBLE_IMAGE_LABELS_TITLE}, + {"accessibleImageLabelsSubtitle", + IDS_SETTINGS_ACCESSIBLE_IMAGE_LABELS_SUBTITLE}, {"moreFeaturesLink", IDS_SETTINGS_MORE_FEATURES_LINK}, {"moreFeaturesLinkDescription", IDS_SETTINGS_MORE_FEATURES_LINK_DESCRIPTION}, @@ -325,8 +317,13 @@ void AddA11yStrings(content::WebUIDataSource* html_source) { {"textToSpeechEngines", IDS_SETTINGS_TEXT_TO_SPEECH_ENGINES}, #endif }; - AddLocalizedStringsBulk(html_source, localized_strings, - arraysize(localized_strings)); + AddLocalizedStringsBulk(html_source, kLocalizedStrings, + base::size(kLocalizedStrings)); + + base::CommandLine& cmd = *base::CommandLine::ForCurrentProcess(); + html_source->AddBoolean( + "showExperimentalA11yLabels", + cmd.HasSwitch(::switches::kEnableExperimentalAccessibilityLabels)); #if defined(OS_CHROMEOS) html_source->AddString("a11yLearnMoreUrl", @@ -334,18 +331,15 @@ void AddA11yStrings(content::WebUIDataSource* html_source) { html_source->AddBoolean( "showExperimentalA11yFeatures", - base::CommandLine::ForCurrentProcess()->HasSwitch( - ::switches::kEnableExperimentalAccessibilityFeatures)); + cmd.HasSwitch(::switches::kEnableExperimentalAccessibilityFeatures)); html_source->AddBoolean( "showExperimentalAccessibilityAutoclick", - base::CommandLine::ForCurrentProcess()->HasSwitch( - ::switches::kEnableExperimentalAccessibilityAutoclick)); + cmd.HasSwitch(::switches::kEnableExperimentalAccessibilityAutoclick)); html_source->AddBoolean( "showExperimentalAccessibilitySwitchAccess", - base::CommandLine::ForCurrentProcess()->HasSwitch( - ::switches::kEnableExperimentalAccessibilitySwitchAccess)); + cmd.HasSwitch(::switches::kEnableExperimentalAccessibilitySwitchAccess)); html_source->AddBoolean("dockedMagnifierFeatureEnabled", ash::features::IsDockedMagnifierEnabled()); @@ -353,7 +347,7 @@ void AddA11yStrings(content::WebUIDataSource* html_source) { } void AddAboutStrings(content::WebUIDataSource* html_source) { - LocalizedString localized_strings[] = { + static constexpr LocalizedString kLocalizedStrings[] = { {"aboutProductLogoAlt", IDS_SHORT_PRODUCT_LOGO_ALT_TEXT}, {"aboutPageTitle", IDS_SETTINGS_ABOUT_PROGRAM}, #if defined(OS_CHROMEOS) @@ -428,8 +422,8 @@ void AddAboutStrings(content::WebUIDataSource* html_source) { IDS_SETTINGS_ABOUT_PAGE_UPDATE_WARNING_CONTINUE_BUTTON}, #endif // defined(OS_CHROMEOS) }; - AddLocalizedStringsBulk(html_source, localized_strings, - arraysize(localized_strings)); + AddLocalizedStringsBulk(html_source, kLocalizedStrings, + base::size(kLocalizedStrings)); html_source->AddString( "aboutUpgradeUpToDate", @@ -447,20 +441,41 @@ void AddAboutStrings(content::WebUIDataSource* html_source) { #if defined(OS_CHROMEOS) void AddCrostiniStrings(content::WebUIDataSource* html_source) { - LocalizedString localized_strings[] = { + static constexpr LocalizedString kLocalizedStrings[] = { {"crostiniPageTitle", IDS_SETTINGS_CROSTINI_TITLE}, {"crostiniPageLabel", IDS_SETTINGS_CROSTINI_LABEL}, {"crostiniEnable", IDS_SETTINGS_TURN_ON}, {"crostiniRemove", IDS_SETTINGS_CROSTINI_REMOVE}, {"crostiniSharedPaths", IDS_SETTINGS_CROSTINI_SHARED_PATHS}, + {"crostiniSharedPathsListHeading", + IDS_SETTINGS_CROSTINI_SHARED_PATHS_LIST_HEADING}, + {"crostiniSharedPathsInstructionsAdd", + IDS_SETTINGS_CROSTINI_SHARED_PATHS_INSTRUCTIONS_ADD}, + {"crostiniSharedPathsInstructionsRemove", + IDS_SETTINGS_CROSTINI_SHARED_PATHS_INSTRUCTIONS_REMOVE}, + {"crostiniSharedPathsRemoveSharing", + IDS_SETTINGS_CROSTINI_SHARED_PATHS_REMOVE_SHARING}, + {"crostiniSharedUsbDevicesLabel", + IDS_SETTINGS_CROSTINI_SHARED_USB_DEVICES_LABEL}, + {"crostiniSharedUsbDevicesDescription", + IDS_SETTINGS_CROSTINI_SHARED_USB_DEVICES_DESCRIPTION}, }; - AddLocalizedStringsBulk(html_source, localized_strings, - arraysize(localized_strings)); + AddLocalizedStringsBulk(html_source, kLocalizedStrings, + base::size(kLocalizedStrings)); html_source->AddString( "crostiniSubtext", l10n_util::GetStringFUTF16( IDS_SETTINGS_CROSTINI_SUBTEXT, GetHelpUrlWithBoard(chrome::kLinuxAppsLearnMoreURL))); + html_source->AddString( + "crostiniSharedPathsInstructionsLocate", + l10n_util::GetStringFUTF16( + IDS_SETTINGS_CROSTINI_SHARED_PATHS_INSTRUCTIONS_LOCATE, + base::ASCIIToUTF16( + crostini::ContainerChromeOSBaseDirectory().value()))); + html_source->AddBoolean( + "enableCrostiniUsbDeviceSupport", + base::FeatureList::IsEnabled(chromeos::features::kCrostiniUsbSupport)); } void AddAndroidAppStrings(content::WebUIDataSource* html_source) { @@ -481,7 +496,7 @@ void AddAndroidAppStrings(content::WebUIDataSource* html_source) { {"androidAppsManageAppLinks", IDS_SETTINGS_ANDROID_APPS_MANAGE_APP_LINKS}, }; AddLocalizedStringsBulk(html_source, localized_strings, - arraysize(localized_strings)); + base::size(localized_strings)); html_source->AddString( "androidAppsSubtext", l10n_util::GetStringFUTF16( @@ -492,7 +507,7 @@ void AddAndroidAppStrings(content::WebUIDataSource* html_source) { void AddAppearanceStrings(content::WebUIDataSource* html_source, Profile* profile) { - LocalizedString localized_strings[] = { + static constexpr LocalizedString kLocalizedStrings[] = { {"appearancePageTitle", IDS_SETTINGS_APPEARANCE}, {"customWebAddress", IDS_SETTINGS_CUSTOM_WEB_ADDRESS}, {"enterCustomWebAddress", IDS_SETTINGS_ENTER_CUSTOM_WEB_ADDRESS}, @@ -524,13 +539,13 @@ void AddAppearanceStrings(content::WebUIDataSource* html_source, {"warnBeforeQuitting", IDS_SETTINGS_WARN_BEFORE_QUITTING_PREF}, #endif }; - AddLocalizedStringsBulk(html_source, localized_strings, - arraysize(localized_strings)); + AddLocalizedStringsBulk(html_source, kLocalizedStrings, + base::size(kLocalizedStrings)); } #if defined(OS_CHROMEOS) void AddBluetoothStrings(content::WebUIDataSource* html_source) { - LocalizedString localized_strings[] = { + static constexpr LocalizedString kLocalizedStrings[] = { {"bluetoothConnected", IDS_SETTINGS_BLUETOOTH_CONNECTED}, {"bluetoothConnecting", IDS_SETTINGS_BLUETOOTH_CONNECTING}, {"bluetoothDeviceListPaired", IDS_SETTINGS_BLUETOOTH_DEVICE_LIST_PAIRED}, @@ -552,25 +567,25 @@ void AddBluetoothStrings(content::WebUIDataSource* html_source) { {"bluetoothPrimaryUserControlled", IDS_SETTINGS_BLUETOOTH_PRIMARY_USER_CONTROLLED}, }; - AddLocalizedStringsBulk(html_source, localized_strings, - arraysize(localized_strings)); + AddLocalizedStringsBulk(html_source, kLocalizedStrings, + base::size(kLocalizedStrings)); chromeos::bluetooth_dialog::AddLocalizedStrings(html_source); } #endif void AddChangePasswordStrings(content::WebUIDataSource* html_source) { - LocalizedString localized_strings[] = { + static constexpr LocalizedString kLocalizedStrings[] = { {"changePasswordPageTitle", IDS_SETTINGS_CHANGE_PASSWORD_TITLE}, {"changePasswordPageDetails", IDS_PAGE_INFO_CHANGE_PASSWORD_DETAILS}, {"changePasswordPageButton", IDS_SETTINGS_CHANGE_PASSWORD_BUTTON}, }; - AddLocalizedStringsBulk(html_source, localized_strings, - arraysize(localized_strings)); + AddLocalizedStringsBulk(html_source, kLocalizedStrings, + base::size(kLocalizedStrings)); } void AddClearBrowsingDataStrings(content::WebUIDataSource* html_source, Profile* profile) { - LocalizedString localized_strings[] = { + static constexpr LocalizedString kLocalizedStrings[] = { {"clearTimeRange", IDS_SETTINGS_CLEAR_PERIOD_TITLE}, {"clearBrowsingDataWithSync", IDS_SETTINGS_CLEAR_BROWSING_DATA_WITH_SYNC}, {"clearBrowsingDataWithSyncError", @@ -594,7 +609,6 @@ void AddClearBrowsingDataStrings(content::WebUIDataSource* html_source, {"clearPasswords", IDS_SETTINGS_CLEAR_PASSWORDS}, {"clearFormData", IDS_SETTINGS_CLEAR_FORM_DATA}, {"clearHostedAppData", IDS_SETTINGS_CLEAR_HOSTED_APP_DATA}, - {"clearMediaLicenses", IDS_SETTINGS_CLEAR_MEDIA_LICENSES}, {"clearPeriodHour", IDS_SETTINGS_CLEAR_PERIOD_HOUR}, {"clearPeriod24Hours", IDS_SETTINGS_CLEAR_PERIOD_24_HOURS}, {"clearPeriod7Days", IDS_SETTINGS_CLEAR_PERIOD_7_DAYS}, @@ -623,13 +637,13 @@ void AddClearBrowsingDataStrings(content::WebUIDataSource* html_source, l10n_util::GetStringUTF16( IDS_SETTINGS_CLEAR_DATA_MYACTIVITY_URL_IN_DIALOG))); - AddLocalizedStringsBulk(html_source, localized_strings, - arraysize(localized_strings)); + AddLocalizedStringsBulk(html_source, kLocalizedStrings, + base::size(kLocalizedStrings)); } #if !defined(OS_CHROMEOS) void AddDefaultBrowserStrings(content::WebUIDataSource* html_source) { - LocalizedString localized_strings[] = { + static constexpr LocalizedString kLocalizedStrings[] = { {"defaultBrowser", IDS_SETTINGS_DEFAULT_BROWSER}, {"defaultBrowserDefault", IDS_SETTINGS_DEFAULT_BROWSER_DEFAULT}, {"defaultBrowserMakeDefault", IDS_SETTINGS_DEFAULT_BROWSER_MAKE_DEFAULT}, @@ -638,24 +652,24 @@ void AddDefaultBrowserStrings(content::WebUIDataSource* html_source) { {"defaultBrowserError", IDS_SETTINGS_DEFAULT_BROWSER_ERROR}, {"defaultBrowserSecondary", IDS_SETTINGS_DEFAULT_BROWSER_SECONDARY}, }; - AddLocalizedStringsBulk(html_source, localized_strings, - arraysize(localized_strings)); + AddLocalizedStringsBulk(html_source, kLocalizedStrings, + base::size(kLocalizedStrings)); } #endif #if defined(OS_CHROMEOS) void AddDeviceStrings(content::WebUIDataSource* html_source) { - LocalizedString device_strings[] = { + static constexpr LocalizedString kDeviceStrings[] = { {"devicePageTitle", IDS_SETTINGS_DEVICE_TITLE}, {"scrollLabel", IDS_SETTINGS_SCROLL_LABEL}, {"traditionalScrollLabel", IDS_SETTINGS_TRADITIONAL_SCROLL_LABEL}, {"naturalScrollLabel", IDS_SETTINGS_NATURAL_SCROLL_LABEL}, {"naturalScrollLearnMore", IDS_LEARN_MORE}, }; - AddLocalizedStringsBulk(html_source, device_strings, - arraysize(device_strings)); + AddLocalizedStringsBulk(html_source, kDeviceStrings, + base::size(kDeviceStrings)); - LocalizedString pointers_strings[] = { + static constexpr LocalizedString kPointersStrings[] = { {"mouseTitle", IDS_SETTINGS_MOUSE_TITLE}, {"touchpadTitle", IDS_SETTINGS_TOUCHPAD_TITLE}, {"mouseAndTouchpadTitle", IDS_SETTINGS_MOUSE_AND_TOUCHPAD_TITLE}, @@ -668,8 +682,8 @@ void AddDeviceStrings(content::WebUIDataSource* html_source) { {"mouseSwapButtons", IDS_SETTINGS_MOUSE_SWAP_BUTTONS_LABEL}, {"mouseReverseScroll", IDS_SETTINGS_MOUSE_REVERSE_SCROLL_LABEL}, }; - AddLocalizedStringsBulk(html_source, pointers_strings, - arraysize(pointers_strings)); + AddLocalizedStringsBulk(html_source, kPointersStrings, + base::size(kPointersStrings)); LocalizedString keyboard_strings[] = { {"keyboardTitle", IDS_SETTINGS_KEYBOARD_TITLE}, @@ -706,9 +720,9 @@ void AddDeviceStrings(content::WebUIDataSource* html_source) { IDS_SETTINGS_KEYBOARD_SHOW_LANGUAGE_AND_INPUT}, }; AddLocalizedStringsBulk(html_source, keyboard_strings, - arraysize(keyboard_strings)); + base::size(keyboard_strings)); - LocalizedString stylus_strings[] = { + static constexpr LocalizedString kStylusStrings[] = { {"stylusTitle", IDS_SETTINGS_STYLUS_TITLE}, {"stylusEnableStylusTools", IDS_SETTINGS_STYLUS_ENABLE_STYLUS_TOOLS}, {"stylusAutoOpenStylusTools", IDS_SETTINGS_STYLUS_AUTO_OPEN_STYLUS_TOOLS}, @@ -726,10 +740,10 @@ void AddDeviceStrings(content::WebUIDataSource* html_source) { IDS_SETTINGS_STYLUS_NOTE_TAKING_APP_NONE_AVAILABLE}, {"stylusNoteTakingAppWaitingForAndroid", IDS_SETTINGS_STYLUS_NOTE_TAKING_APP_WAITING_FOR_ANDROID}}; - AddLocalizedStringsBulk(html_source, stylus_strings, - arraysize(stylus_strings)); + AddLocalizedStringsBulk(html_source, kStylusStrings, + base::size(kStylusStrings)); - LocalizedString display_strings[] = { + static constexpr LocalizedString kDisplayStrings[] = { {"displayTitle", IDS_SETTINGS_DISPLAY_TITLE}, {"displayArrangementText", IDS_SETTINGS_DISPLAY_ARRANGEMENT_TEXT}, {"displayArrangementTitle", IDS_SETTINGS_DISPLAY_ARRANGEMENT_TITLE}, @@ -794,19 +808,17 @@ void AddDeviceStrings(content::WebUIDataSource* html_source) { IDS_SETTINGS_DISPLAY_TOUCH_CALIBRATION_TITLE}, {"displayTouchCalibrationText", IDS_SETTINGS_DISPLAY_TOUCH_CALIBRATION_TEXT}}; - AddLocalizedStringsBulk(html_source, display_strings, - arraysize(display_strings)); + AddLocalizedStringsBulk(html_source, kDisplayStrings, + base::size(kDisplayStrings)); + base::CommandLine& cmd = *base::CommandLine::ForCurrentProcess(); html_source->AddBoolean("unifiedDesktopAvailable", - base::CommandLine::ForCurrentProcess()->HasSwitch( - ::switches::kEnableUnifiedDesktop)); + cmd.HasSwitch(::switches::kEnableUnifiedDesktop)); html_source->AddBoolean("multiMirroringAvailable", - !base::CommandLine::ForCurrentProcess()->HasSwitch( - ::switches::kDisableMultiMirroring)); + !cmd.HasSwitch(::switches::kDisableMultiMirroring)); html_source->AddBoolean( "enableTouchCalibrationSetting", - base::CommandLine::ForCurrentProcess()->HasSwitch( - chromeos::switches::kEnableTouchCalibrationSetting)); + cmd.HasSwitch(chromeos::switches::kEnableTouchCalibrationSetting)); html_source->AddBoolean("hasExternalTouchDevice", display::HasExternalTouchscreenDevice()); @@ -814,7 +826,7 @@ void AddDeviceStrings(content::WebUIDataSource* html_source) { html_source->AddBoolean("nightLightFeatureEnabled", ash::features::IsNightLightEnabled()); - LocalizedString storage_strings[] = { + static constexpr LocalizedString kStorageStrings[] = { {"storageTitle", IDS_SETTINGS_STORAGE_TITLE}, {"storageItemInUse", IDS_SETTINGS_STORAGE_ITEM_IN_USE}, {"storageItemAvailable", IDS_SETTINGS_STORAGE_ITEM_AVAILABLE}, @@ -844,10 +856,10 @@ void AddDeviceStrings(content::WebUIDataSource* html_source) { IDS_SETTINGS_STORAGE_CLEAR_DRIVE_CACHE_DESCRIPTION}, {"storageDeleteAllButtonTitle", IDS_SETTINGS_STORAGE_DELETE_ALL_BUTTON_TITLE}}; - AddLocalizedStringsBulk(html_source, storage_strings, - arraysize(storage_strings)); + AddLocalizedStringsBulk(html_source, kStorageStrings, + base::size(kStorageStrings)); - LocalizedString power_strings[] = { + static constexpr LocalizedString kPowerStrings[] = { {"powerTitle", IDS_SETTINGS_POWER_TITLE}, {"powerSourceLabel", IDS_SETTINGS_POWER_SOURCE_LABEL}, {"powerSourceBattery", IDS_SETTINGS_POWER_SOURCE_BATTERY}, @@ -864,7 +876,8 @@ void AddDeviceStrings(content::WebUIDataSource* html_source) { {"powerLidSignOutLabel", IDS_SETTINGS_POWER_LID_CLOSED_SIGN_OUT_LABEL}, {"powerLidShutDownLabel", IDS_SETTINGS_POWER_LID_CLOSED_SHUT_DOWN_LABEL}, }; - AddLocalizedStringsBulk(html_source, power_strings, arraysize(power_strings)); + AddLocalizedStringsBulk(html_source, kPowerStrings, + base::size(kPowerStrings)); html_source->AddString("naturalScrollLearnMoreLink", GetHelpUrlWithBoard(chrome::kNaturalScrollHelpURL)); @@ -872,7 +885,7 @@ void AddDeviceStrings(content::WebUIDataSource* html_source) { #endif void AddDownloadsStrings(content::WebUIDataSource* html_source) { - LocalizedString localized_strings[] = { + static constexpr LocalizedString kLocalizedStrings[] = { {"downloadsPageTitle", IDS_SETTINGS_DOWNLOADS}, {"downloadLocation", IDS_SETTINGS_DOWNLOAD_LOCATION}, {"changeDownloadLocation", IDS_SETTINGS_CHANGE_DOWNLOAD_LOCATION}, @@ -900,8 +913,8 @@ void AddDownloadsStrings(content::WebUIDataSource* html_source) { IDS_SETTINGS_DOWNLOADS_SHARE_ADDED_MOUNT_INVALID_URL_MESSAGE}, #endif }; - AddLocalizedStringsBulk(html_source, localized_strings, - arraysize(localized_strings)); + AddLocalizedStringsBulk(html_source, kLocalizedStrings, + base::size(kLocalizedStrings)); #if defined(OS_CHROMEOS) chromeos::smb_dialog::AddLocalizedStrings(html_source); @@ -917,7 +930,7 @@ void AddChromeCleanupStrings(content::WebUIDataSource* html_source) { L"https://www.google.ca/chrome/browser/privacy/" "whitepaper.html#unwantedsoftware"; - LocalizedString localized_strings[] = { + static constexpr LocalizedString kLocalizedStrings[] = { {"chromeCleanupPageTitle", IDS_SETTINGS_RESET_CLEAN_UP_COMPUTER_PAGE_TITLE}, {"chromeCleanupDetailsExtensions", @@ -946,7 +959,6 @@ void AddChromeCleanupStrings(content::WebUIDataSource* html_source) { IDS_SETTINGS_RESET_CLEANUP_FIND_BUTTON_LABEL}, {"chromeCleanupLinkShowItems", IDS_SETTINGS_RESET_CLEANUP_LINK_SHOW_FILES}, - {"chromeCleanupLogsUploadPermission", IDS_CHROME_CLEANUP_LOGS_PERMISSION}, {"chromeCleanupRemoveButtonLabel", IDS_SETTINGS_RESET_CLEANUP_REMOVE_BUTTON_LABEL}, {"chromeCleanupRestartButtonLabel", @@ -956,7 +968,7 @@ void AddChromeCleanupStrings(content::WebUIDataSource* html_source) { {"chromeCleanupTitleErrorPermissions", IDS_SETTINGS_RESET_CLEANUP_TITLE_ERROR_PERMISSIONS_NEEDED}, {"chromeCleanupTitleFindAndRemove", - IDS_SETTINGS_RESET_CLEANUP_TITLE_FIND_AND_REMOVE}, + IDS_SETTINGS_RESET_CLEANUP_TITLE_FIND_HARMFUL_SOFTWARE}, {"chromeCleanupTitleNoInternet", IDS_SETTINGS_RESET_CLEANUP_TITLE_NO_INTERNET_CONNECTION}, {"chromeCleanupTitleNothingFound", @@ -970,16 +982,16 @@ void AddChromeCleanupStrings(content::WebUIDataSource* html_source) { IDS_SETTINGS_RESET_CLEANUP_TITLE_ERROR_SCANNING_FAILED}, {"chromeCleanupTitleTryAgainButtonLabel", IDS_SETTINGS_RESET_CLEANUP_TRY_AGAIN_BUTTON_LABEL}, - {"chromeCleanupTitleLogsPermissionExplanation", - IDS_SETTINGS_RESET_CLEANUP_LOGS_PERMISSION_EXPLANATION}, + {"chromeCleanupExplanationLogsPermissionPref", + IDS_SETTINGS_RESET_CLEANUP_LOGS_PERMISSION_PREF}, {"chromeCleanupTitleCleanupUnavailable", IDS_SETTINGS_RESET_CLEANUP_TITLE_CLEANUP_UNAVAILABLE}, {"chromeCleanupExplanationCleanupUnavailable", IDS_SETTINGS_RESET_CLEANUP_EXPLANATION_CLEANUP_UNAVAILABLE}, }; - AddLocalizedStringsBulk(html_source, localized_strings, - arraysize(localized_strings)); + AddLocalizedStringsBulk(html_source, kLocalizedStrings, + base::size(kLocalizedStrings)); const std::string cleanup_learn_more_url = google_util::AppendGoogleLocaleParam( GURL(chrome::kChromeCleanerLearnMoreURL), @@ -1009,7 +1021,7 @@ void AddChromeCleanupStrings(content::WebUIDataSource* html_source) { } void AddIncompatibleApplicationsStrings(content::WebUIDataSource* html_source) { - LocalizedString localized_strings[] = { + static constexpr LocalizedString kLocalizedStrings[] = { {"incompatibleApplicationsResetCardTitle", IDS_SETTINGS_INCOMPATIBLE_APPLICATIONS_RESET_CARD_TITLE}, {"incompatibleApplicationsSubpageSubtitle", @@ -1025,8 +1037,8 @@ void AddIncompatibleApplicationsStrings(content::WebUIDataSource* html_source) { {"incompatibleApplicationsDone", IDS_SETTINGS_INCOMPATIBLE_APPLICATIONS_DONE}, }; - AddLocalizedStringsBulk(html_source, localized_strings, - arraysize(localized_strings)); + AddLocalizedStringsBulk(html_source, kLocalizedStrings, + base::size(kLocalizedStrings)); // The help URL is provided via Field Trial param. If none is provided, the // "Learn How" text is left empty so that no link is displayed. @@ -1044,7 +1056,7 @@ void AddIncompatibleApplicationsStrings(content::WebUIDataSource* html_source) { #endif // defined(OS_WIN) && defined(GOOGLE_CHROME_BUILD) void AddResetStrings(content::WebUIDataSource* html_source) { - LocalizedString localized_strings[] = { + static constexpr LocalizedString kLocalizedStrings[] = { #if defined(OS_WIN) && defined(GOOGLE_CHROME_BUILD) {"resetPageTitle", IDS_SETTINGS_RESET_AND_CLEANUP}, #else @@ -1073,8 +1085,8 @@ void AddResetStrings(content::WebUIDataSource* html_source) { IDS_SETTINGS_RESET_CLEAN_UP_COMPUTER_TRIGGER}, #endif }; - AddLocalizedStringsBulk(html_source, localized_strings, - arraysize(localized_strings)); + AddLocalizedStringsBulk(html_source, kLocalizedStrings, + base::size(kLocalizedStrings)); html_source->AddString("resetPageLearnMoreUrl", chrome::kResetProfileSettingsLearnMoreURL); @@ -1090,29 +1102,30 @@ void AddResetStrings(content::WebUIDataSource* html_source) { #if !defined(OS_CHROMEOS) void AddImportDataStrings(content::WebUIDataSource* html_source) { - LocalizedString localized_strings[] = { - {"importTitle", IDS_SETTINGS_IMPORT_SETTINGS_TITLE}, - {"importFromLabel", IDS_SETTINGS_IMPORT_FROM_LABEL}, - {"importDescription", IDS_SETTINGS_IMPORT_ITEMS_LABEL}, - {"importLoading", IDS_SETTINGS_IMPORT_LOADING_PROFILES}, - {"importHistory", IDS_SETTINGS_IMPORT_HISTORY_CHECKBOX}, - {"importFavorites", IDS_SETTINGS_IMPORT_FAVORITES_CHECKBOX}, - {"importPasswords", IDS_SETTINGS_IMPORT_PASSWORDS_CHECKBOX}, - {"importSearch", IDS_SETTINGS_IMPORT_SEARCH_ENGINES_CHECKBOX}, - {"importAutofillFormData", IDS_SETTINGS_IMPORT_AUTOFILL_FORM_DATA_CHECKBOX}, - {"importChooseFile", IDS_SETTINGS_IMPORT_CHOOSE_FILE}, - {"importCommit", IDS_SETTINGS_IMPORT_COMMIT}, - {"noProfileFound", IDS_SETTINGS_IMPORT_NO_PROFILE_FOUND}, - {"importSuccess", IDS_SETTINGS_IMPORT_SUCCESS}, + static constexpr LocalizedString kLocalizedStrings[] = { + {"importTitle", IDS_SETTINGS_IMPORT_SETTINGS_TITLE}, + {"importFromLabel", IDS_SETTINGS_IMPORT_FROM_LABEL}, + {"importDescription", IDS_SETTINGS_IMPORT_ITEMS_LABEL}, + {"importLoading", IDS_SETTINGS_IMPORT_LOADING_PROFILES}, + {"importHistory", IDS_SETTINGS_IMPORT_HISTORY_CHECKBOX}, + {"importFavorites", IDS_SETTINGS_IMPORT_FAVORITES_CHECKBOX}, + {"importPasswords", IDS_SETTINGS_IMPORT_PASSWORDS_CHECKBOX}, + {"importSearch", IDS_SETTINGS_IMPORT_SEARCH_ENGINES_CHECKBOX}, + {"importAutofillFormData", + IDS_SETTINGS_IMPORT_AUTOFILL_FORM_DATA_CHECKBOX}, + {"importChooseFile", IDS_SETTINGS_IMPORT_CHOOSE_FILE}, + {"importCommit", IDS_SETTINGS_IMPORT_COMMIT}, + {"noProfileFound", IDS_SETTINGS_IMPORT_NO_PROFILE_FOUND}, + {"importSuccess", IDS_SETTINGS_IMPORT_SUCCESS}, }; - AddLocalizedStringsBulk(html_source, localized_strings, - arraysize(localized_strings)); + AddLocalizedStringsBulk(html_source, kLocalizedStrings, + base::size(kLocalizedStrings)); } #endif #if defined(OS_CHROMEOS) void AddDateTimeStrings(content::WebUIDataSource* html_source) { - LocalizedString localized_strings[] = { + static constexpr LocalizedString kLocalizedStrings[] = { {"dateTimePageTitle", IDS_SETTINGS_DATE_TIME}, {"timeZone", IDS_SETTINGS_TIME_ZONE}, {"selectTimeZoneResolveMethod", @@ -1135,8 +1148,8 @@ void AddDateTimeStrings(content::WebUIDataSource* html_source) { {"use24HourClock", IDS_SETTINGS_USE_24_HOUR_CLOCK}, {"setDateTime", IDS_SETTINGS_SET_DATE_TIME}, }; - AddLocalizedStringsBulk(html_source, localized_strings, - arraysize(localized_strings)); + AddLocalizedStringsBulk(html_source, kLocalizedStrings, + base::size(kLocalizedStrings)); html_source->AddString( "timeZoneSettingsLearnMoreURL", base::ASCIIToUTF16(base::StringPrintf( @@ -1145,19 +1158,19 @@ void AddDateTimeStrings(content::WebUIDataSource* html_source) { } void AddEasyUnlockStrings(content::WebUIDataSource* html_source) { - LocalizedString localized_strings[] = { + static constexpr LocalizedString kLocalizedStrings[] = { {"easyUnlockSectionTitle", IDS_SETTINGS_EASY_UNLOCK_SECTION_TITLE}, {"easyUnlockUnlockDeviceOnly", IDS_SETTINGS_EASY_UNLOCK_UNLOCK_DEVICE_ONLY}, {"easyUnlockUnlockDeviceAndAllowSignin", IDS_SETTINGS_EASY_UNLOCK_UNLOCK_DEVICE_AND_ALLOW_SIGNIN}, }; - AddLocalizedStringsBulk(html_source, localized_strings, - arraysize(localized_strings)); + AddLocalizedStringsBulk(html_source, kLocalizedStrings, + base::size(kLocalizedStrings)); } void AddInternetStrings(content::WebUIDataSource* html_source) { - LocalizedString localized_strings[] = { + static constexpr LocalizedString kLocalizedStrings[] = { {"internetAddConnection", IDS_SETTINGS_INTERNET_ADD_CONNECTION}, {"internetAddConnectionExpandA11yLabel", IDS_SETTINGS_INTERNET_ADD_CONNECTION_EXPAND_ACCESSIBILITY_LABEL}, @@ -1269,21 +1282,21 @@ void AddInternetStrings(content::WebUIDataSource* html_source) { IDS_SETTINGS_INTERNET_TETHER_CONNECTION_CONNECT_BUTTON}, {"tetherEnableBluetooth", IDS_ENABLE_BLUETOOTH}, }; - AddLocalizedStringsBulk(html_source, localized_strings, - arraysize(localized_strings)); + AddLocalizedStringsBulk(html_source, kLocalizedStrings, + base::size(kLocalizedStrings)); html_source->AddString("networkGoogleNameserversLearnMoreUrl", chrome::kGoogleNameserversLearnMoreURL); html_source->AddString( "internetNoNetworksMobileData", l10n_util::GetStringFUTF16( - IDS_SETTINGS_INTERNET_NO_NETWORKS_MOBILE_DATA, + IDS_SETTINGS_INTERNET_LOOKING_FOR_MOBILE_NETWORK, GetHelpUrlWithBoard(chrome::kInstantTetheringLearnMoreURL))); } #endif void AddLanguagesStrings(content::WebUIDataSource* html_source) { - LocalizedString localized_strings[] = { + static constexpr LocalizedString kLocalizedStrings[] = { {"languagesPageTitle", IDS_SETTINGS_LANGUAGES_PAGE_TITLE}, {"languagesListTitle", IDS_SETTINGS_LANGUAGES_LANGUAGES_LIST_TITLE}, {"searchLanguages", IDS_SETTINGS_LANGUAGE_SEARCH}, @@ -1349,8 +1362,8 @@ void AddLanguagesStrings(content::WebUIDataSource* html_source) { IDS_SETTINGS_LANGUAGES_DICTIONARY_DOWNLOAD_FAILED_HELP}, #endif }; - AddLocalizedStringsBulk(html_source, localized_strings, - arraysize(localized_strings)); + AddLocalizedStringsBulk(html_source, kLocalizedStrings, + base::size(kLocalizedStrings)); #if defined(OS_CHROMEOS) // Only the Chrome OS help article explains how language order affects website @@ -1392,7 +1405,7 @@ void AddChromeOSUserStrings(content::WebUIDataSource* html_source, #endif void AddOnStartupStrings(content::WebUIDataSource* html_source) { - LocalizedString localized_strings[] = { + static constexpr LocalizedString kLocalizedStrings[] = { {"onStartup", IDS_SETTINGS_ON_STARTUP}, {"onStartupOpenNewTab", IDS_SETTINGS_ON_STARTUP_OPEN_NEW_TAB}, {"onStartupContinue", IDS_SETTINGS_ON_STARTUP_CONTINUE}, @@ -1405,13 +1418,13 @@ void AddOnStartupStrings(content::WebUIDataSource* html_source) { {"onStartupInvalidUrl", IDS_SETTINGS_INVALID_URL}, {"onStartupUrlTooLong", IDS_SETTINGS_URL_TOOL_LONG}, }; - AddLocalizedStringsBulk(html_source, localized_strings, - arraysize(localized_strings)); + AddLocalizedStringsBulk(html_source, kLocalizedStrings, + base::size(kLocalizedStrings)); } void AddAutofillStrings(content::WebUIDataSource* html_source, Profile* profile) { - LocalizedString localized_strings[] = { + static constexpr LocalizedString kLocalizedStrings[] = { {"autofillPageTitle", IDS_SETTINGS_AUTOFILL}, {"passwords", IDS_SETTINGS_PASSWORDS}, {"creditCards", IDS_AUTOFILL_PAYMENT_METHODS}, @@ -1540,15 +1553,15 @@ void AddAutofillStrings(content::WebUIDataSource* html_source, html_source->AddBoolean("uploadToGoogleActive", false); } - bool isGuestMode = false; + bool is_guest_mode = false; #if defined(OS_CHROMEOS) - isGuestMode = user_manager::UserManager::Get()->IsLoggedInAsGuest() || - user_manager::UserManager::Get()->IsLoggedInAsPublicAccount(); + is_guest_mode = user_manager::UserManager::Get()->IsLoggedInAsGuest() || + user_manager::UserManager::Get()->IsLoggedInAsPublicAccount(); #else // !defined(OS_CHROMEOS) - isGuestMode = profile->IsOffTheRecord(); + is_guest_mode = profile->IsOffTheRecord(); #endif // defined(OS_CHROMEOS) - if (isGuestMode) { + if (is_guest_mode) { html_source->AddBoolean("userEmailDomainAllowed", false); } else { const std::string& user_email = @@ -1566,11 +1579,13 @@ void AddAutofillStrings(content::WebUIDataSource* html_source, } } - AddLocalizedStringsBulk(html_source, localized_strings, - arraysize(localized_strings)); + AddLocalizedStringsBulk(html_source, kLocalizedStrings, + base::size(kLocalizedStrings)); } void AddPeopleStrings(content::WebUIDataSource* html_source, Profile* profile) { + bool is_unified_consent_enabled = + unified_consent::IsUnifiedConsentFeatureEnabled(); LocalizedString localized_strings[] = { {"peoplePageTitle", IDS_SETTINGS_PEOPLE}, {"manageOtherPeople", IDS_SETTINGS_PEOPLE_MANAGE_OTHER_PEOPLE}, @@ -1581,6 +1596,10 @@ void AddPeopleStrings(content::WebUIDataSource* html_source, Profile* profile) { {"accountListHeader", IDS_SETTINGS_ACCOUNT_MANAGER_LIST_HEADER}, {"addAccountLabel", IDS_SETTINGS_ACCOUNT_MANAGER_ADD_ACCOUNT_LABEL}, {"removeAccountLabel", IDS_SETTINGS_ACCOUNT_MANAGER_REMOVE_ACCOUNT_LABEL}, + {"accountManagerSignedOutAccountName", + IDS_SETTINGS_ACCOUNT_MANAGER_SIGNED_OUT_ACCOUNT_PLACEHOLDER}, + {"accountManagerReauthenticationLabel", + IDS_SETTINGS_ACCOUNT_MANAGER_REAUTHENTICATION_LABEL}, {"configureFingerprintTitle", IDS_SETTINGS_ADD_FINGERPRINT_DIALOG_TITLE}, {"configureFingerprintInstructionLocateScannerStep", IDS_SETTINGS_ADD_FINGERPRINT_DIALOG_INSTRUCTION_LOCATE_SCANNER}, @@ -1684,11 +1703,13 @@ void AddPeopleStrings(content::WebUIDataSource* html_source, Profile* profile) { {"editPerson", IDS_SETTINGS_EDIT_PERSON}, {"profileNameAndPicture", IDS_SETTINGS_PROFILE_NAME_AND_PICTURE}, {"showShortcutLabel", IDS_SETTINGS_PROFILE_SHORTCUT_TOGGLE_LABEL}, - {"syncWillStart", unified_consent::IsUnifiedConsentFeatureEnabled() + {"syncWillStart", is_unified_consent_enabled ? IDS_SETTINGS_SYNC_WILL_START_UNITY : IDS_SETTINGS_SYNC_WILL_START}, {"syncSettingsSavedToast", IDS_SETTINGS_SYNC_SETTINGS_SAVED_TOAST_LABEL}, {"cancelSync", IDS_SETTINGS_SYNC_SETTINGS_CANCEL_SYNC}, + {"syncSetupCancelDialogTitle", IDS_SETTINGS_SYNC_SETUP_CANCEL_DIALOG_TITLE}, + {"syncSetupCancelDialogBody", IDS_SETTINGS_SYNC_SETUP_CANCEL_DIALOG_BODY}, #endif // defined(OS_CHROMEOS) #if BUILDFLAG(ENABLE_DICE_SUPPORT) {"peopleSignIn", IDS_PROFILES_DICE_SIGNIN_BUTTON}, @@ -1731,7 +1752,7 @@ void AddPeopleStrings(content::WebUIDataSource* html_source, Profile* profile) { IDS_SETTINGS_NON_PERSONALIZED_SERVICES_SECTION_LABEL}, {"syncAndNonPersonalizedServices", IDS_SETTINGS_SYNC_SYNC_AND_NON_PERSONALIZED_SERVICES}, - {"syncPageTitle", unified_consent::IsUnifiedConsentFeatureEnabled() + {"syncPageTitle", is_unified_consent_enabled ? IDS_SETTINGS_SYNC_SYNC_AND_NON_PERSONALIZED_SERVICES : IDS_SETTINGS_SYNC_PAGE_TITLE}, {"syncAdvancedPageTitle", IDS_SETTINGS_SYNC_ADVANCED_PAGE_TITLE}, @@ -1775,7 +1796,7 @@ void AddPeopleStrings(content::WebUIDataSource* html_source, Profile* profile) { IDS_AUTOFILL_ENABLE_PAYMENTS_INTEGRATION_CHECKBOX_LABEL}, }; AddLocalizedStringsBulk(html_source, localized_strings, - arraysize(localized_strings)); + base::size(localized_strings)); // Format numbers to be used on the pin keyboard. for (int j = 0; j <= 9; j++) { @@ -1784,12 +1805,6 @@ void AddPeopleStrings(content::WebUIDataSource* html_source, Profile* profile) { } html_source->AddString("syncLearnMoreUrl", chrome::kSyncLearnMoreURL); - html_source->AddString("autofillHelpURL", -#if defined(OS_CHROMEOS) - GetHelpUrlWithBoard(autofill::kHelpURL)); -#else - autofill::kHelpURL); -#endif html_source->AddString("supervisedUsersUrl", chrome::kLegacySupervisedUserManagementURL); @@ -1843,7 +1858,7 @@ void AddPeopleStrings(content::WebUIDataSource* html_source, Profile* profile) { LocalizedString sync_disconnect_strings[] = { {"syncDisconnect", IDS_SETTINGS_PEOPLE_SYNC_TURN_OFF}, {"syncDisconnectTitle", - unified_consent::IsUnifiedConsentFeatureEnabled() + is_unified_consent_enabled ? IDS_SETTINGS_TURN_OFF_SYNC_AND_SIGN_OUT_DIALOG_TITLE_UNIFIED_CONSENT : IDS_SETTINGS_TURN_OFF_SYNC_AND_SIGN_OUT_DIALOG_TITLE}, {"syncDisconnectDeleteProfile", @@ -1852,9 +1867,9 @@ void AddPeopleStrings(content::WebUIDataSource* html_source, Profile* profile) { IDS_SETTINGS_TURN_OFF_SYNC_DIALOG_MANAGED_CONFIRM}, }; AddLocalizedStringsBulk(html_source, sync_disconnect_strings, - arraysize(sync_disconnect_strings)); + base::size(sync_disconnect_strings)); - if (unified_consent::IsUnifiedConsentFeatureEnabled()) { + if (is_unified_consent_enabled) { html_source->AddLocalizedString( "syncDisconnectExplanation", IDS_SETTINGS_SYNC_DISCONNECT_AND_SIGN_OUT_EXPLANATION_UNIFIED_CONSENT); @@ -1895,7 +1910,7 @@ void AddPeopleStrings(content::WebUIDataSource* html_source, Profile* profile) { } void AddPrintingStrings(content::WebUIDataSource* html_source) { - LocalizedString localized_strings[] = { + static constexpr LocalizedString kLocalizedStrings[] = { {"printingPageTitle", IDS_SETTINGS_PRINTING}, {"printingCloudPrintLearnMoreLabel", IDS_SETTINGS_PRINTING_CLOUD_PRINT_LEARN_MORE_LABEL}, @@ -1986,8 +2001,8 @@ void AddPrintingStrings(content::WebUIDataSource* html_source) { {"localPrintersTitle", IDS_SETTINGS_PRINTING_LOCAL_PRINTERS_TITLE}, #endif }; - AddLocalizedStringsBulk(html_source, localized_strings, - arraysize(localized_strings)); + AddLocalizedStringsBulk(html_source, kLocalizedStrings, + base::size(kLocalizedStrings)); html_source->AddString("devicesUrl", chrome::kChromeUIDevicesURL); html_source->AddString("printingCloudPrintLearnMoreUrl", @@ -2001,7 +2016,7 @@ void AddPrintingStrings(content::WebUIDataSource* html_source) { void AddPrivacyStrings(content::WebUIDataSource* html_source, Profile* profile) { - LocalizedString localized_strings[] = { + static constexpr LocalizedString kLocalizedStrings[] = { {"privacyPageTitle", IDS_SETTINGS_PRIVACY}, {"signinAllowedTitle", IDS_SETTINGS_SIGNIN_ALLOWED}, {"signinAllowedDescription", IDS_SETTINGS_SIGNIN_ALLOWED_DESC}, @@ -2028,19 +2043,21 @@ void AddPrivacyStrings(content::WebUIDataSource* html_source, IDS_SETTINGS_SAFEBROWSING_ENABLEPROTECTION}, {"safeBrowsingEnableProtectionDesc", IDS_SETTINGS_SAFEBROWSING_ENABLEPROTECTION_DESC}, + {"syncAndGoogleServicesPrivacyDescription", + IDS_SETTINGS_SYNC_AND_GOOGLE_SERVICES_PRIVACY_DESC_UNIFIED_CONSENT}, {"urlKeyedAnonymizedDataCollection", IDS_SETTINGS_ENABLE_URL_KEYED_ANONYMIZED_DATA_COLLECTION}, {"urlKeyedAnonymizedDataCollectionDesc", IDS_SETTINGS_ENABLE_URL_KEYED_ANONYMIZED_DATA_COLLECTION_DESC}, }; - AddLocalizedStringsBulk(html_source, localized_strings, - arraysize(localized_strings)); + AddLocalizedStringsBulk(html_source, kLocalizedStrings, + base::size(kLocalizedStrings)); // Select strings depending on unified-consent enabledness. bool is_unified_consent_enabled = unified_consent::IsUnifiedConsentFeatureEnabled(); if (is_unified_consent_enabled) { - LocalizedString conditional_localized_strings[] = { + static constexpr LocalizedString kConditionalLocalizedStrings[] = { {"searchSuggestPref", IDS_SETTINGS_SUGGEST_PREF_UNIFIED_CONSENT}, {"searchSuggestPrefDesc", IDS_SETTINGS_SUGGEST_PREF_DESC_UNIFIED_CONSENT}, @@ -2054,15 +2071,13 @@ void AddPrivacyStrings(content::WebUIDataSource* html_source, {"spellingPref", IDS_SETTINGS_SPELLING_PREF_UNIFIED_CONSENT}, {"spellingDescription", IDS_SETTINGS_SPELLING_DESCRIPTION_UNIFIED_CONSENT}, - {"syncAndPersonalizationLink", - IDS_SETTINGS_PRIVACY_MORE_SETTINGS_UNIFIED_CONSENT}, {"enableLogging", IDS_SETTINGS_ENABLE_LOGGING_UNIFIED_CONSENT}, {"enableLoggingDesc", IDS_SETTINGS_ENABLE_LOGGING_DESC_UNIFIED_CONSENT}, }; - AddLocalizedStringsBulk(html_source, conditional_localized_strings, - arraysize(conditional_localized_strings)); + AddLocalizedStringsBulk(html_source, kConditionalLocalizedStrings, + base::size(kConditionalLocalizedStrings)); } else { - LocalizedString conditional_localized_strings[] = { + static constexpr LocalizedString kConditionalLocalizedStrings[] = { {"searchSuggestPref", IDS_SETTINGS_SUGGEST_PREF}, {"searchSuggestPrefDesc", IDS_SETTINGS_EMPTY_STRING}, {"networkPredictionEnabled", @@ -2072,7 +2087,6 @@ void AddPrivacyStrings(content::WebUIDataSource* html_source, {"linkDoctorPrefDesc", IDS_SETTINGS_EMPTY_STRING}, {"spellingPref", IDS_SETTINGS_SPELLING_PREF}, {"spellingDescription", IDS_SETTINGS_SPELLING_DESCRIPTION}, - {"syncAndPersonalizationLink", IDS_SETTINGS_PRIVACY_MORE_SETTINGS}, #if defined(OS_CHROMEOS) {"enableLogging", IDS_SETTINGS_ENABLE_LOGGING_DIAGNOSTIC_AND_USAGE_DATA}, #else @@ -2080,12 +2094,12 @@ void AddPrivacyStrings(content::WebUIDataSource* html_source, #endif {"enableLoggingDesc", IDS_SETTINGS_EMPTY_STRING}, }; - AddLocalizedStringsBulk(html_source, conditional_localized_strings, - arraysize(conditional_localized_strings)); + AddLocalizedStringsBulk(html_source, kConditionalLocalizedStrings, + base::size(kConditionalLocalizedStrings)); } html_source->AddString("syncAndGoogleServicesLearnMoreURL", - unified_consent::IsUnifiedConsentFeatureEnabled() + is_unified_consent_enabled ? chrome::kSyncAndGoogleServicesLearnMoreURL : ""); html_source->AddString( @@ -2112,7 +2126,7 @@ void AddPrivacyStrings(content::WebUIDataSource* html_source, } void AddSearchInSettingsStrings(content::WebUIDataSource* html_source) { - LocalizedString localized_strings[] = { + static constexpr LocalizedString kLocalizedStrings[] = { {"searchPrompt", IDS_SETTINGS_SEARCH_PROMPT}, {"searchNoResults", IDS_SEARCH_NO_RESULTS}, {"searchResults", IDS_SEARCH_RESULTS}, @@ -2120,8 +2134,8 @@ void AddSearchInSettingsStrings(content::WebUIDataSource* html_source) { // are identical, merge them to one and re-use here. {"clearSearch", IDS_DOWNLOAD_CLEAR_SEARCH}, }; - AddLocalizedStringsBulk(html_source, localized_strings, - arraysize(localized_strings)); + AddLocalizedStringsBulk(html_source, kLocalizedStrings, + base::size(kLocalizedStrings)); base::string16 help_text = l10n_util::GetStringFUTF16( IDS_SETTINGS_SEARCH_NO_RESULTS_HELP, @@ -2154,7 +2168,7 @@ void AddSearchStrings(content::WebUIDataSource* html_source, Profile* profile) { #endif }; AddLocalizedStringsBulk(html_source, localized_strings, - arraysize(localized_strings)); + base::size(localized_strings)); base::string16 search_explanation_text = l10n_util::GetStringFUTF16( IDS_SETTINGS_SEARCH_EXPLANATION, base::ASCIIToUTF16(chrome::kOmniboxLearnMoreURL)); @@ -2167,7 +2181,7 @@ void AddSearchStrings(content::WebUIDataSource* html_source, Profile* profile) { } void AddSearchEnginesStrings(content::WebUIDataSource* html_source) { - LocalizedString localized_strings[] = { + static constexpr LocalizedString kLocalizedStrings[] = { {"searchEnginesPageTitle", IDS_SETTINGS_SEARCH_ENGINES}, {"searchEnginesAddSearchEngine", IDS_SETTINGS_SEARCH_ENGINES_ADD_SEARCH_ENGINE}, @@ -2191,13 +2205,13 @@ void AddSearchEnginesStrings(content::WebUIDataSource* html_source) { {"searchEnginesManageExtension", IDS_SETTINGS_SEARCH_ENGINES_MANAGE_EXTENSION}, }; - AddLocalizedStringsBulk(html_source, localized_strings, - arraysize(localized_strings)); + AddLocalizedStringsBulk(html_source, kLocalizedStrings, + base::size(kLocalizedStrings)); } #if defined(OS_CHROMEOS) void AddGoogleAssistantStrings(content::WebUIDataSource* html_source) { - LocalizedString localized_strings[] = { + static constexpr LocalizedString kLocalizedStrings[] = { {"googleAssistantPageTitle", IDS_SETTINGS_GOOGLE_ASSISTANT}, {"googleAssistantEnableContext", IDS_SETTINGS_GOOGLE_ASSISTANT_ENABLE_CONTEXT}, @@ -2207,6 +2221,20 @@ void AddGoogleAssistantStrings(content::WebUIDataSource* html_source) { IDS_SETTINGS_GOOGLE_ASSISTANT_ENABLE_HOTWORD}, {"googleAssistantEnableHotwordDescription", IDS_SETTINGS_GOOGLE_ASSISTANT_ENABLE_HOTWORD_DESCRIPTION}, + {"googleAssistantVoiceSettings", + IDS_SETTINGS_GOOGLE_ASSISTANT_VOICE_SETTINGS}, + {"googleAssistantVoiceSettingsDescription", + IDS_SETTINGS_GOOGLE_ASSISTANT_VOICE_SETTINGS_DESCRIPTION}, + {"googleAssistantVoiceSettingsRetrainButton", + IDS_SETTINGS_GOOGLE_ASSISTANT_VOICE_SETTINGS_RETRAIN}, + {"googleAssistantEnableHotwordWithoutDspDescription", + IDS_SETTINGS_GOOGLE_ASSISTANT_ENABLE_HOTWORD_WITHOUT_DSP_DESCRIPTION}, + {"googleAssistantEnableHotwordWithoutDspRecommended", + IDS_SETTINGS_GOOGLE_ASSISTANT_ENABLE_HOTWORD_WITHOUT_DSP_RECOMMENDED}, + {"googleAssistantEnableHotwordWithoutDspAlwaysOn", + IDS_SETTINGS_GOOGLE_ASSISTANT_ENABLE_HOTWORD_WITHOUT_DSP_ALWAYS_ON}, + {"googleAssistantEnableHotwordWithoutDspOff", + IDS_SETTINGS_GOOGLE_ASSISTANT_ENABLE_HOTWORD_WITHOUT_DSP_OFF}, {"googleAssistantEnableNotification", IDS_SETTINGS_GOOGLE_ASSISTANT_ENABLE_NOTIFICATION}, {"googleAssistantEnableNotificationDescription", @@ -2217,14 +2245,22 @@ void AddGoogleAssistantStrings(content::WebUIDataSource* html_source) { IDS_SETTINGS_GOOGLE_ASSISTANT_LAUNCH_WITH_MIC_OPEN_DESCRIPTION}, {"googleAssistantSettings", IDS_SETTINGS_GOOGLE_ASSISTANT_SETTINGS}, }; - AddLocalizedStringsBulk(html_source, localized_strings, - arraysize(localized_strings)); + AddLocalizedStringsBulk(html_source, kLocalizedStrings, + base::size(kLocalizedStrings)); + + html_source->AddBoolean("hotwordDspAvailable", + chromeos::IsHotwordDspAvailable()); + + html_source->AddBoolean( + "voiceMatchEnabled", + base::FeatureList::IsEnabled( + chromeos::assistant::features::kAssistantVoiceMatch)); } #endif void AddSiteSettingsStrings(content::WebUIDataSource* html_source, Profile* profile) { - LocalizedString localized_strings[] = { + static constexpr LocalizedString kLocalizedStrings[] = { {"addSite", IDS_SETTINGS_ADD_SITE}, {"addSiteExceptionPlaceholder", IDS_SETTINGS_ADD_SITE_EXCEPTION_PLACEHOLDER}, @@ -2497,6 +2533,12 @@ void AddSiteSettingsStrings(content::WebUIDataSource* html_source, IDS_SETTINGS_SITE_SETTINGS_SITE_CLEAR_STORAGE_CONFIRMATION}, {"siteSettingsSiteClearStorageDialogTitle", IDS_SETTINGS_SITE_SETTINGS_SITE_CLEAR_STORAGE_DIALOG_TITLE}, + {"siteSettingsSiteGroupDelete", IDS_SETTINGS_SITE_SETTINGS_GROUP_DELETE}, + {"siteSettingsSiteGroupDeleteDialogTitle", + IDS_SETTINGS_SITE_SETTINGS_SITE_GROUP_DELETE_DIALOG_TITLE}, + {"siteSettingsSiteGroupDeleteConfirmation", + IDS_SETTINGS_SITE_SETTINGS_SITE_GROUP_DELETE_CONFIRMATION}, + {"siteSettingsSiteGroupReset", IDS_SETTINGS_SITE_SETTINGS_GROUP_RESET}, {"siteSettingsSiteGroupResetDialogTitle", IDS_SETTINGS_SITE_SETTINGS_SITE_GROUP_RESET_DIALOG_TITLE}, {"siteSettingsSiteGroupResetConfirmation", @@ -2531,9 +2573,11 @@ void AddSiteSettingsStrings(content::WebUIDataSource* html_source, IDS_SETTINGS_SITE_SETTINGS_PAYMENT_HANDLER_BLOCK}, {"siteSettingsBlockAutoplaySetting", IDS_SETTINGS_SITE_SETTINGS_BLOCK_AUTOPLAY}, + {"emptyAllSitesPage", IDS_SETTINGS_SITE_SETTINGS_EMPTY_ALL_SITES_PAGE}, + {"noSitesFound", IDS_SETTINGS_SITE_SETTINGS_NO_SITES_FOUND}, }; - AddLocalizedStringsBulk(html_source, localized_strings, - arraysize(localized_strings)); + AddLocalizedStringsBulk(html_source, kLocalizedStrings, + base::size(kLocalizedStrings)); html_source->AddBoolean("enableSiteSettings", base::FeatureList::IsEnabled( features::kSiteSettings)); @@ -2568,18 +2612,17 @@ void AddSiteSettingsStrings(content::WebUIDataSource* html_source, if (PluginUtils::ShouldPreferHtmlOverPlugins( HostContentSettingsMapFactory::GetForProfile(profile))) { - LocalizedString flash_strings[] = { + static constexpr LocalizedString kFlashStrings[] = { {"siteSettingsFlashAskFirst", IDS_SETTINGS_SITE_SETTINGS_ASK_FIRST}, {"siteSettingsFlashAskFirstRecommended", IDS_SETTINGS_SITE_SETTINGS_ASK_FIRST_RECOMMENDED}, {"siteSettingsFlashPermissionsEphemeral", IDS_SETTINGS_SITE_SETTINGS_FLASH_PERMISSIONS_ARE_EPHEMERAL}, - }; - AddLocalizedStringsBulk(html_source, flash_strings, - arraysize(flash_strings)); + AddLocalizedStringsBulk(html_source, kFlashStrings, + base::size(kFlashStrings)); } else { - LocalizedString flash_strings[] = { + static constexpr LocalizedString kFlashStrings[] = { {"siteSettingsFlashAskFirst", IDS_SETTINGS_SITE_SETTINGS_FLASH_DETECT_IMPORTANT}, {"siteSettingsFlashAskFirstRecommended", @@ -2587,31 +2630,31 @@ void AddSiteSettingsStrings(content::WebUIDataSource* html_source, {"siteSettingsFlashPermissionsEphemeral", IDS_SETTINGS_SITE_SETTINGS_FLASH_PERMISSIONS_ARE_EPHEMERAL}, }; - AddLocalizedStringsBulk(html_source, flash_strings, - arraysize(flash_strings)); + AddLocalizedStringsBulk(html_source, kFlashStrings, + base::size(kFlashStrings)); } } #if defined(OS_CHROMEOS) void AddUsersStrings(content::WebUIDataSource* html_source) { - LocalizedString localized_strings[] = { - {"usersModifiedByOwnerLabel", IDS_SETTINGS_USERS_MODIFIED_BY_OWNER_LABEL}, - {"guestBrowsingLabel", IDS_SETTINGS_USERS_GUEST_BROWSING_LABEL}, - {"settingsManagedLabel", IDS_SETTINGS_USERS_MANAGED_LABEL}, - {"showOnSigninLabel", IDS_SETTINGS_USERS_SHOW_ON_SIGNIN_LABEL}, - {"restrictSigninLabel", IDS_SETTINGS_USERS_RESTRICT_SIGNIN_LABEL}, - {"deviceOwnerLabel", IDS_SETTINGS_USERS_DEVICE_OWNER_LABEL}, - {"addUsers", IDS_SETTINGS_USERS_ADD_USERS}, - {"addUsersEmail", IDS_SETTINGS_USERS_ADD_USERS_EMAIL}, + static constexpr LocalizedString kLocalizedStrings[] = { + {"usersModifiedByOwnerLabel", IDS_SETTINGS_USERS_MODIFIED_BY_OWNER_LABEL}, + {"guestBrowsingLabel", IDS_SETTINGS_USERS_GUEST_BROWSING_LABEL}, + {"settingsManagedLabel", IDS_SETTINGS_USERS_MANAGED_LABEL}, + {"showOnSigninLabel", IDS_SETTINGS_USERS_SHOW_ON_SIGNIN_LABEL}, + {"restrictSigninLabel", IDS_SETTINGS_USERS_RESTRICT_SIGNIN_LABEL}, + {"deviceOwnerLabel", IDS_SETTINGS_USERS_DEVICE_OWNER_LABEL}, + {"addUsers", IDS_SETTINGS_USERS_ADD_USERS}, + {"addUsersEmail", IDS_SETTINGS_USERS_ADD_USERS_EMAIL}, }; - AddLocalizedStringsBulk(html_source, localized_strings, - arraysize(localized_strings)); + AddLocalizedStringsBulk(html_source, kLocalizedStrings, + base::size(kLocalizedStrings)); } #endif #if !defined(OS_CHROMEOS) void AddSystemStrings(content::WebUIDataSource* html_source) { - LocalizedString localized_strings[] = { + static constexpr LocalizedString kLocalizedStrings[] = { {"systemPageTitle", IDS_SETTINGS_SYSTEM}, #if !defined(OS_MACOSX) {"backgroundAppsLabel", IDS_SETTINGS_SYSTEM_BACKGROUND_APPS_LABEL}, @@ -2620,8 +2663,8 @@ void AddSystemStrings(content::WebUIDataSource* html_source) { IDS_SETTINGS_SYSTEM_HARDWARE_ACCELERATION_LABEL}, {"proxySettingsLabel", IDS_SETTINGS_SYSTEM_PROXY_SETTINGS_LABEL}, }; - AddLocalizedStringsBulk(html_source, localized_strings, - arraysize(localized_strings)); + AddLocalizedStringsBulk(html_source, kLocalizedStrings, + base::size(kLocalizedStrings)); // TODO(dbeam): we should probably rename anything involving "localized // strings" to "load time data" as all primitive types are used now. @@ -2630,7 +2673,7 @@ void AddSystemStrings(content::WebUIDataSource* html_source) { #endif void AddWebContentStrings(content::WebUIDataSource* html_source) { - LocalizedString localized_strings[] = { + static constexpr LocalizedString kLocalizedStrings[] = { {"webContent", IDS_SETTINGS_WEB_CONTENT}, {"pageZoom", IDS_SETTINGS_PAGE_ZOOM_LABEL}, {"fontSize", IDS_SETTINGS_FONT_SIZE_LABEL}, @@ -2656,13 +2699,13 @@ void AddWebContentStrings(content::WebUIDataSource* html_source) { {"requiresWebStoreExtension", IDS_SETTINGS_REQUIRES_WEB_STORE_EXTENSION}, {"quickBrownFox", IDS_SETTINGS_QUICK_BROWN_FOX}, }; - AddLocalizedStringsBulk(html_source, localized_strings, - arraysize(localized_strings)); + AddLocalizedStringsBulk(html_source, kLocalizedStrings, + base::size(kLocalizedStrings)); } #if defined(OS_CHROMEOS) void AddMultideviceStrings(content::WebUIDataSource* html_source) { - LocalizedString localized_strings[] = { + static constexpr LocalizedString kLocalizedStrings[] = { {"multidevicePageTitle", IDS_SETTINGS_MULTIDEVICE}, {"multideviceSetupButton", IDS_SETTINGS_MULTIDEVICE_SETUP_BUTTON}, {"multideviceVerifyButton", IDS_SETTINGS_MULTIDEVICE_VERIFY_BUTTON}, @@ -2685,8 +2728,8 @@ void AddMultideviceStrings(content::WebUIDataSource* html_source) { {"multideviceSmartLockOptions", IDS_SETTINGS_PEOPLE_LOCK_SCREEN_OPTIONS_LOCK}, }; - AddLocalizedStringsBulk(html_source, localized_strings, - arraysize(localized_strings)); + AddLocalizedStringsBulk(html_source, kLocalizedStrings, + base::size(kLocalizedStrings)); html_source->AddString( "multideviceVerificationText", diff --git a/chromium/chrome/browser/ui/webui/settings/md_settings_ui.cc b/chromium/chrome/browser/ui/webui/settings/md_settings_ui.cc index 257e8c6dd6c..5a9b7b784ef 100644 --- a/chromium/chrome/browser/ui/webui/settings/md_settings_ui.cc +++ b/chromium/chrome/browser/ui/webui/settings/md_settings_ui.cc @@ -14,11 +14,16 @@ #include "ash/public/cpp/ash_features.h" #include "base/memory/ptr_util.h" #include "base/metrics/histogram_macros.h" +#include "base/stl_util.h" #include "build/build_config.h" #include "chrome/browser/profiles/profile.h" +#include "chrome/browser/signin/identity_manager_factory.h" #include "chrome/browser/ui/passwords/manage_passwords_view_utils.h" +#include "chrome/browser/ui/webui/dark_mode_handler.h" +#include "chrome/browser/ui/webui/managed_ui_handler.h" #include "chrome/browser/ui/webui/metrics_handler.h" #include "chrome/browser/ui/webui/settings/about_handler.h" +#include "chrome/browser/ui/webui/settings/accessibility_main_handler.h" #include "chrome/browser/ui/webui/settings/appearance_handler.h" #include "chrome/browser/ui/webui/settings/browser_lifetime_handler.h" #include "chrome/browser/ui/webui/settings/downloads_handler.h" @@ -73,11 +78,12 @@ #include "ash/public/cpp/resources/grit/ash_public_unscaled_resources.h" #include "ash/public/cpp/stylus_utils.h" #include "chrome/browser/browser_process.h" +#include "chrome/browser/chromeos/android_sms/android_sms_app_manager.h" +#include "chrome/browser/chromeos/android_sms/android_sms_service_factory.h" #include "chrome/browser/chromeos/arc/arc_util.h" #include "chrome/browser/chromeos/crostini/crostini_util.h" #include "chrome/browser/chromeos/login/demo_mode/demo_session.h" #include "chrome/browser/chromeos/login/quick_unlock/quick_unlock_utils.h" -#include "chrome/browser/chromeos/multidevice_setup/android_sms_app_helper_delegate_impl.h" #include "chrome/browser/chromeos/multidevice_setup/multidevice_setup_client_factory.h" #include "chrome/browser/signin/account_tracker_service_factory.h" #include "chrome/browser/ui/webui/chromeos/smb_shares/smb_handler.h" @@ -102,8 +108,8 @@ #include "chrome/grit/browser_resources.h" #include "chromeos/account_manager/account_manager.h" #include "chromeos/account_manager/account_manager_factory.h" -#include "chromeos/chromeos_features.h" -#include "chromeos/chromeos_switches.h" +#include "chromeos/constants/chromeos_features.h" +#include "chromeos/constants/chromeos_switches.h" #include "chromeos/services/multidevice_setup/public/cpp/prefs.h" #include "components/arc/arc_util.h" #include "ui/base/ui_base_features.h" @@ -158,6 +164,7 @@ MdSettingsUI::MdSettingsUI(content::WebUI* web_ui) AddSettingsPageUIHandler(std::make_unique<NativeCertificatesHandler>()); #endif // defined(USE_NSS_CERTS) + AddSettingsPageUIHandler(std::make_unique<AccessibilityMainHandler>()); AddSettingsPageUIHandler(std::make_unique<BrowserLifetimeHandler>()); AddSettingsPageUIHandler(std::make_unique<ClearBrowsingDataHandler>(web_ui)); AddSettingsPageUIHandler(std::make_unique<CookiesViewHandler>()); @@ -199,12 +206,13 @@ MdSettingsUI::MdSettingsUI(content::WebUI* web_ui) AddSettingsPageUIHandler( std::make_unique<chromeos::settings::AccountManagerUIHandler>( account_manager, - AccountTrackerServiceFactory::GetInstance()->GetForProfile( - profile))); + AccountTrackerServiceFactory::GetInstance()->GetForProfile(profile), + IdentityManagerFactory::GetForProfile(profile))); } AddSettingsPageUIHandler( std::make_unique<chromeos::settings::ChangePictureHandler>()); - if (crostini::IsCrostiniUIAllowedForProfile(profile)) { + if (crostini::IsCrostiniUIAllowedForProfile(profile, + false /* check_policy */)) { AddSettingsPageUIHandler( std::make_unique<chromeos::settings::CrostiniHandler>(profile)); } @@ -212,8 +220,7 @@ MdSettingsUI::MdSettingsUI(content::WebUI* web_ui) std::make_unique<chromeos::settings::CupsPrintersHandler>(web_ui)); AddSettingsPageUIHandler( std::make_unique<chromeos::settings::FingerprintHandler>(profile)); - if (chromeos::switches::IsVoiceInteractionEnabled() || - chromeos::switches::IsAssistantEnabled()) { + if (chromeos::switches::IsAssistantEnabled()) { AddSettingsPageUIHandler( std::make_unique<chromeos::settings::GoogleAssistantHandler>(profile)); } @@ -275,26 +282,22 @@ MdSettingsUI::MdSettingsUI(content::WebUI* web_ui) password_protection_available); #if defined(OS_CHROMEOS) - if (!profile->IsGuestSession() && - base::FeatureList::IsEnabled( - chromeos::features::kEnableUnifiedMultiDeviceSetup) && - base::FeatureList::IsEnabled( - chromeos::features::kEnableUnifiedMultiDeviceSettings) && - base::FeatureList::IsEnabled(chromeos::features::kMultiDeviceApi)) { + if (!profile->IsGuestSession()) { + chromeos::android_sms::AndroidSmsService* android_sms_service = + chromeos::android_sms::AndroidSmsServiceFactory::GetForBrowserContext( + profile); AddSettingsPageUIHandler( std::make_unique<chromeos::settings::MultideviceHandler>( profile->GetPrefs(), chromeos::multidevice_setup::MultiDeviceSetupClientFactory:: GetForProfile(profile), - std::make_unique< - chromeos::multidevice_setup::AndroidSmsAppHelperDelegateImpl>( - profile))); + android_sms_service + ? android_sms_service->android_sms_pairing_state_tracker() + : nullptr, + android_sms_service ? android_sms_service->android_sms_app_manager() + : nullptr)); } html_source->AddBoolean( - "enableMultideviceSettings", - base::FeatureList::IsEnabled( - chromeos::features::kEnableUnifiedMultiDeviceSettings)); - html_source->AddBoolean( "multideviceAllowedByPolicy", chromeos::multidevice_setup::AreAnyMultiDeviceFeaturesAllowed( profile->GetPrefs())); @@ -322,6 +325,10 @@ MdSettingsUI::MdSettingsUI(content::WebUI* web_ui) ash::stylus_utils::HasInternalStylus()); html_source->AddBoolean("showCrostini", + crostini::IsCrostiniUIAllowedForProfile( + profile, false /* check_policy */)); + + html_source->AddBoolean("allowCrostini", crostini::IsCrostiniUIAllowedForProfile(profile)); html_source->AddBoolean("isDemoSession", @@ -334,9 +341,8 @@ MdSettingsUI::MdSettingsUI(content::WebUI* web_ui) // For AOSP images we don't have the Play Store app. In last case we Android // apps settings consists only from root link to Android settings and only // visible once settings app is registered. - const bool androidAppsVisible = arc::IsArcAllowedForProfile(profile) && - !arc::IsArcOptInVerificationDisabled(); - html_source->AddBoolean("androidAppsVisible", androidAppsVisible); + html_source->AddBoolean("androidAppsVisible", + arc::IsArcAllowedForProfile(profile)); html_source->AddBoolean("havePlayStoreApp", arc::IsPlayStoreAvailable()); // TODO(mash): Support Chrome power settings in Mash. https://crbug.com/644348 @@ -396,7 +402,12 @@ MdSettingsUI::MdSettingsUI(content::WebUI* web_ui) html_source->SetDefaultResource(use_polymer_2 ? IDR_MD_SETTINGS_VULCANIZED_P2_HTML : IDR_MD_SETTINGS_VULCANIZED_HTML); - html_source->UseGzip(exclude_from_gzip); + html_source->UseGzip(base::BindRepeating( + [](const std::vector<std::string>& excluded_paths, + const std::string& path) { + return !base::ContainsValue(excluded_paths, path); + }, + std::move(exclude_from_gzip))); #if defined(OS_CHROMEOS) html_source->AddResourcePath("manifest.json", IDR_MD_SETTINGS_MANIFEST); #endif // defined (OS_CHROMEOS) @@ -411,6 +422,9 @@ MdSettingsUI::MdSettingsUI(content::WebUI* web_ui) AddLocalizedStrings(html_source, profile); + DarkModeHandler::Initialize(web_ui, html_source); + ManagedUIHandler::Initialize(web_ui, html_source); + content::WebUIDataSource::Add(web_ui->GetWebContents()->GetBrowserContext(), html_source); } diff --git a/chromium/chrome/browser/ui/webui/settings/people_handler.cc b/chromium/chrome/browser/ui/webui/settings/people_handler.cc index a1e56381edc..e92cea80ce7 100644 --- a/chromium/chrome/browser/ui/webui/settings/people_handler.cc +++ b/chromium/chrome/browser/ui/webui/settings/people_handler.cc @@ -8,23 +8,17 @@ #include "base/bind.h" #include "base/bind_helpers.h" -#include "base/command_line.h" #include "base/compiler_specific.h" #include "base/i18n/time_formatting.h" #include "base/json/json_reader.h" -#include "base/json/json_writer.h" #include "base/metrics/histogram_macros.h" #include "base/values.h" #include "build/build_config.h" #include "chrome/browser/lifetime/application_lifetime.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/profiles/profile_metrics.h" -#include "chrome/browser/profiles/profile_window.h" -#include "chrome/browser/signin/chrome_signin_helper.h" #include "chrome/browser/signin/identity_manager_factory.h" -#include "chrome/browser/signin/profile_oauth2_token_service_factory.h" #include "chrome/browser/signin/signin_error_controller_factory.h" -#include "chrome/browser/signin/signin_manager_factory.h" #include "chrome/browser/signin/signin_promo.h" #include "chrome/browser/signin/signin_ui_util.h" #include "chrome/browser/sync/profile_sync_service_factory.h" @@ -35,50 +29,46 @@ #include "chrome/browser/ui/singleton_tabs.h" #include "chrome/browser/ui/webui/signin/login_ui_service.h" #include "chrome/browser/ui/webui/signin/login_ui_service_factory.h" -#include "chrome/common/chrome_switches.h" #include "chrome/common/url_constants.h" #include "chrome/grit/generated_resources.h" -#include "components/autofill/core/common/autofill_constants.h" #include "components/autofill/core/common/autofill_prefs.h" -#include "components/browser_sync/profile_sync_service.h" #include "components/prefs/pref_service.h" #include "components/signin/core/browser/account_consistency_method.h" -#include "components/signin/core/browser/profile_oauth2_token_service.h" #include "components/signin/core/browser/signin_error_controller.h" #include "components/signin/core/browser/signin_header_helper.h" #include "components/signin/core/browser/signin_metrics.h" #include "components/signin/core/browser/signin_pref_names.h" #include "components/strings/grit/components_strings.h" #include "components/sync/base/passphrase_enums.h" +#include "components/sync/driver/sync_service.h" +#include "components/sync/driver/sync_service_utils.h" +#include "components/sync/driver/sync_user_settings.h" #include "components/unified_consent/feature.h" #include "components/unified_consent/unified_consent_metrics.h" #include "content/public/browser/render_view_host.h" #include "content/public/browser/web_contents.h" #include "content/public/browser/web_contents_delegate.h" #include "google_apis/gaia/gaia_auth_util.h" -#include "google_apis/gaia/gaia_constants.h" -#include "net/base/url_util.h" +#include "services/identity/public/cpp/accounts_mutator.h" +#include "services/identity/public/cpp/identity_manager.h" +#include "services/identity/public/cpp/primary_account_mutator.h" #include "ui/base/l10n/l10n_util.h" #include "ui/base/webui/web_ui_util.h" #if defined(OS_CHROMEOS) #include "chrome/browser/chromeos/login/quick_unlock/pin_backend.h" -#include "components/signin/core/browser/signin_manager_base.h" #else #include "chrome/browser/signin/signin_util.h" #include "chrome/browser/ui/webui/profile_helper.h" -#include "components/signin/core/browser/signin_manager.h" #endif + #if BUILDFLAG(ENABLE_DICE_SUPPORT) #include "chrome/browser/profiles/profile_avatar_icon_util.h" #include "chrome/browser/signin/account_consistency_mode_manager.h" -#include "chrome/browser/signin/account_tracker_service_factory.h" -#include "components/signin/core/browser/account_tracker_service.h" #include "third_party/skia/include/core/SkBitmap.h" #include "ui/gfx/image/image.h" #endif -using browser_sync::ProfileSyncService; using content::WebContents; using l10n_util::GetStringFUTF16; using l10n_util::GetStringUTF16; @@ -187,19 +177,16 @@ std::string GetSyncErrorAction(sync_ui_util::ActionType action_type) { #if BUILDFLAG(ENABLE_DICE_SUPPORT) // Returns the base::Value associated with the account, to use in the stored // accounts list. -base::Value GetAccountValue(const AccountInfo& account, - AccountTrackerService* account_tracker) { +base::Value GetAccountValue(const AccountInfo& account) { DCHECK(!account.IsEmpty()); base::Value dictionary(base::Value::Type::DICTIONARY); dictionary.SetKey("email", base::Value(account.email)); dictionary.SetKey("fullName", base::Value(account.full_name)); dictionary.SetKey("givenName", base::Value(account.given_name)); - const gfx::Image& account_image = - account_tracker->GetAccountImage(account.account_id); - if (!account_image.IsEmpty()) { + if (!account.account_image.IsEmpty()) { dictionary.SetKey( "avatarImage", - base::Value(webui::GetBitmapDataUrl(account_image.AsBitmap()))); + base::Value(webui::GetBitmapDataUrl(account.account_image.AsBitmap()))); } return dictionary; } @@ -220,14 +207,8 @@ PeopleHandler::PeopleHandler(Profile* profile) : profile_(profile), configuring_sync_(false), identity_manager_observer_(this), -#if BUILDFLAG(ENABLE_DICE_SUPPORT) - sync_service_observer_(this), - account_tracker_observer_(this) { -} -#else sync_service_observer_(this) { } -#endif PeopleHandler::~PeopleHandler() { // Early exit if running unit tests (no actual WebUI is attached). @@ -308,26 +289,16 @@ void PeopleHandler::OnJavascriptAllowed() { // This is intentionally not using GetSyncService(), to go around the // Profile::IsSyncAllowed() check. - ProfileSyncService* sync_service( - ProfileSyncServiceFactory::GetInstance()->GetForProfile(profile_)); + syncer::SyncService* sync_service = + ProfileSyncServiceFactory::GetSyncServiceForProfile(profile_); if (sync_service) sync_service_observer_.Add(sync_service); - -#if BUILDFLAG(ENABLE_DICE_SUPPORT) - AccountTrackerService* account_tracker( - AccountTrackerServiceFactory::GetForProfile(profile_)); - if (account_tracker) - account_tracker_observer_.Add(account_tracker); -#endif } void PeopleHandler::OnJavascriptDisallowed() { profile_pref_registrar_.RemoveAll(); identity_manager_observer_.RemoveAll(); sync_service_observer_.RemoveAll(); -#if BUILDFLAG(ENABLE_DICE_SUPPORT) - account_tracker_observer_.RemoveAll(); -#endif } #if !defined(OS_CHROMEOS) @@ -344,29 +315,27 @@ void PeopleHandler::DisplayGaiaLoginInNewTabOrWindow( signin_metrics::AccessPoint access_point) { Browser* browser = chrome::FindBrowserWithWebContents(web_ui()->GetWebContents()); - bool force_new_tab = false; - if (!browser) { - // Settings is not displayed in a browser window. Open a new window. - browser = new Browser( - Browser::CreateParams(Browser::TYPE_TABBED, profile_, true)); - force_new_tab = true; - } + if (!browser) + return; - ProfileSyncService* service = GetSyncService(); + auto* identity_manager = + IdentityManagerFactory::GetForProfile(browser->profile()); + + syncer::SyncService* service = GetSyncService(); if (service && service->HasUnrecoverableError()) { // When the user has an unrecoverable error, they first have to sign out and // then sign in again. - SigninManagerFactory::GetForProfile(browser->profile()) - ->SignOut(signin_metrics::USER_CLICKED_SIGNOUT_SETTINGS, - signin_metrics::SignoutDelete::IGNORE_METRIC); + + identity_manager->GetPrimaryAccountMutator()->ClearPrimaryAccount( + identity::PrimaryAccountMutator::ClearAccountsAction::kDefault, + signin_metrics::USER_CLICKED_SIGNOUT_SETTINGS, + signin_metrics::SignoutDelete::IGNORE_METRIC); } // If the signin manager already has an authenticated username, this is a // re-auth scenario, and we need to ensure that the user signs in with the // same email address. - GURL url; - if (SigninManagerFactory::GetForProfile(browser->profile()) - ->IsAuthenticated()) { + if (identity_manager->HasPrimaryAccount()) { UMA_HISTOGRAM_ENUMERATION("Signin.Reauth", signin_metrics::HISTOGRAM_REAUTH_SHOWN, signin_metrics::HISTOGRAM_REAUTH_MAX); @@ -374,29 +343,14 @@ void PeopleHandler::DisplayGaiaLoginInNewTabOrWindow( SigninErrorController* error_controller = SigninErrorControllerFactory::GetForProfile(browser->profile()); DCHECK(error_controller->HasError()); - if (!force_new_tab) { browser->window()->ShowAvatarBubbleFromAvatarButton( BrowserWindow::AVATAR_BUBBLE_MODE_REAUTH, signin::ManageAccountsParams(), access_point, false); - } else { - url = signin::GetReauthURLForTab( - access_point, signin_metrics::Reason::REASON_REAUTHENTICATION, - browser->profile(), error_controller->error_account_id()); - } } else { - if (!force_new_tab) { - browser->window()->ShowAvatarBubbleFromAvatarButton( - BrowserWindow::AVATAR_BUBBLE_MODE_SIGNIN, - signin::ManageAccountsParams(), access_point, false); - } else { - url = signin::GetPromoURLForTab( - access_point, signin_metrics::Reason::REASON_SIGNIN_PRIMARY_ACCOUNT, - true); - } + browser->window()->ShowAvatarBubbleFromAvatarButton( + BrowserWindow::AVATAR_BUBBLE_MODE_SIGNIN, + signin::ManageAccountsParams(), access_point, false); } - - if (url.is_valid()) - ShowSingletonTab(browser, url); } #endif @@ -449,7 +403,7 @@ void PeopleHandler::SyncStartupFailed() { } void PeopleHandler::SyncStartupCompleted() { - ProfileSyncService* service = GetSyncService(); + syncer::SyncService* service = GetSyncService(); DCHECK(service->IsEngineInitialized()); // Stop a timer to handle timeout in waiting for checking network connection. @@ -460,9 +414,9 @@ void PeopleHandler::SyncStartupCompleted() { PushSyncPrefs(); } -ProfileSyncService* PeopleHandler::GetSyncService() const { +syncer::SyncService* PeopleHandler::GetSyncService() const { return profile_->IsSyncAllowed() - ? ProfileSyncServiceFactory::GetForProfile(profile_) + ? ProfileSyncServiceFactory::GetSyncServiceForProfile(profile_) : nullptr; } @@ -476,9 +430,9 @@ void PeopleHandler::HandleSetDatatypes(const base::ListValue* args) { autofill::prefs::SetPaymentsIntegrationEnabled( profile_->GetPrefs(), configuration.payments_integration_enabled); - // Start configuring the ProfileSyncService using the configuration passed - // to us from the JS layer. - ProfileSyncService* service = GetSyncService(); + // Start configuring the SyncService using the configuration passed to us from + // the JS layer. + syncer::SyncService* service = GetSyncService(); // If the sync engine has shutdown for some reason, just close the sync // dialog. @@ -505,56 +459,46 @@ void PeopleHandler::HandleGetStoredAccounts(const base::ListValue* args) { const base::Value* callback_id; CHECK(args->Get(0, &callback_id)); - ResolveJavascriptCallback(*callback_id, *GetStoredAccountsList()); + ResolveJavascriptCallback(*callback_id, GetStoredAccountsList()); } void PeopleHandler::OnAccountUpdated(const AccountInfo& info) { - FireWebUIListener("stored-accounts-updated", *GetStoredAccountsList()); -} - -void PeopleHandler::OnAccountImageUpdated(const std::string& account_id, - const gfx::Image& image) { - FireWebUIListener("stored-accounts-updated", *GetStoredAccountsList()); + FireWebUIListener("stored-accounts-updated", GetStoredAccountsList()); } -void PeopleHandler::OnAccountRemoved(const AccountInfo& info) { - FireWebUIListener("stored-accounts-updated", *GetStoredAccountsList()); +void PeopleHandler::OnAccountRemovedWithInfo(const AccountInfo& info) { + FireWebUIListener("stored-accounts-updated", GetStoredAccountsList()); } -std::unique_ptr<base::ListValue> PeopleHandler::GetStoredAccountsList() { - std::unique_ptr<base::ListValue> accounts_list = - std::make_unique<base::ListValue>(); - bool dice_enabled = +base::Value PeopleHandler::GetStoredAccountsList() { + base::Value accounts(base::Value::Type::LIST); + const bool dice_enabled = AccountConsistencyModeManager::IsDiceEnabledForProfile(profile_); // Dice and unified consent both disabled: do not show the list of accounts. if (!dice_enabled && !unified_consent::IsUnifiedConsentFeatureEnabled()) - return accounts_list; - - AccountTrackerService* account_tracker = - AccountTrackerServiceFactory::GetForProfile(profile_); + return accounts; + base::Value::ListStorage& accounts_list = accounts.GetList(); if (dice_enabled) { // If dice is enabled, show all the accounts. std::vector<AccountInfo> accounts = signin_ui_util::GetAccountsForDicePromos(profile_); - accounts_list->Reserve(accounts.size()); + accounts_list.reserve(accounts.size()); for (auto const& account : accounts) { - accounts_list->GetList().push_back( - GetAccountValue(account, account_tracker)); + accounts_list.push_back(GetAccountValue(account)); } } else { // If dice is disabled (and unified consent enabled), show only the primary // account. - std::string primary_account = SigninManagerFactory::GetForProfile(profile_) - ->GetAuthenticatedAccountId(); - if (!primary_account.empty()) { - accounts_list->GetList().push_back(GetAccountValue( - account_tracker->GetAccountInfo(primary_account), account_tracker)); + auto* identity_manager = IdentityManagerFactory::GetForProfile(profile_); + if (identity_manager->HasPrimaryAccount()) { + accounts_list.push_back( + GetAccountValue(identity_manager->GetPrimaryAccountInfo())); } } - return accounts_list; + return accounts; } void PeopleHandler::HandleStartSyncingWithEmail(const base::ListValue* args) { @@ -567,12 +511,15 @@ void PeopleHandler::HandleStartSyncingWithEmail(const base::ListValue* args) { Browser* browser = chrome::FindBrowserWithWebContents(web_ui()->GetWebContents()); - AccountTrackerService* account_tracker = - AccountTrackerServiceFactory::GetForProfile(profile_); - AccountInfo account = - account_tracker->FindAccountInfoByEmail(email->GetString()); + base::Optional<AccountInfo> maybe_account = + IdentityManagerFactory::GetForProfile(profile_) + ->FindAccountInfoForAccountWithRefreshTokenByEmailAddress( + email->GetString()); + signin_ui_util::EnableSyncFromPromo( - browser, account, signin_metrics::AccessPoint::ACCESS_POINT_SETTINGS, + browser, + maybe_account.has_value() ? maybe_account.value() : AccountInfo(), + signin_metrics::AccessPoint::ACCESS_POINT_SETTINGS, is_default_promo_account->GetBool()); } #endif @@ -584,9 +531,9 @@ void PeopleHandler::HandleSetEncryption(const base::ListValue* args) { const base::Value* callback_id = nullptr; ParseConfigurationArguments(args, &configuration, &callback_id); - // Start configuring the ProfileSyncService using the configuration passed - // to us from the JS layer. - ProfileSyncService* service = GetSyncService(); + // Start configuring the SyncService using the configuration passed to us from + // the JS layer. + syncer::SyncService* service = GetSyncService(); // If the sync engine has shutdown for some reason, just close the sync // dialog. @@ -596,7 +543,7 @@ void PeopleHandler::HandleSetEncryption(const base::ListValue* args) { return; } - // Don't allow "encrypt all" if the ProfileSyncService doesn't allow it. + // Don't allow "encrypt all" if the SyncService doesn't allow it. // The UI is hidden, but the user may have enabled it e.g. by fiddling with // the web inspector. if (!service->GetUserSettings()->IsEncryptEverythingAllowed()) @@ -658,7 +605,7 @@ void PeopleHandler::HandleSetEncryption(const base::ListValue* args) { void PeopleHandler::HandleShowSetupUI(const base::ListValue* args) { AllowJavascript(); - ProfileSyncService* service = GetSyncService(); + syncer::SyncService* service = GetSyncService(); if (unified_consent::IsUnifiedConsentFeatureEnabled()) { if (service && !sync_blocker_) @@ -682,7 +629,7 @@ void PeopleHandler::HandleShowSetupUI(const base::ListValue* args) { // This if-statement is not using IsProfileAuthNeededOrHasErrors(), because // in some error cases (e.g. "confirmSyncSettings") the UI still needs to // show. - if (!SigninManagerFactory::GetForProfile(profile_)->IsAuthenticated()) { + if (!IdentityManagerFactory::GetForProfile(profile_)->HasPrimaryAccount()) { // For web-based signin, the signin page is not displayed in an overlay // on the settings page. So if we get here, it must be due to the user // cancelling signin (by reloading the sync settings page during initial @@ -708,26 +655,25 @@ void PeopleHandler::HandleShowSetupUI(const base::ListValue* args) { // Requesting the sync service to start may trigger call to PushSyncPrefs. // Setting up the startup tracker beforehand correctly signals the // re-entrant call to early exit. - sync_startup_tracker_ = - std::make_unique<SyncStartupTracker>(profile_, this); + sync_startup_tracker_ = std::make_unique<SyncStartupTracker>(service, this); // SetSyncRequested(true) does two things: // 1) If DISABLE_REASON_USER_CHOICE is set (meaning that Sync was reset via // the dashboard), clears it. // 2) Pokes the sync service to start *immediately*, i.e. bypass deferred // startup. // It's possible that both of these are already the case, i.e. the engine is - // already in the process of initializing, in which case RequestStart() will - // effectively do nothing. It's also possible that the sync service is - // already running in standalone transport mode and so the engine is already - // initialized. In that case, this will trigger the service to switch to - // full Sync-the-feature mode. + // already in the process of initializing, in which case + // SetSyncRequested(true) will effectively do nothing. It's also possible + // that the sync service is already running in standalone transport mode and + // so the engine is already initialized. In that case, this will trigger the + // service to switch to full Sync-the-feature mode. service->GetUserSettings()->SetSyncRequested(true); // See if it's even possible to bring up the sync engine - if not // (unrecoverable error?), don't bother displaying a spinner that will be // immediately closed because this leads to some ugly infinite UI loop (see // http://crbug.com/244769). - if (SyncStartupTracker::GetSyncServiceState(profile_) != + if (SyncStartupTracker::GetSyncServiceState(service) != SyncStartupTracker::SYNC_STARTUP_ERROR) { DisplaySpinner(); } @@ -762,7 +708,7 @@ void PeopleHandler::HandleStartSignin(const base::ListValue* args) { // Should only be called if the user is not already signed in, has a auth // error, or a unrecoverable sync error requiring re-auth. - ProfileSyncService* service = GetSyncService(); + syncer::SyncService* service = GetSyncService(); DCHECK(IsProfileAuthNeededOrHasErrors() || (service && service->HasUnrecoverableError())); @@ -777,24 +723,24 @@ void PeopleHandler::HandleSignout(const base::ListValue* args) { // If the user cannot signout, the profile must be destroyed. DCHECK(delete_profile); } else { - SigninManager* signin_manager = - SigninManagerFactory::GetForProfile(profile_); - if (signin_manager->IsAuthenticated()) { + auto* identity_manager = IdentityManagerFactory::GetForProfile(profile_); + if (identity_manager->HasPrimaryAccount()) { if (GetSyncService()) - ProfileSyncService::SyncEvent(ProfileSyncService::STOP_FROM_OPTIONS); + syncer::RecordSyncEvent(syncer::STOP_FROM_OPTIONS); signin_metrics::SignoutDelete delete_metric = delete_profile ? signin_metrics::SignoutDelete::DELETED : signin_metrics::SignoutDelete::KEEPING; - signin_manager->SignOutAndRemoveAllAccounts( + + identity_manager->GetPrimaryAccountMutator()->ClearPrimaryAccount( + identity::PrimaryAccountMutator::ClearAccountsAction::kRemoveAll, signin_metrics::USER_CLICKED_SIGNOUT_SETTINGS, delete_metric); } else { DCHECK(!delete_profile) << "Deleting the profile should only be offered the user is syncing."; - ProfileOAuth2TokenServiceFactory::GetForProfile(profile_) - ->RevokeAllCredentials( - signin_metrics::SourceForRefreshTokenOperation:: - kSettings_Signout); + + identity_manager->GetAccountsMutator()->RemoveAllAccounts( + signin_metrics::SourceForRefreshTokenOperation::kSettings_Signout); } } @@ -806,11 +752,14 @@ void PeopleHandler::HandleSignout(const base::ListValue* args) { void PeopleHandler::HandlePauseSync(const base::ListValue* args) { DCHECK(AccountConsistencyModeManager::IsDiceEnabledForProfile(profile_)); - SigninManager* signin_manager = SigninManagerFactory::GetForProfile(profile_); - DCHECK(signin_manager->IsAuthenticated()); - ProfileOAuth2TokenServiceFactory::GetForProfile(profile_)->UpdateCredentials( - signin_manager->GetAuthenticatedAccountId(), + auto* identity_manager = IdentityManagerFactory::GetForProfile(profile_); + DCHECK(identity_manager->HasPrimaryAccount()); + + AccountInfo primary_account_info = identity_manager->GetPrimaryAccountInfo(); + identity_manager->GetAccountsMutator()->AddOrUpdateAccount( + primary_account_info.gaia, primary_account_info.email, OAuth2TokenServiceDelegate::kInvalidRefreshToken, + primary_account_info.is_under_advanced_protection, signin_metrics::SourceForRefreshTokenOperation::kSettings_PauseSync); } #endif @@ -832,7 +781,7 @@ void PeopleHandler::CloseSyncSetup() { // Clear the sync startup tracker, since the setup wizard is being closed. sync_startup_tracker_.reset(); - ProfileSyncService* sync_service = GetSyncService(); + syncer::SyncService* sync_service = GetSyncService(); // LoginUIService can be nullptr if page is brought up in incognito mode // (i.e. if the user is running in guest mode in cros and brings up settings). @@ -846,25 +795,28 @@ void PeopleHandler::CloseSyncSetup() { sync_service->GetAuthError().state() == GoogleServiceAuthError::NONE))) { if (configuring_sync_) { - ProfileSyncService::SyncEvent( - ProfileSyncService::CANCEL_DURING_CONFIGURE); + syncer::RecordSyncEvent(syncer::CANCEL_DURING_CONFIGURE); // If the user clicked "Cancel" while setting up sync, disable sync // because we don't want the sync engine to remain in the // first-setup-incomplete state. // Note: In order to disable sync across restarts on Chrome OS, - // we must call RequestStop(CLEAR_DATA), which suppresses sync startup - // in addition to disabling it. + // we must call StopAndClear(), which suppresses sync startup in + // addition to disabling it. if (sync_service) { DVLOG(1) << "Sync setup aborted by user action"; - sync_service->RequestStop(ProfileSyncService::CLEAR_DATA); + sync_service->StopAndClear(); #if !defined(OS_CHROMEOS) // Sign out the user on desktop Chrome if they click cancel during // initial setup. if (sync_service->IsFirstSetupInProgress()) { - SigninManagerFactory::GetForProfile(profile_) - ->SignOut(signin_metrics::ABORT_SIGNIN, - signin_metrics::SignoutDelete::IGNORE_METRIC); + IdentityManagerFactory::GetForProfile(profile_) + ->GetPrimaryAccountMutator() + ->ClearPrimaryAccount( + identity::PrimaryAccountMutator::ClearAccountsAction:: + kDefault, + signin_metrics::ABORT_SIGNIN, + signin_metrics::SignoutDelete::IGNORE_METRIC); } #endif } @@ -887,7 +839,7 @@ void PeopleHandler::InitializeSyncBlocker() { return; WebContents* web_contents = web_ui()->GetWebContents(); if (web_contents) { - ProfileSyncService* service = GetSyncService(); + syncer::SyncService* service = GetSyncService(); const GURL current_url = web_contents->GetVisibleURL(); if (service && current_url == chrome::GetSettingsUrl(chrome::kSyncSetupSubPage)) { @@ -937,16 +889,13 @@ PeopleHandler::GetSyncStatusDictionary() { sync_status->SetBoolean("supervisedUser", profile_->IsSupervised()); sync_status->SetBoolean("childUser", profile_->IsChild()); - SigninManagerBase* signin = SigninManagerFactory::GetForProfile(profile_); - DCHECK(signin); - auto* identity_manager = IdentityManagerFactory::GetForProfile(profile_); DCHECK(identity_manager); #if !defined(OS_CHROMEOS) // Signout is not allowed if the user has policy (crbug.com/172204). if (!signin_util::IsUserSignoutAllowedForProfile(profile_)) { - std::string username = signin->GetAuthenticatedAccountInfo().email; + std::string username = identity_manager->GetPrimaryAccountInfo().email; // If there is no one logged in or if the profile name is empty then the // domain name is empty. This happens in browser tests. @@ -958,24 +907,26 @@ PeopleHandler::GetSyncStatusDictionary() { // This is intentionally not using GetSyncService(), in order to access more // nuanced information, since GetSyncService() returns nullptr if anything // makes Profile::IsSyncAllowed() false. - ProfileSyncService* service = - ProfileSyncServiceFactory::GetInstance()->GetForProfile(profile_); + syncer::SyncService* service = + ProfileSyncServiceFactory::GetSyncServiceForProfile(profile_); bool disallowed_by_policy = service && service->HasDisableReason( syncer::SyncService::DISABLE_REASON_ENTERPRISE_POLICY); - sync_status->SetBoolean("signinAllowed", signin->IsSigninAllowed()); + sync_status->SetBoolean( + "signinAllowed", profile_->GetPrefs()->GetBoolean(prefs::kSigninAllowed)); sync_status->SetBoolean("syncSystemEnabled", (service != nullptr)); sync_status->SetBoolean("setupInProgress", service && !disallowed_by_policy && service->IsFirstSetupInProgress() && - signin->IsAuthenticated()); + identity_manager->HasPrimaryAccount()); base::string16 status_label; base::string16 link_label; sync_ui_util::ActionType action_type = sync_ui_util::NO_ACTION; + bool status_has_error = - sync_ui_util::GetStatusLabels(profile_, service, *signin, &status_label, - &link_label, + sync_ui_util::GetStatusLabels(profile_, service, identity_manager, + &status_label, &link_label, &action_type) == sync_ui_util::SYNC_ERROR; sync_status->SetString("statusText", status_label); sync_status->SetString("statusActionText", link_label); @@ -986,7 +937,7 @@ PeopleHandler::GetSyncStatusDictionary() { sync_status->SetBoolean( "disabled", !service || disallowed_by_policy || !service->GetUserSettings()->IsSyncAllowedByPlatform()); - sync_status->SetBoolean("signedIn", signin->IsAuthenticated()); + sync_status->SetBoolean("signedIn", identity_manager->HasPrimaryAccount()); sync_status->SetString( "signedInUsername", signin_ui_util::GetAuthenticatedUsername(identity_manager)); @@ -1002,7 +953,7 @@ void PeopleHandler::PushSyncPrefs() { return; #endif - ProfileSyncService* service = GetSyncService(); + syncer::SyncService* service = GetSyncService(); // The sync service may be nullptr if it has been just disabled by policy. if (!service || !service->IsEngineInitialized()) { return; @@ -1116,24 +1067,24 @@ void PeopleHandler::MarkFirstSetupComplete() { // doesn't see the sign in promo even if they sign out later on. signin::SetUserSkippedPromo(profile_); - ProfileSyncService* service = GetSyncService(); + syncer::SyncService* service = GetSyncService(); // The sync service may be nullptr if it has been just disabled by policy. if (!service || service->GetUserSettings()->IsFirstSetupComplete()) return; - // This is the first time configuring sync, so log it. - base::FilePath profile_file_path = profile_->GetPath(); - ProfileMetrics::LogProfileSyncSignIn(profile_file_path); + unified_consent::metrics::RecordSyncSetupDataTypesHistrogam( + service->GetUserSettings(), profile_->GetPrefs()); - // We're done configuring, so notify ProfileSyncService that it is OK to - // start syncing. + // We're done configuring, so notify SyncService that it is OK to start + // syncing. sync_blocker_.reset(); service->GetUserSettings()->SetFirstSetupComplete(); FireWebUIListener("sync-settings-saved"); } bool PeopleHandler::IsProfileAuthNeededOrHasErrors() { - return !SigninManagerFactory::GetForProfile(profile_)->IsAuthenticated() || + return !IdentityManagerFactory::GetForProfile(profile_) + ->HasPrimaryAccount() || SigninErrorControllerFactory::GetForProfile(profile_)->HasError(); } diff --git a/chromium/chrome/browser/ui/webui/settings/people_handler.h b/chromium/chrome/browser/ui/webui/settings/people_handler.h index 6af3d98b7ec..37e540233c2 100644 --- a/chromium/chrome/browser/ui/webui/settings/people_handler.h +++ b/chromium/chrome/browser/ui/webui/settings/people_handler.h @@ -24,16 +24,8 @@ #include "components/sync/driver/sync_service_observer.h" #include "services/identity/public/cpp/identity_manager.h" -#if BUILDFLAG(ENABLE_DICE_SUPPORT) -#include "components/signin/core/browser/account_tracker_service.h" -#endif - class LoginUIService; -namespace browser_sync { -class ProfileSyncService; -} // namespace browser_sync - namespace content { class WebUI; } // namespace content @@ -43,6 +35,7 @@ enum class AccessPoint; } // namespace signin_metrics namespace syncer { +class SyncService; class SyncSetupInProgressHandle; } // namespace syncer @@ -51,9 +44,6 @@ namespace settings { class PeopleHandler : public SettingsPageUIHandler, public identity::IdentityManager::Observer, public SyncStartupTracker::Observer, -#if BUILDFLAG(ENABLE_DICE_SUPPORT) - public AccountTrackerService::Observer, -#endif public LoginUIService::LoginUI, public syncer::SyncServiceObserver { public: @@ -139,25 +129,22 @@ class PeopleHandler : public SettingsPageUIHandler, void OnPrimaryAccountSet(const AccountInfo& primary_account_info) override; void OnPrimaryAccountCleared( const AccountInfo& previous_primary_account_info) override; +#if BUILDFLAG(ENABLE_DICE_SUPPORT) + void OnAccountUpdated(const AccountInfo& info) override; + void OnAccountRemovedWithInfo(const AccountInfo& info) override; +#endif // syncer::SyncServiceObserver implementation. void OnStateChanged(syncer::SyncService* sync) override; -#if BUILDFLAG(ENABLE_DICE_SUPPORT) - // AccountTrackerService::Observer implementation. - void OnAccountUpdated(const AccountInfo& info) override; - void OnAccountImageUpdated(const std::string& account_id, - const gfx::Image& image) override; - void OnAccountRemoved(const AccountInfo& info) override; -#endif // Returns a newly created dictionary with a number of properties that // correspond to the status of sync. std::unique_ptr<base::DictionaryValue> GetSyncStatusDictionary(); - // Helper routine that gets the ProfileSyncService associated with the parent + // Helper routine that gets the SyncService associated with the parent // profile. - browser_sync::ProfileSyncService* GetSyncService() const; + syncer::SyncService* GetSyncService() const; // Returns the LoginUIService for the parent profile. LoginUIService* GetLoginUIService() const; @@ -196,7 +183,7 @@ class PeopleHandler : public SettingsPageUIHandler, #if BUILDFLAG(ENABLE_DICE_SUPPORT) void HandleGetStoredAccounts(const base::ListValue* args); void HandleStartSyncingWithEmail(const base::ListValue* args); - std::unique_ptr<base::ListValue> GetStoredAccountsList(); + base::Value GetStoredAccountsList(); #endif // Displays spinner-only UI indicating that something is going on in the @@ -224,12 +211,12 @@ class PeopleHandler : public SettingsPageUIHandler, bool IsProfileAuthNeededOrHasErrors(); // If we're directly loading the sync setup page, we acquire a - // SetupInProgressHandle early in order to prevent a lapse in - // ProfileSyncService's "SetupInProgress" status. This lapse previously - // occured between when the sync confirmation dialog was closed and when the - // sync setup page hadn't yet fired the SyncSetupShowSetupUI event. - // InitializeSyncBlocker is responsible for checking if we're navigating to - // the setup page and acquiring the sync_blocker. + // SetupInProgressHandle early in order to prevent a lapse in SyncService's + // "SetupInProgress" status. This lapse previously occurred between when the + // sync confirmation dialog was closed and when the sync setup page hadn't yet + // fired the SyncSetupShowSetupUI event. InitializeSyncBlocker is responsible + // for checking if we're navigating to the setup page and acquiring the + // |sync_blocker_|. void InitializeSyncBlocker(); // Weak pointer. @@ -256,13 +243,7 @@ class PeopleHandler : public SettingsPageUIHandler, // Manages observer lifetimes. ScopedObserver<identity::IdentityManager, PeopleHandler> identity_manager_observer_; - ScopedObserver<browser_sync::ProfileSyncService, PeopleHandler> - sync_service_observer_; - -#if BUILDFLAG(ENABLE_DICE_SUPPORT) - ScopedObserver<AccountTrackerService, PeopleHandler> - account_tracker_observer_; -#endif + ScopedObserver<syncer::SyncService, PeopleHandler> sync_service_observer_; #if defined(OS_CHROMEOS) base::WeakPtrFactory<PeopleHandler> weak_factory_{this}; diff --git a/chromium/chrome/browser/ui/webui/settings/people_handler_unittest.cc b/chromium/chrome/browser/ui/webui/settings/people_handler_unittest.cc index f8566400196..7ef14432f17 100644 --- a/chromium/chrome/browser/ui/webui/settings/people_handler_unittest.cc +++ b/chromium/chrome/browser/ui/webui/settings/people_handler_unittest.cc @@ -16,7 +16,6 @@ #include "base/values.h" #include "build/build_config.h" #include "chrome/browser/signin/identity_test_environment_profile_adaptor.h" -#include "chrome/browser/signin/profile_oauth2_token_service_factory.h" #include "chrome/browser/signin/scoped_account_consistency.h" #include "chrome/browser/signin/signin_error_controller_factory.h" #include "chrome/browser/sync/profile_sync_service_factory.h" @@ -33,9 +32,6 @@ #include "chrome/test/base/testing_browser_process.h" #include "chrome/test/base/testing_profile.h" #include "components/prefs/pref_service.h" -#include "components/signin/core/browser/profile_oauth2_token_service.h" -#include "components/signin/core/browser/signin_manager.h" -#include "components/sync/base/sync_prefs.h" #include "components/sync_preferences/pref_service_syncable.h" #include "components/unified_consent/scoped_unified_consent.h" #include "content/public/browser/web_contents.h" @@ -46,10 +42,10 @@ #include "content/public/test/test_browser_thread_bundle.h" #include "content/public/test/test_web_ui.h" #include "content/public/test/web_contents_tester.h" -#include "google_apis/gaia/oauth2_token_service_delegate.h" +#include "services/identity/public/cpp/accounts_mutator.h" #include "services/identity/public/cpp/identity_manager.h" +#include "services/identity/public/cpp/identity_test_utils.h" #include "testing/gtest/include/gtest/gtest.h" -#include "ui/base/layout.h" using ::testing::_; using ::testing::Invoke; @@ -213,10 +209,10 @@ class PeopleHandlerTest : public ChromeRenderViewHostTestHarness { ProfileSyncServiceFactory::GetInstance()->SetTestingFactoryAndUse( profile(), base::BindRepeating(&BuildMockProfileSyncService))); ON_CALL(*mock_pss_, GetAuthError()).WillByDefault(ReturnRef(error_)); - ON_CALL(*mock_pss_, GetPassphraseType()) + ON_CALL(*mock_pss_->GetUserSettingsMock(), GetPassphraseType()) .WillByDefault(Return(syncer::PassphraseType::IMPLICIT_PASSPHRASE)); - ON_CALL(*mock_pss_, GetExplicitPassphraseTime()).WillByDefault( - Return(base::Time())); + ON_CALL(*mock_pss_->GetUserSettingsMock(), GetExplicitPassphraseTime()) + .WillByDefault(Return(base::Time())); ON_CALL(*mock_pss_, GetRegisteredDataTypes()) .WillByDefault(Return(syncer::ModelTypeSet())); ON_CALL(*mock_pss_, GetSetupInProgressHandle()) @@ -250,15 +246,19 @@ class PeopleHandlerTest : public ChromeRenderViewHostTestHarness { void SetDefaultExpectationsForConfigPage() { ON_CALL(*mock_pss_, GetDisableReasons()) .WillByDefault(Return(syncer::SyncService::DISABLE_REASON_NONE)); + ON_CALL(*mock_pss_->GetUserSettingsMock(), IsSyncRequested()) + .WillByDefault(Return(true)); ON_CALL(*mock_pss_, GetRegisteredDataTypes()) .WillByDefault(Return(GetAllTypes())); - ON_CALL(*mock_pss_, GetPreferredDataTypes()) + ON_CALL(*mock_pss_->GetUserSettingsMock(), IsSyncEverythingEnabled()) + .WillByDefault(Return(true)); + ON_CALL(*mock_pss_->GetUserSettingsMock(), GetChosenDataTypes()) .WillByDefault(Return(GetAllTypes())); ON_CALL(*mock_pss_, GetActiveDataTypes()) .WillByDefault(Return(GetAllTypes())); - ON_CALL(*mock_pss_, IsEncryptEverythingAllowed()) + ON_CALL(*mock_pss_->GetUserSettingsMock(), IsEncryptEverythingAllowed()) .WillByDefault(Return(true)); - ON_CALL(*mock_pss_, IsEncryptEverythingEnabled()) + ON_CALL(*mock_pss_->GetUserSettingsMock(), IsEncryptEverythingEnabled()) .WillByDefault(Return(false)); } @@ -356,7 +356,8 @@ TEST_F(PeopleHandlerFirstSigninTest, DisplayBasicLogin) { ON_CALL(*mock_pss_, GetDisableReasons()) .WillByDefault(Return(syncer::SyncService::DISABLE_REASON_NOT_SIGNED_IN)); - ON_CALL(*mock_pss_, IsFirstSetupComplete()).WillByDefault(Return(false)); + ON_CALL(*mock_pss_->GetUserSettingsMock(), IsFirstSetupComplete()) + .WillByDefault(Return(false)); // Ensure that the user is not signed in before calling |HandleStartSignin()|. identity_test_env()->ClearPrimaryAccount(); base::ListValue list_args; @@ -378,7 +379,8 @@ TEST_F(PeopleHandlerFirstSigninTest, DisplayBasicLogin) { TEST_F(PeopleHandlerTest, ShowSyncSetupWhenNotSignedIn) { ON_CALL(*mock_pss_, GetDisableReasons()) .WillByDefault(Return(syncer::SyncService::DISABLE_REASON_NOT_SIGNED_IN)); - ON_CALL(*mock_pss_, IsFirstSetupComplete()).WillByDefault(Return(false)); + ON_CALL(*mock_pss_->GetUserSettingsMock(), IsFirstSetupComplete()) + .WillByDefault(Return(false)); handler_->HandleShowSetupUI(nullptr); ExpectPageStatusChanged(PeopleHandler::kDonePageStatus); @@ -410,11 +412,14 @@ TEST_F(PeopleHandlerTest, HandleSetupUIWhenSyncDisabled) { TEST_F(PeopleHandlerTest, DisplayConfigureWithEngineDisabledAndCancel) { ON_CALL(*mock_pss_, GetDisableReasons()) .WillByDefault(Return(syncer::SyncService::DISABLE_REASON_NONE)); - ON_CALL(*mock_pss_, IsFirstSetupComplete()).WillByDefault(Return(false)); + ON_CALL(*mock_pss_->GetUserSettingsMock(), IsSyncRequested()) + .WillByDefault(Return(true)); + ON_CALL(*mock_pss_->GetUserSettingsMock(), IsFirstSetupComplete()) + .WillByDefault(Return(false)); error_ = GoogleServiceAuthError::AuthErrorNone(); ON_CALL(*mock_pss_, GetTransportState()) .WillByDefault(Return(syncer::SyncService::TransportState::INITIALIZING)); - EXPECT_CALL(*mock_pss_, RequestStart()); + EXPECT_CALL(*mock_pss_->GetUserSettingsMock(), SetSyncRequested(true)); // We're simulating a user setting up sync, which would cause the engine to // kick off initialization, but not download user data types. The sync @@ -434,15 +439,18 @@ TEST_F(PeopleHandlerTest, DisplayConfigureWithEngineDisabledAndCancel) { // to showing a configuration page when sync setup completes successfully. TEST_F(PeopleHandlerTest, DisplayConfigureWithEngineDisabledAndSyncStartupCompleted) { - ON_CALL(*mock_pss_, IsFirstSetupComplete()).WillByDefault(Return(false)); + ON_CALL(*mock_pss_->GetUserSettingsMock(), IsFirstSetupComplete()) + .WillByDefault(Return(false)); ON_CALL(*mock_pss_, GetDisableReasons()) .WillByDefault(Return(syncer::SyncService::DISABLE_REASON_NONE)); + ON_CALL(*mock_pss_->GetUserSettingsMock(), IsSyncRequested()) + .WillByDefault(Return(true)); error_ = GoogleServiceAuthError::AuthErrorNone(); // Sync engine is stopped initially, and will start up. ON_CALL(*mock_pss_, GetTransportState()) .WillByDefault(Return( syncer::SyncService::TransportState::WAITING_FOR_START_REQUEST)); - EXPECT_CALL(*mock_pss_, RequestStart()); + EXPECT_CALL(*mock_pss_->GetUserSettingsMock(), SetSyncRequested(true)); SetDefaultExpectationsForConfigPage(); handler_->HandleShowSetupUI(nullptr); @@ -477,19 +485,22 @@ TEST_F(PeopleHandlerTest, DisplayConfigureWithEngineDisabledAndCancelAfterSigninSuccess) { ON_CALL(*mock_pss_, GetDisableReasons()) .WillByDefault(Return(syncer::SyncService::DISABLE_REASON_NONE)); - ON_CALL(*mock_pss_, IsFirstSetupComplete()).WillByDefault(Return(false)); + ON_CALL(*mock_pss_->GetUserSettingsMock(), IsSyncRequested()) + .WillByDefault(Return(true)); + ON_CALL(*mock_pss_->GetUserSettingsMock(), IsFirstSetupComplete()) + .WillByDefault(Return(false)); error_ = GoogleServiceAuthError::AuthErrorNone(); EXPECT_CALL(*mock_pss_, GetTransportState()) .WillOnce(Return(syncer::SyncService::TransportState::INITIALIZING)) .WillRepeatedly(Return(syncer::SyncService::TransportState::ACTIVE)); - EXPECT_CALL(*mock_pss_, RequestStart()); + EXPECT_CALL(*mock_pss_->GetUserSettingsMock(), SetSyncRequested(true)); SetDefaultExpectationsForConfigPage(); handler_->HandleShowSetupUI(nullptr); // It's important to tell sync the user cancelled the setup flow before we // tell it we're through with the setup progress. testing::InSequence seq; - EXPECT_CALL(*mock_pss_, RequestStop(ProfileSyncService::CLEAR_DATA)); + EXPECT_CALL(*mock_pss_, StopAndClear()); EXPECT_CALL(*mock_pss_, OnSetupInProgressHandleDestroyed()); handler_->CloseSyncSetup(); @@ -501,11 +512,14 @@ TEST_F(PeopleHandlerTest, TEST_F(PeopleHandlerTest, DisplayConfigureWithEngineDisabledAndSigninFailed) { ON_CALL(*mock_pss_, GetDisableReasons()) .WillByDefault(Return(syncer::SyncService::DISABLE_REASON_NONE)); - ON_CALL(*mock_pss_, IsFirstSetupComplete()).WillByDefault(Return(false)); + ON_CALL(*mock_pss_->GetUserSettingsMock(), IsSyncRequested()) + .WillByDefault(Return(true)); + ON_CALL(*mock_pss_->GetUserSettingsMock(), IsFirstSetupComplete()) + .WillByDefault(Return(false)); error_ = GoogleServiceAuthError::AuthErrorNone(); ON_CALL(*mock_pss_, GetTransportState()) .WillByDefault(Return(syncer::SyncService::TransportState::INITIALIZING)); - EXPECT_CALL(*mock_pss_, RequestStart()); + EXPECT_CALL(*mock_pss_->GetUserSettingsMock(), SetSyncRequested(true)); handler_->HandleShowSetupUI(nullptr); ExpectPageStatusChanged(PeopleHandler::kSpinnerPageStatus); @@ -526,20 +540,24 @@ TEST_F(PeopleHandlerTest, RestartSyncAfterDashboardClear) { // being set. ON_CALL(*mock_pss_, GetDisableReasons()) .WillByDefault(Return(syncer::SyncService::DISABLE_REASON_USER_CHOICE)); - ON_CALL(*mock_pss_, IsFirstSetupComplete()).WillByDefault(Return(true)); + ON_CALL(*mock_pss_->GetUserSettingsMock(), IsFirstSetupComplete()) + .WillByDefault(Return(true)); ON_CALL(*mock_pss_, GetTransportState()) .WillByDefault(Return(syncer::SyncService::TransportState::DISABLED)); // Attempting to open the setup UI should restart sync. - EXPECT_CALL(*mock_pss_, RequestStart()).WillOnce([&]() { - // RequestStart() clears DISABLE_REASON_USER_CHOICE, and immediately starts - // initialzing the engine. - ON_CALL(*mock_pss_, GetDisableReasons()) - .WillByDefault(Return(syncer::SyncService::DISABLE_REASON_NONE)); - ON_CALL(*mock_pss_, GetTransportState()) - .WillByDefault( - Return(syncer::SyncService::TransportState::INITIALIZING)); - }); + EXPECT_CALL(*mock_pss_->GetUserSettingsMock(), SetSyncRequested(true)) + .WillOnce([&](bool) { + // SetSyncRequested(true) clears DISABLE_REASON_USER_CHOICE, and + // immediately starts initialzing the engine. + ON_CALL(*mock_pss_, GetDisableReasons()) + .WillByDefault(Return(syncer::SyncService::DISABLE_REASON_NONE)); + ON_CALL(*mock_pss_->GetUserSettingsMock(), IsSyncRequested()) + .WillByDefault(Return(true)); + ON_CALL(*mock_pss_, GetTransportState()) + .WillByDefault( + Return(syncer::SyncService::TransportState::INITIALIZING)); + }); handler_->HandleShowSetupUI(nullptr); ExpectPageStatusChanged(PeopleHandler::kSpinnerPageStatus); @@ -552,20 +570,24 @@ TEST_F(PeopleHandlerTest, // mode. ON_CALL(*mock_pss_, GetDisableReasons()) .WillByDefault(Return(syncer::SyncService::DISABLE_REASON_USER_CHOICE)); - ON_CALL(*mock_pss_, IsFirstSetupComplete()).WillByDefault(Return(true)); + ON_CALL(*mock_pss_->GetUserSettingsMock(), IsFirstSetupComplete()) + .WillByDefault(Return(true)); ON_CALL(*mock_pss_, GetTransportState()) .WillByDefault(Return(syncer::SyncService::TransportState::ACTIVE)); // Attempting to open the setup UI should re-enable sync-the-feature. - EXPECT_CALL(*mock_pss_, RequestStart()).WillOnce([&]() { - // RequestStart() clears DISABLE_REASON_USER_CHOICE. Since the engine is - // already running, it just gets reconfigured. - ON_CALL(*mock_pss_, GetDisableReasons()) - .WillByDefault(Return(syncer::SyncService::DISABLE_REASON_NONE)); - ON_CALL(*mock_pss_, GetTransportState()) - .WillByDefault( - Return(syncer::SyncService::TransportState::CONFIGURING)); - }); + EXPECT_CALL(*mock_pss_->GetUserSettingsMock(), SetSyncRequested(true)) + .WillOnce([&](bool) { + // SetSyncRequested(true) clears DISABLE_REASON_USER_CHOICE. Since the + // engine is already running, it just gets reconfigured. + ON_CALL(*mock_pss_, GetDisableReasons()) + .WillByDefault(Return(syncer::SyncService::DISABLE_REASON_NONE)); + ON_CALL(*mock_pss_->GetUserSettingsMock(), IsSyncRequested()) + .WillByDefault(Return(true)); + ON_CALL(*mock_pss_, GetTransportState()) + .WillByDefault( + Return(syncer::SyncService::TransportState::CONFIGURING)); + }); handler_->HandleShowSetupUI(nullptr); ExpectPageStatusChanged(PeopleHandler::kSpinnerPageStatus); @@ -576,7 +598,8 @@ TEST_F(PeopleHandlerTest, TEST_F(PeopleHandlerTest, OnlyStartEngineWhenConfiguringSync) { ON_CALL(*mock_pss_, GetTransportState()) .WillByDefault(Return(syncer::SyncService::TransportState::INITIALIZING)); - EXPECT_CALL(*mock_pss_, RequestStart()).Times(0); + EXPECT_CALL(*mock_pss_->GetUserSettingsMock(), SetSyncRequested(true)) + .Times(0); NotifySyncStateChanged(); } @@ -614,7 +637,8 @@ TEST_F(PeopleHandlerNonCrosTest, UnrecoverableErrorInitializingSync) { ON_CALL(*mock_pss_, GetDisableReasons()) .WillByDefault( Return(syncer::SyncService::DISABLE_REASON_UNRECOVERABLE_ERROR)); - ON_CALL(*mock_pss_, IsFirstSetupComplete()).WillByDefault(Return(false)); + ON_CALL(*mock_pss_->GetUserSettingsMock(), IsFirstSetupComplete()) + .WillByDefault(Return(false)); // Open the web UI. handler_->HandleShowSetupUI(nullptr); @@ -624,7 +648,8 @@ TEST_F(PeopleHandlerNonCrosTest, UnrecoverableErrorInitializingSync) { TEST_F(PeopleHandlerNonCrosTest, GaiaErrorInitializingSync) { ON_CALL(*mock_pss_, GetDisableReasons()) .WillByDefault(Return(syncer::SyncService::DISABLE_REASON_NOT_SIGNED_IN)); - ON_CALL(*mock_pss_, IsFirstSetupComplete()).WillByDefault(Return(false)); + ON_CALL(*mock_pss_->GetUserSettingsMock(), IsFirstSetupComplete()) + .WillByDefault(Return(false)); // Open the web UI. handler_->HandleShowSetupUI(nullptr); @@ -639,11 +664,13 @@ TEST_F(PeopleHandlerTest, TestSyncEverything) { base::ListValue list_args; list_args.AppendString(kTestCallbackId); list_args.AppendString(args); - ON_CALL(*mock_pss_, IsPassphraseRequiredForDecryption()) + ON_CALL(*mock_pss_->GetUserSettingsMock(), + IsPassphraseRequiredForDecryption()) + .WillByDefault(Return(false)); + ON_CALL(*mock_pss_->GetUserSettingsMock(), IsPassphraseRequired()) .WillByDefault(Return(false)); - ON_CALL(*mock_pss_, IsPassphraseRequired()).WillByDefault(Return(false)); SetupInitializedProfileSyncService(); - EXPECT_CALL(*mock_pss_, OnUserChoseDatatypes(true, _)); + EXPECT_CALL(*mock_pss_->GetUserSettingsMock(), SetChosenDataTypes(true, _)); handler_->HandleSetDatatypes(&list_args); ExpectPageStatusResponse(PeopleHandler::kConfigurePageStatus); @@ -655,10 +682,12 @@ TEST_F(PeopleHandlerTest, TestPassphraseStillRequired) { base::ListValue list_args; list_args.AppendString(kTestCallbackId); list_args.AppendString(args); - ON_CALL(*mock_pss_, IsPassphraseRequiredForDecryption()) + ON_CALL(*mock_pss_->GetUserSettingsMock(), + IsPassphraseRequiredForDecryption()) + .WillByDefault(Return(true)); + ON_CALL(*mock_pss_->GetUserSettingsMock(), IsPassphraseRequired()) .WillByDefault(Return(true)); - ON_CALL(*mock_pss_, IsPassphraseRequired()).WillByDefault(Return(true)); - ON_CALL(*mock_pss_, IsUsingSecondaryPassphrase()) + ON_CALL(*mock_pss_->GetUserSettingsMock(), IsUsingSecondaryPassphrase()) .WillByDefault(Return(false)); SetupInitializedProfileSyncService(); SetDefaultExpectationsForConfigPage(); @@ -678,13 +707,16 @@ TEST_F(PeopleHandlerTest, EnterExistingFrozenImplicitPassword) { list_args.AppendString(args); // Act as if an encryption passphrase is required the first time, then never // again after that. - EXPECT_CALL(*mock_pss_, IsPassphraseRequired()).WillOnce(Return(true)); - ON_CALL(*mock_pss_, IsPassphraseRequiredForDecryption()) + EXPECT_CALL(*mock_pss_->GetUserSettingsMock(), IsPassphraseRequired()) + .WillOnce(Return(true)); + ON_CALL(*mock_pss_->GetUserSettingsMock(), + IsPassphraseRequiredForDecryption()) .WillByDefault(Return(false)); - ON_CALL(*mock_pss_, IsUsingSecondaryPassphrase()) + ON_CALL(*mock_pss_->GetUserSettingsMock(), IsUsingSecondaryPassphrase()) .WillByDefault(Return(false)); SetupInitializedProfileSyncService(); - EXPECT_CALL(*mock_pss_, SetDecryptionPassphrase("oldGaiaPassphrase")) + EXPECT_CALL(*mock_pss_->GetUserSettingsMock(), + SetDecryptionPassphrase("oldGaiaPassphrase")) .WillOnce(Return(true)); handler_->HandleSetEncryption(&list_args); @@ -699,13 +731,16 @@ TEST_F(PeopleHandlerTest, SetNewCustomPassphrase) { base::ListValue list_args; list_args.AppendString(kTestCallbackId); list_args.AppendString(args); - ON_CALL(*mock_pss_, IsPassphraseRequiredForDecryption()) + ON_CALL(*mock_pss_->GetUserSettingsMock(), + IsPassphraseRequiredForDecryption()) + .WillByDefault(Return(false)); + ON_CALL(*mock_pss_->GetUserSettingsMock(), IsPassphraseRequired()) .WillByDefault(Return(false)); - ON_CALL(*mock_pss_, IsPassphraseRequired()).WillByDefault(Return(false)); - ON_CALL(*mock_pss_, IsUsingSecondaryPassphrase()) + ON_CALL(*mock_pss_->GetUserSettingsMock(), IsUsingSecondaryPassphrase()) .WillByDefault(Return(false)); SetupInitializedProfileSyncService(); - EXPECT_CALL(*mock_pss_, SetEncryptionPassphrase("custom_passphrase")); + EXPECT_CALL(*mock_pss_->GetUserSettingsMock(), + SetEncryptionPassphrase("custom_passphrase")); handler_->HandleSetEncryption(&list_args); ExpectPageStatusResponse(PeopleHandler::kConfigurePageStatus); @@ -719,14 +754,17 @@ TEST_F(PeopleHandlerTest, EnterWrongExistingPassphrase) { base::ListValue list_args; list_args.AppendString(kTestCallbackId); list_args.AppendString(args); - ON_CALL(*mock_pss_, IsPassphraseRequiredForDecryption()) + ON_CALL(*mock_pss_->GetUserSettingsMock(), + IsPassphraseRequiredForDecryption()) .WillByDefault(Return(true)); - ON_CALL(*mock_pss_, IsPassphraseRequired()).WillByDefault(Return(true)); - ON_CALL(*mock_pss_, IsUsingSecondaryPassphrase()) + ON_CALL(*mock_pss_->GetUserSettingsMock(), IsPassphraseRequired()) + .WillByDefault(Return(true)); + ON_CALL(*mock_pss_->GetUserSettingsMock(), IsUsingSecondaryPassphrase()) .WillByDefault(Return(false)); SetupInitializedProfileSyncService(); - EXPECT_CALL(*mock_pss_, SetDecryptionPassphrase("invalid_passphrase")). - WillOnce(Return(false)); + EXPECT_CALL(*mock_pss_->GetUserSettingsMock(), + SetDecryptionPassphrase("invalid_passphrase")) + .WillOnce(Return(false)); SetDefaultExpectationsForConfigPage(); @@ -746,10 +784,12 @@ TEST_F(PeopleHandlerTest, EnterBlankExistingPassphrase) { base::ListValue list_args; list_args.AppendString(kTestCallbackId); list_args.AppendString(args); - ON_CALL(*mock_pss_, IsPassphraseRequiredForDecryption()) + ON_CALL(*mock_pss_->GetUserSettingsMock(), + IsPassphraseRequiredForDecryption()) + .WillByDefault(Return(true)); + ON_CALL(*mock_pss_->GetUserSettingsMock(), IsPassphraseRequired()) .WillByDefault(Return(true)); - ON_CALL(*mock_pss_, IsPassphraseRequired()).WillByDefault(Return(true)); - ON_CALL(*mock_pss_, IsUsingSecondaryPassphrase()) + ON_CALL(*mock_pss_->GetUserSettingsMock(), IsUsingSecondaryPassphrase()) .WillByDefault(Return(false)); SetupInitializedProfileSyncService(); @@ -775,12 +815,14 @@ TEST_F(PeopleHandlerTest, TestSyncIndividualTypes) { base::ListValue list_args; list_args.AppendString(kTestCallbackId); list_args.AppendString(args); - ON_CALL(*mock_pss_, IsPassphraseRequiredForDecryption()) + ON_CALL(*mock_pss_->GetUserSettingsMock(), + IsPassphraseRequiredForDecryption()) + .WillByDefault(Return(false)); + ON_CALL(*mock_pss_->GetUserSettingsMock(), IsPassphraseRequired()) .WillByDefault(Return(false)); - ON_CALL(*mock_pss_, IsPassphraseRequired()).WillByDefault(Return(false)); SetupInitializedProfileSyncService(); - EXPECT_CALL(*mock_pss_, - OnUserChoseDatatypes(false, ModelTypeSetMatches(type_to_set))); + EXPECT_CALL(*mock_pss_->GetUserSettingsMock(), + SetChosenDataTypes(false, ModelTypeSetMatches(type_to_set))); handler_->HandleSetDatatypes(&list_args); ExpectPageStatusResponse(PeopleHandler::kConfigurePageStatus); @@ -797,20 +839,23 @@ TEST_F(PeopleHandlerTest, TestSyncAllManually) { base::ListValue list_args; list_args.AppendString(kTestCallbackId); list_args.AppendString(args); - ON_CALL(*mock_pss_, IsPassphraseRequiredForDecryption()) + ON_CALL(*mock_pss_->GetUserSettingsMock(), + IsPassphraseRequiredForDecryption()) + .WillByDefault(Return(false)); + ON_CALL(*mock_pss_->GetUserSettingsMock(), IsPassphraseRequired()) .WillByDefault(Return(false)); - ON_CALL(*mock_pss_, IsPassphraseRequired()).WillByDefault(Return(false)); SetupInitializedProfileSyncService(); - EXPECT_CALL(*mock_pss_, - OnUserChoseDatatypes(false, ModelTypeSetMatches(GetAllTypes()))); + EXPECT_CALL(*mock_pss_->GetUserSettingsMock(), + SetChosenDataTypes(false, ModelTypeSetMatches(GetAllTypes()))); handler_->HandleSetDatatypes(&list_args); ExpectPageStatusResponse(PeopleHandler::kConfigurePageStatus); } TEST_F(PeopleHandlerTest, ShowSyncSetup) { - ON_CALL(*mock_pss_, IsPassphraseRequired()).WillByDefault(Return(false)); - ON_CALL(*mock_pss_, IsUsingSecondaryPassphrase()) + ON_CALL(*mock_pss_->GetUserSettingsMock(), IsPassphraseRequired()) + .WillByDefault(Return(false)); + ON_CALL(*mock_pss_->GetUserSettingsMock(), IsUsingSecondaryPassphrase()) .WillByDefault(Return(false)); SetupInitializedProfileSyncService(); // This should display the sync setup dialog (not login). @@ -827,24 +872,29 @@ TEST_F(PeopleHandlerTest, ShowSigninOnAuthError) { GoogleServiceAuthError::INVALID_GAIA_CREDENTIALS); SetupInitializedProfileSyncService(); - DCHECK_EQ( - identity_test_env()->identity_manager()->GetPrimaryAccountInfo().email, - kTestUser); - const std::string& account_id = identity_test_env() - ->identity_manager() - ->GetPrimaryAccountInfo() - .account_id; - ProfileOAuth2TokenService* token_service = - ProfileOAuth2TokenServiceFactory::GetForProfile(profile()); - token_service->UpdateCredentials(account_id, "refresh_token"); - // TODO(https://crbug.com/836212): Do not use the delegate directly, because - // it is internal API. - token_service->GetDelegate()->UpdateAuthError(account_id, error_); + + auto* identity_manager = identity_test_env()->identity_manager(); + AccountInfo primary_account_info = identity_manager->GetPrimaryAccountInfo(); + DCHECK_EQ(primary_account_info.email, kTestUser); + + auto* accounts_mutator = identity_manager->GetAccountsMutator(); + DCHECK(accounts_mutator); + + accounts_mutator->AddOrUpdateAccount( + primary_account_info.gaia, primary_account_info.email, "refresh_token", + primary_account_info.is_under_advanced_protection, + signin_metrics::SourceForRefreshTokenOperation::kUnknown); + + identity::UpdatePersistentErrorOfRefreshTokenForAccount( + identity_manager, primary_account_info.account_id, error_); ON_CALL(*mock_pss_, GetDisableReasons()) .WillByDefault(Return(syncer::SyncService::DISABLE_REASON_NONE)); - ON_CALL(*mock_pss_, IsPassphraseRequired()).WillByDefault(Return(false)); - ON_CALL(*mock_pss_, IsUsingSecondaryPassphrase()) + ON_CALL(*mock_pss_->GetUserSettingsMock(), IsSyncRequested()) + .WillByDefault(Return(true)); + ON_CALL(*mock_pss_->GetUserSettingsMock(), IsPassphraseRequired()) + .WillByDefault(Return(false)); + ON_CALL(*mock_pss_->GetUserSettingsMock(), IsUsingSecondaryPassphrase()) .WillByDefault(Return(false)); ON_CALL(*mock_pss_, GetTransportState()) .WillByDefault(Return(syncer::SyncService::TransportState::INITIALIZING)); @@ -874,8 +924,9 @@ TEST_F(PeopleHandlerTest, ShowSigninOnAuthError) { } TEST_F(PeopleHandlerTest, ShowSetupSyncEverything) { - ON_CALL(*mock_pss_, IsPassphraseRequired()).WillByDefault(Return(false)); - ON_CALL(*mock_pss_, IsUsingSecondaryPassphrase()) + ON_CALL(*mock_pss_->GetUserSettingsMock(), IsPassphraseRequired()) + .WillByDefault(Return(false)); + ON_CALL(*mock_pss_->GetUserSettingsMock(), IsUsingSecondaryPassphrase()) .WillByDefault(Return(false)); SetupInitializedProfileSyncService(); SetDefaultExpectationsForConfigPage(); @@ -901,13 +952,14 @@ TEST_F(PeopleHandlerTest, ShowSetupSyncEverything) { } TEST_F(PeopleHandlerTest, ShowSetupManuallySyncAll) { - ON_CALL(*mock_pss_, IsPassphraseRequired()).WillByDefault(Return(false)); - ON_CALL(*mock_pss_, IsUsingSecondaryPassphrase()) + ON_CALL(*mock_pss_->GetUserSettingsMock(), IsPassphraseRequired()) + .WillByDefault(Return(false)); + ON_CALL(*mock_pss_->GetUserSettingsMock(), IsUsingSecondaryPassphrase()) .WillByDefault(Return(false)); SetupInitializedProfileSyncService(); - syncer::SyncPrefs sync_prefs(profile()->GetPrefs()); - sync_prefs.SetKeepEverythingSynced(false); SetDefaultExpectationsForConfigPage(); + ON_CALL(*mock_pss_->GetUserSettingsMock(), IsSyncEverythingEnabled()) + .WillByDefault(Return(false)); // This should display the sync setup dialog (not login). handler_->HandleShowSetupUI(nullptr); @@ -918,16 +970,18 @@ TEST_F(PeopleHandlerTest, ShowSetupManuallySyncAll) { TEST_F(PeopleHandlerTest, ShowSetupSyncForAllTypesIndividually) { syncer::ModelTypeSet user_selectable_types = GetAllTypes(); for (syncer::ModelType type : user_selectable_types) { - ON_CALL(*mock_pss_, IsPassphraseRequired()).WillByDefault(Return(false)); - ON_CALL(*mock_pss_, IsUsingSecondaryPassphrase()) + ON_CALL(*mock_pss_->GetUserSettingsMock(), IsPassphraseRequired()) + .WillByDefault(Return(false)); + ON_CALL(*mock_pss_->GetUserSettingsMock(), IsUsingSecondaryPassphrase()) .WillByDefault(Return(false)); SetupInitializedProfileSyncService(); - syncer::SyncPrefs sync_prefs(profile()->GetPrefs()); - sync_prefs.SetKeepEverythingSynced(false); SetDefaultExpectationsForConfigPage(); + ON_CALL(*mock_pss_->GetUserSettingsMock(), IsSyncEverythingEnabled()) + .WillByDefault(Return(false)); syncer::ModelTypeSet types; types.Put(type); - ON_CALL(*mock_pss_, GetPreferredDataTypes()).WillByDefault(Return(types)); + ON_CALL(*mock_pss_->GetUserSettingsMock(), GetChosenDataTypes()) + .WillByDefault(Return(types)); // This should display the sync setup dialog (not login). handler_->HandleShowSetupUI(nullptr); @@ -945,8 +999,9 @@ TEST_F(PeopleHandlerTest, ShowSetupSyncForAllTypesIndividually) { } TEST_F(PeopleHandlerTest, ShowSetupOldGaiaPassphraseRequired) { - ON_CALL(*mock_pss_, IsPassphraseRequired()).WillByDefault(Return(true)); - ON_CALL(*mock_pss_, GetPassphraseType()) + ON_CALL(*mock_pss_->GetUserSettingsMock(), IsPassphraseRequired()) + .WillByDefault(Return(true)); + ON_CALL(*mock_pss_->GetUserSettingsMock(), GetPassphraseType()) .WillByDefault( Return(syncer::PassphraseType::FROZEN_IMPLICIT_PASSPHRASE)); SetupInitializedProfileSyncService(); @@ -961,8 +1016,9 @@ TEST_F(PeopleHandlerTest, ShowSetupOldGaiaPassphraseRequired) { } TEST_F(PeopleHandlerTest, ShowSetupCustomPassphraseRequired) { - ON_CALL(*mock_pss_, IsPassphraseRequired()).WillByDefault(Return(true)); - ON_CALL(*mock_pss_, GetPassphraseType()) + ON_CALL(*mock_pss_->GetUserSettingsMock(), IsPassphraseRequired()) + .WillByDefault(Return(true)); + ON_CALL(*mock_pss_->GetUserSettingsMock(), GetPassphraseType()) .WillByDefault(Return(syncer::PassphraseType::CUSTOM_PASSPHRASE)); SetupInitializedProfileSyncService(); SetDefaultExpectationsForConfigPage(); @@ -976,12 +1032,14 @@ TEST_F(PeopleHandlerTest, ShowSetupCustomPassphraseRequired) { } TEST_F(PeopleHandlerTest, ShowSetupEncryptAll) { - ON_CALL(*mock_pss_, IsPassphraseRequired()).WillByDefault(Return(false)); - ON_CALL(*mock_pss_, IsUsingSecondaryPassphrase()) + ON_CALL(*mock_pss_->GetUserSettingsMock(), IsPassphraseRequired()) + .WillByDefault(Return(false)); + ON_CALL(*mock_pss_->GetUserSettingsMock(), IsUsingSecondaryPassphrase()) .WillByDefault(Return(false)); SetupInitializedProfileSyncService(); SetDefaultExpectationsForConfigPage(); - ON_CALL(*mock_pss_, IsEncryptEverythingEnabled()).WillByDefault(Return(true)); + ON_CALL(*mock_pss_->GetUserSettingsMock(), IsEncryptEverythingEnabled()) + .WillByDefault(Return(true)); // This should display the sync setup dialog (not login). handler_->HandleShowSetupUI(nullptr); @@ -991,12 +1049,13 @@ TEST_F(PeopleHandlerTest, ShowSetupEncryptAll) { } TEST_F(PeopleHandlerTest, ShowSetupEncryptAllDisallowed) { - ON_CALL(*mock_pss_, IsPassphraseRequired()).WillByDefault(Return(false)); - ON_CALL(*mock_pss_, IsUsingSecondaryPassphrase()) + ON_CALL(*mock_pss_->GetUserSettingsMock(), IsPassphraseRequired()) + .WillByDefault(Return(false)); + ON_CALL(*mock_pss_->GetUserSettingsMock(), IsUsingSecondaryPassphrase()) .WillByDefault(Return(false)); SetupInitializedProfileSyncService(); SetDefaultExpectationsForConfigPage(); - ON_CALL(*mock_pss_, IsEncryptEverythingAllowed()) + ON_CALL(*mock_pss_->GetUserSettingsMock(), IsEncryptEverythingAllowed()) .WillByDefault(Return(false)); // This should display the sync setup dialog (not login). @@ -1013,13 +1072,16 @@ TEST_F(PeopleHandlerTest, TurnOnEncryptAllDisallowed) { base::ListValue list_args; list_args.AppendString(kTestCallbackId); list_args.AppendString(args); - ON_CALL(*mock_pss_, IsPassphraseRequiredForDecryption()) + ON_CALL(*mock_pss_->GetUserSettingsMock(), + IsPassphraseRequiredForDecryption()) + .WillByDefault(Return(false)); + ON_CALL(*mock_pss_->GetUserSettingsMock(), IsPassphraseRequired()) .WillByDefault(Return(false)); - ON_CALL(*mock_pss_, IsPassphraseRequired()).WillByDefault(Return(false)); SetupInitializedProfileSyncService(); - ON_CALL(*mock_pss_, IsEncryptEverythingAllowed()) + ON_CALL(*mock_pss_->GetUserSettingsMock(), IsEncryptEverythingAllowed()) .WillByDefault(Return(false)); - EXPECT_CALL(*mock_pss_, EnableEncryptEverything()).Times(0); + EXPECT_CALL(*mock_pss_->GetUserSettingsMock(), EnableEncryptEverything()) + .Times(0); handler_->HandleSetEncryption(&list_args); ExpectPageStatusResponse(PeopleHandler::kConfigurePageStatus); @@ -1042,7 +1104,7 @@ TEST_P(PeopleHandlerDiceUnifiedConsentTest, StoredAccountsList) { : unified_consent::UnifiedConsentFeatureState::kDisabled); ScopedAccountConsistency dice( dice_enabled ? signin::AccountConsistencyMethod::kDice - : signin::AccountConsistencyMethod::kDiceFixAuthErrors); + : signin::AccountConsistencyMethod::kDiceMigration); // Setup the profile. std::unique_ptr<TestingProfile> profile = @@ -1058,21 +1120,23 @@ TEST_P(PeopleHandlerDiceUnifiedConsentTest, StoredAccountsList) { identity_test_env->SetPrimaryAccount(account_1.email); PeopleHandler handler(profile.get()); - std::unique_ptr<base::ListValue> accounts_list = - handler.GetStoredAccountsList(); + base::Value accounts = handler.GetStoredAccountsList(); + + ASSERT_TRUE(accounts.is_list()); + const base::Value::ListStorage& accounts_list = accounts.GetList(); if (dice_enabled) { - EXPECT_EQ(2u, accounts_list->GetSize()); - EXPECT_EQ("a@gmail.com", - accounts_list->GetList()[0].FindKey("email")->GetString()); - EXPECT_EQ("b@gmail.com", - accounts_list->GetList()[1].FindKey("email")->GetString()); + ASSERT_EQ(2u, accounts_list.size()); + ASSERT_TRUE(accounts_list[0].FindKey("email")); + ASSERT_TRUE(accounts_list[1].FindKey("email")); + EXPECT_EQ("a@gmail.com", accounts_list[0].FindKey("email")->GetString()); + EXPECT_EQ("b@gmail.com", accounts_list[1].FindKey("email")->GetString()); } else if (unified_consent_enabled) { - EXPECT_EQ(1u, accounts_list->GetSize()); - EXPECT_EQ("a@gmail.com", - accounts_list->GetList()[0].FindKey("email")->GetString()); + ASSERT_EQ(1u, accounts_list.size()); + ASSERT_TRUE(accounts_list[0].FindKey("email")); + EXPECT_EQ("a@gmail.com", accounts_list[0].FindKey("email")->GetString()); } else { - EXPECT_EQ(0u, accounts_list->GetSize()); + EXPECT_EQ(0u, accounts_list.size()); } } diff --git a/chromium/chrome/browser/ui/webui/settings/settings_clear_browsing_data_handler.cc b/chromium/chrome/browser/ui/webui/settings/settings_clear_browsing_data_handler.cc index 39487b81589..145aa955d96 100644 --- a/chromium/chrome/browser/ui/webui/settings/settings_clear_browsing_data_handler.cc +++ b/chromium/chrome/browser/ui/webui/settings/settings_clear_browsing_data_handler.cc @@ -8,9 +8,9 @@ #include <vector> #include "base/feature_list.h" -#include "base/macros.h" #include "base/metrics/histogram_functions.h" #include "base/metrics/histogram_macros.h" +#include "base/stl_util.h" #include "base/values.h" #include "chrome/browser/browsing_data/browsing_data_helper.h" #include "chrome/browser/browsing_data/browsing_data_important_sites_util.h" @@ -20,7 +20,6 @@ #include "chrome/browser/history/web_history_service_factory.h" #include "chrome/browser/signin/account_reconcilor_factory.h" #include "chrome/browser/signin/identity_manager_factory.h" -#include "chrome/browser/signin/signin_manager_factory.h" #include "chrome/browser/sync/profile_sync_service_factory.h" #include "chrome/browser/sync/sync_ui_util.h" #include "chrome/common/channel_info.h" @@ -57,7 +56,6 @@ const char* kCounterPrefsAdvanced[] = { browsing_data::prefs::kDeleteDownloadHistory, browsing_data::prefs::kDeleteFormData, browsing_data::prefs::kDeleteHostedAppsData, - browsing_data::prefs::kDeleteMediaLicenses, browsing_data::prefs::kDeletePasswords, browsing_data::prefs::kDeleteSiteSettings, }; @@ -198,9 +196,6 @@ void ClearBrowsingDataHandler::HandleClearBrowsingData( remove_mask |= ChromeBrowsingDataRemoverDelegate::DATA_TYPE_CONTENT_SETTINGS; break; - case BrowsingDataType::MEDIA_LICENSES: - remove_mask |= content::BrowsingDataRemover::DATA_TYPE_MEDIA_LICENSES; - break; case BrowsingDataType::HOSTED_APPS_DATA: remove_mask |= site_data_mask; origin_mask |= content::BrowsingDataRemover::ORIGIN_TYPE_PROTECTED_WEB; @@ -238,9 +233,8 @@ void ClearBrowsingDataHandler::HandleClearBrowsingData( BrowsingDataType::HISTORY, BrowsingDataType::DOWNLOADS, BrowsingDataType::CACHE, BrowsingDataType::COOKIES, BrowsingDataType::FORM_DATA, BrowsingDataType::HOSTED_APPS_DATA, - BrowsingDataType::MEDIA_LICENSES, }; - static size_t num_other_types = arraysize(other_types); + static size_t num_other_types = base::size(other_types); int checked_other_types = std::count_if(other_types, other_types + num_other_types, [&data_types](BrowsingDataType type) { @@ -256,7 +250,7 @@ void ClearBrowsingDataHandler::HandleClearBrowsingData( std::unique_ptr<AccountReconcilor::ScopedSyncedDataDeletion> scoped_data_deletion; sync_ui_util::MessageType sync_status = sync_ui_util::GetStatus( - profile_, sync_service_, *SigninManagerFactory::GetForProfile(profile_)); + profile_, sync_service_, IdentityManagerFactory::GetForProfile(profile_)); if (sync_status == sync_ui_util::SYNCED) { scoped_data_deletion = AccountReconcilorFactory::GetForProfile(profile_) ->GetScopedSyncDataDeletion(); @@ -345,8 +339,8 @@ void ClearBrowsingDataHandler::OnStateChanged(syncer::SyncService* sync) { void ClearBrowsingDataHandler::UpdateSyncState() { identity::IdentityManager* identity_manager = IdentityManagerFactory::GetForProfile(profile_); - CallJavascriptFunction( - "cr.webUIListenerCallback", base::Value("update-sync-state"), + FireWebUIListener( + "update-sync-state", base::Value(identity_manager && identity_manager->HasPrimaryAccount()), base::Value(sync_service_ && sync_service_->IsSyncFeatureActive() && sync_service_->GetActiveDataTypes().Has( @@ -389,9 +383,8 @@ void ClearBrowsingDataHandler::AddCounter( void ClearBrowsingDataHandler::UpdateCounterText( std::unique_ptr<browsing_data::BrowsingDataCounter::Result> result) { - CallJavascriptFunction( - "cr.webUIListenerCallback", base::Value("update-counter-text"), - base::Value(result->source()->GetPrefName()), + FireWebUIListener( + "update-counter-text", base::Value(result->source()->GetPrefName()), base::Value(browsing_data_counter_utils::GetChromeCounterTextFromResult( result.get(), profile_))); } diff --git a/chromium/chrome/browser/ui/webui/settings/settings_cookies_view_handler.cc b/chromium/chrome/browser/ui/webui/settings/settings_cookies_view_handler.cc index 12b0a2a44ee..67db5ae7a92 100644 --- a/chromium/chrome/browser/ui/webui/settings/settings_cookies_view_handler.cc +++ b/chromium/chrome/browser/ui/webui/settings/settings_cookies_view_handler.cc @@ -12,22 +12,9 @@ #include "base/bind.h" #include "base/bind_helpers.h" #include "base/i18n/number_formatting.h" -#include "base/macros.h" +#include "base/stl_util.h" #include "base/strings/utf_string_conversions.h" #include "base/values.h" -#include "chrome/browser/browsing_data/browsing_data_appcache_helper.h" -#include "chrome/browser/browsing_data/browsing_data_cache_storage_helper.h" -#include "chrome/browser/browsing_data/browsing_data_channel_id_helper.h" -#include "chrome/browser/browsing_data/browsing_data_cookie_helper.h" -#include "chrome/browser/browsing_data/browsing_data_database_helper.h" -#include "chrome/browser/browsing_data/browsing_data_file_system_helper.h" -#include "chrome/browser/browsing_data/browsing_data_flash_lso_helper.h" -#include "chrome/browser/browsing_data/browsing_data_indexed_db_helper.h" -#include "chrome/browser/browsing_data/browsing_data_local_storage_helper.h" -#include "chrome/browser/browsing_data/browsing_data_media_license_helper.h" -#include "chrome/browser/browsing_data/browsing_data_quota_helper.h" -#include "chrome/browser/browsing_data/browsing_data_service_worker_helper.h" -#include "chrome/browser/browsing_data/browsing_data_shared_worker_helper.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/ui/webui/cookies_tree_model_util.h" #include "chrome/grit/generated_resources.h" @@ -45,9 +32,6 @@ class FileSystemContext; namespace { -constexpr char kEffectiveTopLevelDomainPlus1Name[] = "etldPlus1"; -constexpr char kNumCookies[] = "numCookies"; - int GetCategoryLabelID(CookieTreeNode::DetailedInfo::NodeType node_type) { constexpr struct { CookieTreeNode::DetailedInfo::NodeType node_type; @@ -80,11 +64,6 @@ int GetCategoryLabelID(CookieTreeNode::DetailedInfo::NodeType node_type) { {CookieTreeNode::DetailedInfo::TYPE_FILE_SYSTEM, IDS_SETTINGS_COOKIES_FILE_SYSTEM}, - {CookieTreeNode::DetailedInfo::TYPE_CHANNEL_IDS, - IDS_SETTINGS_COOKIES_CHANNEL_ID}, - {CookieTreeNode::DetailedInfo::TYPE_CHANNEL_ID, - IDS_SETTINGS_COOKIES_CHANNEL_ID}, - {CookieTreeNode::DetailedInfo::TYPE_SERVICE_WORKERS, IDS_SETTINGS_COOKIES_SERVICE_WORKER}, {CookieTreeNode::DetailedInfo::TYPE_SERVICE_WORKER, @@ -110,7 +89,7 @@ int GetCategoryLabelID(CookieTreeNode::DetailedInfo::NodeType node_type) { }; // Before optimizing, consider the data size and the cost of L2 cache misses. // A linear search over a couple dozen integers is very fast. - for (size_t i = 0; i < arraysize(kCategoryLabels); ++i) { + for (size_t i = 0; i < base::size(kCategoryLabels); ++i) { if (kCategoryLabels[i].node_type == node_type) { return kCategoryLabels[i].id; } @@ -177,10 +156,6 @@ void CookiesViewHandler::RegisterMessages() { base::BindRepeating(&CookiesViewHandler::HandleGetCookieDetails, base::Unretained(this))); web_ui()->RegisterMessageCallback( - "localData.getNumCookiesList", - base::BindRepeating(&CookiesViewHandler::HandleGetNumCookiesList, - base::Unretained(this))); - web_ui()->RegisterMessageCallback( "localData.getNumCookiesString", base::BindRepeating(&CookiesViewHandler::HandleGetNumCookiesString, base::Unretained(this))); @@ -264,34 +239,7 @@ void CookiesViewHandler::TreeModelEndBatch(CookiesTreeModel* model) { void CookiesViewHandler::EnsureCookiesTreeModelCreated() { if (!cookies_tree_model_.get()) { Profile* profile = Profile::FromWebUI(web_ui()); - content::StoragePartition* storage_partition = - content::BrowserContext::GetDefaultStoragePartition(profile); - content::IndexedDBContext* indexed_db_context = - storage_partition->GetIndexedDBContext(); - content::ServiceWorkerContext* service_worker_context = - storage_partition->GetServiceWorkerContext(); - content::CacheStorageContext* cache_storage_context = - storage_partition->GetCacheStorageContext(); - storage::FileSystemContext* file_system_context = - storage_partition->GetFileSystemContext(); - auto container = std::make_unique<LocalDataContainer>( - new BrowsingDataCookieHelper(storage_partition), - new BrowsingDataDatabaseHelper(profile), - new BrowsingDataLocalStorageHelper(profile), - /*session_storage_helper=*/nullptr, - new BrowsingDataAppCacheHelper(profile), - new BrowsingDataIndexedDBHelper(indexed_db_context), - BrowsingDataFileSystemHelper::Create(file_system_context), - BrowsingDataQuotaHelper::Create(profile), - BrowsingDataChannelIDHelper::Create(profile->GetRequestContext()), - new BrowsingDataServiceWorkerHelper(service_worker_context), - new BrowsingDataSharedWorkerHelper(storage_partition, - profile->GetResourceContext()), - new BrowsingDataCacheStorageHelper(cache_storage_context), - BrowsingDataFlashLSOHelper::Create(profile), - BrowsingDataMediaLicenseHelper::Create(file_system_context)); - cookies_tree_model_ = std::make_unique<CookiesTreeModel>( - std::move(container), profile->GetExtensionSpecialStoragePolicy()); + cookies_tree_model_ = CookiesTreeModel::CreateForProfile(profile); cookies_tree_model_->AddCookiesTreeObserver(this); } } @@ -316,64 +264,6 @@ void CookiesViewHandler::HandleGetCookieDetails(const base::ListValue* args) { SendCookieDetails(node); } -void CookiesViewHandler::HandleGetNumCookiesList(const base::ListValue* args) { - CHECK_EQ(2U, args->GetSize()); - std::string callback_id; - CHECK(args->GetString(0, &callback_id)); - const base::ListValue* etld_plus1_list; - CHECK(args->GetList(1, &etld_plus1_list)); - - AllowJavascript(); - CHECK(cookies_tree_model_.get()); - - base::string16 etld_plus1; - base::Value result(base::Value::Type::LIST); - for (size_t i = 0; i < etld_plus1_list->GetSize(); ++i) { - etld_plus1_list->GetString(i, &etld_plus1); - // This method is only interested in the number of cookies, so don't save - // |etld_plus1| as a new filter and keep the existing |sorted_sites_| list. - cookies_tree_model_->UpdateSearchResults(etld_plus1); - - int num_cookies = 0; - const CookieTreeNode* root = cookies_tree_model_->GetRoot(); - for (int i = 0; i < root->child_count(); ++i) { - const CookieTreeNode* site = root->GetChild(i); - const base::string16& title = site->GetTitle(); - if (!base::EndsWith(title, etld_plus1, - base::CompareCase::INSENSITIVE_ASCII)) { - continue; - } - - for (int j = 0; j < site->child_count(); ++j) { - const CookieTreeNode* category = site->GetChild(j); - if (category->GetDetailedInfo().node_type != - CookieTreeNode::DetailedInfo::TYPE_COOKIES) { - continue; - } - - for (int k = 0; k < category->child_count(); ++k) { - if (category->GetChild(k)->GetDetailedInfo().node_type != - CookieTreeNode::DetailedInfo::TYPE_COOKIE) { - continue; - } - - ++num_cookies; - } - } - } - - base::Value cookies_per_etld_plus1(base::Value::Type::DICTIONARY); - cookies_per_etld_plus1.SetKey(kEffectiveTopLevelDomainPlus1Name, - base::Value(etld_plus1)); - cookies_per_etld_plus1.SetKey(kNumCookies, base::Value(num_cookies)); - result.GetList().emplace_back(std::move(cookies_per_etld_plus1)); - } - ResolveJavascriptCallback(base::Value(callback_id), result); - - // Restore the original |filter_|. - cookies_tree_model_->UpdateSearchResults(filter_); -} - void CookiesViewHandler::HandleGetNumCookiesString( const base::ListValue* args) { CHECK_EQ(2U, args->GetSize()); @@ -492,7 +382,7 @@ void CookiesViewHandler::SendLocalDataList(const CookieTreeNode* parent) { // The layers in the CookieTree are: // root - Top level. // site - www.google.com, example.com, etc. - // category - Cookies, Channel ID, Local Storage, etc. + // category - Cookies, Local Storage, etc. // item - Info on the actual thing. // Gather list of sites with some highlights of the categories and items. std::unique_ptr<base::ListValue> site_list(new base::ListValue); diff --git a/chromium/chrome/browser/ui/webui/settings/settings_cookies_view_handler.h b/chromium/chrome/browser/ui/webui/settings/settings_cookies_view_handler.h index bba06ea179a..d8debac00fa 100644 --- a/chromium/chrome/browser/ui/webui/settings/settings_cookies_view_handler.h +++ b/chromium/chrome/browser/ui/webui/settings/settings_cookies_view_handler.h @@ -61,11 +61,6 @@ class CookiesViewHandler : public SettingsPageUIHandler, // Retrieve cookie details for a specific site. void HandleGetCookieDetails(const base::ListValue* args); - // Gets a list containing the number of cookies for each domain (eTLD+1 names) - // given in |siteList|. This will always return a result array the same length - // and in the same order as |siteList|. - void HandleGetNumCookiesList(const base::ListValue* args); - // Gets a plural string for the given number of cookies. void HandleGetNumCookiesString(const base::ListValue* args); diff --git a/chromium/chrome/browser/ui/webui/settings/settings_import_data_handler.cc b/chromium/chrome/browser/ui/webui/settings/settings_import_data_handler.cc index 32deebd14fb..f546887fdfc 100644 --- a/chromium/chrome/browser/ui/webui/settings/settings_import_data_handler.cc +++ b/chromium/chrome/browser/ui/webui/settings/settings_import_data_handler.cc @@ -209,10 +209,9 @@ void ImportDataHandler::ImportEnded() { importer_host_->set_observer(NULL); importer_host_ = NULL; - CallJavascriptFunction( - "cr.webUIListenerCallback", base::Value("import-data-status-changed"), - base::Value(import_did_succeed_ ? kImportStatusSucceeded - : kImportStatusFailed)); + FireWebUIListener("import-data-status-changed", + base::Value(import_did_succeed_ ? kImportStatusSucceeded + : kImportStatusFailed)); } void ImportDataHandler::FileSelected(const base::FilePath& path, diff --git a/chromium/chrome/browser/ui/webui/settings/settings_media_devices_selection_handler.cc b/chromium/chrome/browser/ui/webui/settings/settings_media_devices_selection_handler.cc index 9c91e087592..42d27c5dd19 100644 --- a/chromium/chrome/browser/ui/webui/settings/settings_media_devices_selection_handler.cc +++ b/chromium/chrome/browser/ui/webui/settings/settings_media_devices_selection_handler.cc @@ -59,12 +59,12 @@ void MediaDevicesSelectionHandler::RegisterMessages() { } void MediaDevicesSelectionHandler::OnUpdateAudioDevices( - const content::MediaStreamDevices& devices) { + const blink::MediaStreamDevices& devices) { UpdateDevicesMenu(AUDIO, devices); } void MediaDevicesSelectionHandler::OnUpdateVideoDevices( - const content::MediaStreamDevices& devices) { + const blink::MediaStreamDevices& devices) { UpdateDevicesMenu(VIDEO, devices); } @@ -106,7 +106,8 @@ void MediaDevicesSelectionHandler::SetDefaultCaptureDevice( } void MediaDevicesSelectionHandler::UpdateDevicesMenu( - DeviceType type, const content::MediaStreamDevices& devices) { + DeviceType type, + const blink::MediaStreamDevices& devices) { AllowJavascript(); // Get the default device unique id from prefs. @@ -148,7 +149,7 @@ void MediaDevicesSelectionHandler::UpdateDevicesMenu( } std::string MediaDevicesSelectionHandler::GetDeviceDisplayName( - const content::MediaStreamDevice& device) const { + const blink::MediaStreamDevice& device) const { std::string facing_info; #if BUILDFLAG(ENABLE_EXTENSIONS) @@ -173,7 +174,7 @@ std::string MediaDevicesSelectionHandler::GetDeviceDisplayName( } void MediaDevicesSelectionHandler::UpdateDevicesMenuForType(DeviceType type) { - content::MediaStreamDevices devices; + blink::MediaStreamDevices devices; switch (type) { case AUDIO: devices = MediaCaptureDevicesDispatcher::GetInstance()-> diff --git a/chromium/chrome/browser/ui/webui/settings/settings_media_devices_selection_handler.h b/chromium/chrome/browser/ui/webui/settings/settings_media_devices_selection_handler.h index 9d0863b955a..bbf9313859e 100644 --- a/chromium/chrome/browser/ui/webui/settings/settings_media_devices_selection_handler.h +++ b/chromium/chrome/browser/ui/webui/settings/settings_media_devices_selection_handler.h @@ -27,10 +27,8 @@ class MediaDevicesSelectionHandler void RegisterMessages() override; // MediaCaptureDevicesDispatcher::Observer: - void OnUpdateAudioDevices( - const content::MediaStreamDevices& devices) override; - void OnUpdateVideoDevices( - const content::MediaStreamDevices& devices) override; + void OnUpdateAudioDevices(const blink::MediaStreamDevices& devices) override; + void OnUpdateVideoDevices(const blink::MediaStreamDevices& devices) override; private: enum DeviceType { @@ -49,11 +47,11 @@ class MediaDevicesSelectionHandler // Helpers methods to update the device menus. void UpdateDevicesMenuForType(DeviceType type); void UpdateDevicesMenu(DeviceType type, - const content::MediaStreamDevices& devices); + const blink::MediaStreamDevices& devices); // Gets the human readable name of the device. std::string GetDeviceDisplayName( - const content::MediaStreamDevice& device) const; + const blink::MediaStreamDevice& device) const; Profile* profile_; // Weak pointer. diff --git a/chromium/chrome/browser/ui/webui/settings/site_settings_handler.cc b/chromium/chrome/browser/ui/webui/settings/site_settings_handler.cc index bf646ef3d11..9e0d11e641c 100644 --- a/chromium/chrome/browser/ui/webui/settings/site_settings_handler.cc +++ b/chromium/chrome/browser/ui/webui/settings/site_settings_handler.cc @@ -5,17 +5,16 @@ #include "chrome/browser/ui/webui/settings/site_settings_handler.h" #include <algorithm> -#include <map> -#include <memory> -#include <set> -#include <string> #include <utility> +#include <vector> #include "base/barrier_closure.h" #include "base/bind.h" #include "base/i18n/number_formatting.h" #include "base/macros.h" #include "base/metrics/user_metrics.h" +#include "base/stl_util.h" +#include "base/strings/utf_string_conversions.h" #include "base/values.h" #include "chrome/browser/chrome_notification_types.h" #include "chrome/browser/content_settings/host_content_settings_map_factory.h" @@ -34,6 +33,8 @@ #include "chrome/browser/ui/page_info/page_info_infobar_delegate.h" #include "chrome/browser/ui/tabs/tab_strip_model.h" #include "chrome/browser/ui/webui/site_settings_helper.h" +#include "chrome/browser/usb/usb_chooser_context.h" +#include "chrome/browser/usb/usb_chooser_context_factory.h" #include "chrome/common/extensions/manifest_handlers/app_launch_info.h" #include "chrome/common/pref_names.h" #include "chrome/grit/generated_resources.h" @@ -54,8 +55,6 @@ #include "extensions/browser/extension_registry.h" #include "extensions/common/permissions/api_permission.h" #include "extensions/common/permissions/permissions_data.h" -#include "storage/browser/quota/quota_manager.h" -#include "third_party/blink/public/mojom/quota/quota_types.mojom.h" #include "ui/base/l10n/l10n_util.h" #include "ui/base/text/bytes_formatting.h" @@ -74,6 +73,7 @@ constexpr char kReasonKey[] = "reason"; constexpr char kEffectiveTopLevelDomainPlus1Name[] = "etldPlus1"; constexpr char kOriginList[] = "origins"; constexpr char kNumCookies[] = "numCookies"; +constexpr char kHasPermissionSettings[] = "hasPermissionSettings"; constexpr char kZoom[] = "zoom"; // Return an appropriate API Permission ID for the given string name. @@ -142,7 +142,7 @@ bool PatternAppliesToSingleOrigin(const ContentSettingPatternSource& pattern) { // Groups |url| into sets of eTLD+1s in |site_group_map|, assuming |url| is an // origin. -void CreateOrAppendSiteGroupEntry( +void CreateOrAppendSiteGroupEntryForUrl( std::map<std::string, std::set<std::string>>* site_group_map, const GURL& url) { std::string etld_plus1_string = @@ -152,15 +152,72 @@ void CreateOrAppendSiteGroupEntry( if (entry == site_group_map->end()) { site_group_map->emplace(etld_plus1_string, std::set<std::string>({url.spec()})); - } else { - entry->second.insert(url.spec()); + return; } + entry->second.insert(url.spec()); +} + +// Update the storage data in |origin_size_map|. +void UpdateDataForOrigin(const GURL& url, + const int size, + std::map<std::string, int>* origin_size_map) { + if (size > 0) + (*origin_size_map)[url.spec()] += size; +} + +// Groups |host| into sets of eTLD+1s in |site_group_map|, |host| can either +// be an eTLD+1 or an origin. +// There are three cases: +// 1. The ETLD+1 of |host| is not yet in |site_group_map|. We add the ETLD+1 +// to |site_group_map| +// 2. The ETLD+1 of |host| is in |site_group_map|, and is equal to |host|. +// This means case 1 has already happened and nothing more needs to be +// done. +// 3. The ETLD+1 of |host| is in |site_group_map| and is different to |host|. +// In case 3, we try to add |host| to the set of origins for the ETLD+1. +// This requires adding a scheme. We initially check if a HTTPS scheme has +// been added for the host, and fall back to HTTP if not. +void CreateOrAppendSiteGroupEntryForCookieHost( + const std::string& host, + std::map<std::string, std::set<std::string>>* site_group_map) { + std::string etld_plus1_string = + net::registry_controlled_domains::GetDomainAndRegistry( + host, net::registry_controlled_domains::INCLUDE_PRIVATE_REGISTRIES); + auto entry = site_group_map->find(etld_plus1_string); + if (entry == site_group_map->end()) { + site_group_map->emplace( + etld_plus1_string, + // Add etld+1 origin as place holder. + std::set<std::string>({std::string(url::kHttpScheme) + + url::kStandardSchemeSeparator + host + "/"})); + return; + } + // If |host| equals to etld_plus1_string that is already exists in + // |site_group_map|, nothing need to be done. + if (host == etld_plus1_string) + return; + // Cookies ignore schemes, so try and see if a https schemed version + // already exists in the origin list, if not, then add the http schemed + // version into the map. + std::string https_url = std::string(url::kHttpsScheme) + + url::kStandardSchemeSeparator + host + "/"; + if (entry->second.find(https_url) != entry->second.end()) + return; + entry->second.insert(std::string(url::kHttpScheme) + + url::kStandardSchemeSeparator + host + "/"); + // Check if we have an etld_plus1 url place holder, if there is, delete + // that entry. + std::string etld_plus1_url = std::string(url::kHttpScheme) + + url::kStandardSchemeSeparator + + etld_plus1_string + "/"; + entry->second.erase(etld_plus1_url); } // Converts a given |site_group_map| to a list of base::DictionaryValues, adding // the site engagement score for each origin. void ConvertSiteGroupMapToListValue( const std::map<std::string, std::set<std::string>>& site_group_map, + const std::set<std::string>& origin_permission_set, base::Value* list_value, Profile* profile) { DCHECK_EQ(base::Value::Type::LIST, list_value->type()); @@ -180,6 +237,10 @@ void ConvertSiteGroupMapToListValue( "engagement", base::Value(engagement_service->GetScore(GURL(origin)))); origin_object.SetKey("usage", base::Value(0)); + origin_object.SetKey(kNumCookies, base::Value(0)); + origin_object.SetKey( + kHasPermissionSettings, + base::Value(base::ContainsKey(origin_permission_set, origin))); origin_list.GetList().emplace_back(std::move(origin_object)); } site_group.SetKey(kNumCookies, base::Value(0)); @@ -222,18 +283,30 @@ bool IsPatternValidForType(const std::string& pattern_string, return true; } +void UpdateDataFromCookiesTree( + std::map<std::string, std::set<std::string>>* all_sites_map, + std::map<std::string, int>* origin_size_map, + const GURL& origin, + int64_t size) { + UpdateDataForOrigin(origin, size, origin_size_map); + CreateOrAppendSiteGroupEntryForUrl(all_sites_map, origin); +} + } // namespace SiteSettingsHandler::SiteSettingsHandler(Profile* profile) : profile_(profile), observer_(this), - pref_change_registrar_(nullptr), - local_storage_helper_(nullptr) {} + chooser_observer_(this), + pref_change_registrar_(nullptr) {} SiteSettingsHandler::~SiteSettingsHandler() { + if (cookies_tree_model_) + cookies_tree_model_->RemoveCookiesTreeObserver(this); } void SiteSettingsHandler::RegisterMessages() { + web_ui()->RegisterMessageCallback( "fetchUsageTotal", base::BindRepeating(&SiteSettingsHandler::HandleFetchUsageTotal, @@ -272,6 +345,10 @@ void SiteSettingsHandler::RegisterMessages() { base::BindRepeating(&SiteSettingsHandler::HandleGetExceptionList, base::Unretained(this))); web_ui()->RegisterMessageCallback( + "getChooserExceptionList", + base::BindRepeating(&SiteSettingsHandler::HandleGetChooserExceptionList, + base::Unretained(this))); + web_ui()->RegisterMessageCallback( "getOriginPermissions", base::BindRepeating(&SiteSettingsHandler::HandleGetOriginPermissions, base::Unretained(this))); @@ -294,6 +371,11 @@ void SiteSettingsHandler::RegisterMessages() { &SiteSettingsHandler::HandleSetCategoryPermissionForPattern, base::Unretained(this))); web_ui()->RegisterMessageCallback( + "resetChooserExceptionForSite", + base::BindRepeating( + &SiteSettingsHandler::HandleResetChooserExceptionForSite, + base::Unretained(this))); + web_ui()->RegisterMessageCallback( "isOriginValid", base::BindRepeating(&SiteSettingsHandler::HandleIsOriginValid, base::Unretained(this))); @@ -321,16 +403,15 @@ void SiteSettingsHandler::RegisterMessages() { "fetchBlockAutoplayStatus", base::BindRepeating(&SiteSettingsHandler::HandleFetchBlockAutoplayStatus, base::Unretained(this))); + web_ui()->RegisterMessageCallback( + "clearEtldPlus1DataAndCookies", + base::BindRepeating( + &SiteSettingsHandler::HandleClearEtldPlus1DataAndCookies, + base::Unretained(this))); } void SiteSettingsHandler::OnJavascriptAllowed() { - observer_.Add(HostContentSettingsMapFactory::GetForProfile(profile_)); - if (profile_->HasOffTheRecordProfile()) { - auto* map = HostContentSettingsMapFactory::GetForProfile( - profile_->GetOffTheRecordProfile()); - if (!observer_.IsObserving(map)) - observer_.Add(map); - } + ObserveSources(); notification_registrar_.Add( this, chrome::NOTIFICATION_PROFILE_CREATED, @@ -368,6 +449,7 @@ void SiteSettingsHandler::OnJavascriptAllowed() { void SiteSettingsHandler::OnJavascriptDisallowed() { observer_.RemoveAll(); + chooser_observer_.RemoveAll(); notification_registrar_.RemoveAll(); host_zoom_map_subscription_.reset(); pref_change_registrar_->Remove(prefs::kBlockAutoplayEnabled); @@ -376,38 +458,26 @@ void SiteSettingsHandler::OnJavascriptDisallowed() { #endif } -void SiteSettingsHandler::OnGetUsageInfo( - const storage::UsageInfoEntries& entries) { +void SiteSettingsHandler::OnGetUsageInfo() { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); - - for (const auto& entry : entries) { - if (entry.usage <= 0) continue; - if (entry.host == usage_host_) { - CallJavascriptFunction("settings.WebsiteUsagePrivateApi.returnUsageTotal", - base::Value(entry.host), - base::Value(ui::FormatBytes(entry.usage)), - base::Value(static_cast<int>(entry.type))); + // Site Details Page does not display the number of cookies for the origin. + const CookieTreeNode* root = cookies_tree_model_->GetRoot(); + for (int i = 0; i < root->child_count(); ++i) { + const CookieTreeNode* site = root->GetChild(i); + std::string title = base::UTF16ToUTF8(site->GetTitle()); + if (title == usage_host_) { + CallJavascriptFunction( + "settings.WebsiteUsagePrivateApi.returnUsageTotal", + base::Value(usage_host_), + base::Value(ui::FormatBytes(site->InclusiveSize()))); return; } } } -void SiteSettingsHandler::OnStorageCleared(base::OnceClosure callback, - blink::mojom::QuotaStatusCode code) { - if (code == blink::mojom::QuotaStatusCode::kOk) { - std::move(callback).Run(); - } -} - -void SiteSettingsHandler::OnUsageCleared() { - CallJavascriptFunction("settings.WebsiteUsagePrivateApi.onUsageCleared", - base::Value(clearing_origin_)); -} - #if defined(OS_CHROMEOS) void SiteSettingsHandler::OnPrefEnableDrmChanged() { - CallJavascriptFunction("cr.webUIListenerCallback", - base::Value("prefEnableDrmChanged")); + FireWebUIListener("prefEnableDrmChanged"); } #endif @@ -420,15 +490,12 @@ void SiteSettingsHandler::OnContentSettingChanged( return; if (primary_pattern.ToString().empty()) { - CallJavascriptFunction( - "cr.webUIListenerCallback", - base::Value("contentSettingCategoryChanged"), - base::Value( - site_settings::ContentSettingsTypeToGroupName(content_type))); + FireWebUIListener("contentSettingCategoryChanged", + base::Value(site_settings::ContentSettingsTypeToGroupName( + content_type))); } else { - CallJavascriptFunction( - "cr.webUIListenerCallback", - base::Value("contentSettingSitePermissionChanged"), + FireWebUIListener( + "contentSettingSitePermissionChanged", base::Value( site_settings::ContentSettingsTypeToGroupName(content_type)), base::Value(primary_pattern.ToString()), @@ -479,6 +546,21 @@ void SiteSettingsHandler::Observe( } } +void SiteSettingsHandler::OnChooserObjectPermissionChanged( + ContentSettingsType guard_content_settings_type, + ContentSettingsType data_content_settings_type) { + if (!site_settings::HasRegisteredGroupName(guard_content_settings_type) || + !site_settings::HasRegisteredGroupName(data_content_settings_type)) { + return; + } + + FireWebUIListener("contentSettingChooserPermissionChanged", + base::Value(site_settings::ContentSettingsTypeToGroupName( + guard_content_settings_type)), + base::Value(site_settings::ContentSettingsTypeToGroupName( + data_content_settings_type))); +} + void SiteSettingsHandler::OnZoomLevelChanged( const content::HostZoomMap::ZoomLevelChange& change) { SendZoomLevels(); @@ -487,47 +569,37 @@ void SiteSettingsHandler::OnZoomLevelChanged( void SiteSettingsHandler::HandleFetchUsageTotal( const base::ListValue* args) { AllowJavascript(); - CHECK_EQ(1U, args->GetSize()); std::string host; CHECK(args->GetString(0, &host)); usage_host_ = host; - scoped_refptr<StorageInfoFetcher> storage_info_fetcher - = new StorageInfoFetcher(profile_); - storage_info_fetcher->FetchStorageInfo( - base::Bind(&SiteSettingsHandler::OnGetUsageInfo, base::Unretained(this))); + update_site_details_ = true; + + if (cookies_tree_model_ && !send_sites_list_) { + cookies_tree_model_->RemoveCookiesTreeObserver(this); + cookies_tree_model_.reset(); + } + EnsureCookiesTreeModelCreated(/*omit_cookies=*/true); } void SiteSettingsHandler::HandleClearUsage( const base::ListValue* args) { - CHECK_EQ(2U, args->GetSize()); + CHECK_EQ(1U, args->GetSize()); std::string origin; CHECK(args->GetString(0, &origin)); - double storage_type; - CHECK(args->GetDouble(1, &storage_type)); GURL url(origin); - if (url.is_valid()) { - clearing_origin_ = origin; - - // Call OnUsageCleared when StorageInfoFetcher::ClearStorage and - // BrowsingDataLocalStorageHelper::DeleteOrigin are done. - base::RepeatingClosure barrier = base::BarrierClosure( - 2, base::BindOnce(&SiteSettingsHandler::OnUsageCleared, - base::Unretained(this))); - - // Start by clearing the storage data asynchronously. - scoped_refptr<StorageInfoFetcher> storage_info_fetcher - = new StorageInfoFetcher(profile_); - storage_info_fetcher->ClearStorage( - url.host(), - static_cast<blink::mojom::StorageType>(static_cast<int>(storage_type)), - base::BindRepeating(&SiteSettingsHandler::OnStorageCleared, - base::Unretained(this), barrier)); - - // Also clear the *local* storage data. - GetLocalStorageHelper()->DeleteOrigin(url, barrier); + if (!url.is_valid()) + return; + AllowJavascript(); + CookieTreeNode* parent = cookies_tree_model_->GetRoot(); + for (int i = 0; i < parent->child_count(); ++i) { + CookieTreeNode* node = parent->GetChild(i); + if (origin == node->GetDetailedInfo().origin.GetURL().spec()) { + cookies_tree_model_->DeleteCookieNode(node); + return; + } } } @@ -539,8 +611,10 @@ void SiteSettingsHandler::HandleFetchUsbDevices(const base::ListValue* args) { CHECK(args->Get(0, &callback_id)); base::ListValue exceptions; + const std::string group_name = site_settings::ContentSettingsTypeToGroupName( + CONTENT_SETTINGS_TYPE_USB_CHOOSER_DATA); const site_settings::ChooserTypeNameEntry* chooser_type = - site_settings::ChooserTypeFromGroupName(site_settings::kGroupTypeUsb); + site_settings::ChooserTypeFromGroupName(group_name); // TODO(finnur): Figure out whether incognito permissions are also needed. site_settings::GetChooserExceptionsFromProfile( profile_, false, *chooser_type, &exceptions); @@ -563,8 +637,10 @@ void SiteSettingsHandler::HandleRemoveUsbDevice(const base::ListValue* args) { const base::DictionaryValue* object = nullptr; CHECK(args->GetDictionary(2, &object)); + const std::string group_name = site_settings::ContentSettingsTypeToGroupName( + CONTENT_SETTINGS_TYPE_USB_CHOOSER_DATA); const site_settings::ChooserTypeNameEntry* chooser_type = - site_settings::ChooserTypeFromGroupName(site_settings::kGroupTypeUsb); + site_settings::ChooserTypeFromGroupName(group_name); ChooserContextBase* chooser_context = chooser_type->get_context(profile_); chooser_context->RevokeObjectPermission(requesting_origin, embedding_origin, *object); @@ -636,6 +712,9 @@ void SiteSettingsHandler::HandleGetAllSites(const base::ListValue* args) { const base::ListValue* types; CHECK(args->GetList(1, &types)); + all_sites_map_.clear(); + origin_permission_set_.clear(); + // Convert |types| to a list of ContentSettingsTypes. std::vector<ContentSettingsType> content_types; for (size_t i = 0; i < types->GetSize(); ++i) { @@ -655,14 +734,6 @@ void SiteSettingsHandler::HandleGetAllSites(const base::ListValue* args) { DCHECK(profile); HostContentSettingsMap* map = HostContentSettingsMapFactory::GetForProfile(profile); - std::map<std::string, std::set<std::string>> all_sites_map; - - // TODO(https://crbug.com/835712): Assess performance of this method for - // unusually large numbers of stored content settings. - - // Add sites that are using any local storage to the list. - GetLocalStorageHelper()->StartFetching(base::BindRepeating( - &SiteSettingsHandler::OnLocalStorageFetched, base::Unretained(this))); // Retrieve a list of embargoed settings to check separately. This ensures // that only settings included in |content_types| will be listed in all sites. @@ -679,7 +750,8 @@ void SiteSettingsHandler::HandleGetAllSites(const base::ListValue* args) { permission_manager->GetPermissionStatus(content_type, url, url); if (result.source == PermissionStatusSource::MULTIPLE_DISMISSALS || result.source == PermissionStatusSource::MULTIPLE_IGNORES) { - CreateOrAppendSiteGroupEntry(&all_sites_map, url); + CreateOrAppendSiteGroupEntryForUrl(&all_sites_map_, url); + origin_permission_set_.insert(url.spec()); break; } } @@ -691,44 +763,81 @@ void SiteSettingsHandler::HandleGetAllSites(const base::ListValue* args) { ContentSettingsForOneType entries; map->GetSettingsForOneType(content_type, std::string(), &entries); for (const ContentSettingPatternSource& e : entries) { - if (PatternAppliesToSingleOrigin(e)) - CreateOrAppendSiteGroupEntry(&all_sites_map, - GURL(e.primary_pattern.ToString())); + if (PatternAppliesToSingleOrigin(e)) { + CreateOrAppendSiteGroupEntryForUrl(&all_sites_map_, + GURL(e.primary_pattern.ToString())); + origin_permission_set_.insert( + GURL(e.primary_pattern.ToString()).spec()); + } } } + // Recreate the cookies tree model to refresh the usage information. + // This happens in the background and will call TreeModelEndBatch() when + // finished. At that point we send usage data to the page. + if (cookies_tree_model_) + cookies_tree_model_->RemoveCookiesTreeObserver(this); + cookies_tree_model_.reset(); + EnsureCookiesTreeModelCreated(); + base::Value result(base::Value::Type::LIST); - ConvertSiteGroupMapToListValue(all_sites_map, &result, profile); + + // Respond with currently available data. + ConvertSiteGroupMapToListValue(all_sites_map_, origin_permission_set_, + &result, profile); + + send_sites_list_ = true; + ResolveJavascriptCallback(*callback_id, result); } -void SiteSettingsHandler::OnLocalStorageFetched( - const std::list<BrowsingDataLocalStorageHelper::LocalStorageInfo>& - local_storage_info) { +base::Value SiteSettingsHandler::PopulateCookiesAndUsageData(Profile* profile) { std::map<std::string, int> origin_size_map; - std::map<std::string, std::set<std::string>> all_sites_map; - for (const BrowsingDataLocalStorageHelper::LocalStorageInfo& info : - local_storage_info) { - origin_size_map.emplace(info.origin_url.spec(), info.size); - CreateOrAppendSiteGroupEntry(&all_sites_map, info.origin_url); - } - base::Value result(base::Value::Type::LIST); - ConvertSiteGroupMapToListValue(all_sites_map, &result, profile_); - - // Merge the origin usage number into |result|. - for (size_t i = 0; i < result.GetList().size(); ++i) { - base::Value* site_group = &result.GetList()[i]; - base::Value* origin_list = site_group->FindKey(kOriginList); - - for (size_t i = 0; i < origin_list->GetList().size(); ++i) { - base::Value* origin_info = &origin_list->GetList()[i]; - const std::string& origin = origin_info->FindKey("origin")->GetString(); - const auto& size_info = origin_size_map.find(origin); - if (size_info != origin_size_map.end()) - origin_info->SetKey("usage", base::Value(size_info->second)); + std::map<std::string, int> origin_cookie_map; + base::Value list_value(base::Value::Type::LIST); + + GetOriginStorage(&all_sites_map_, &origin_size_map); + GetOriginCookies(&all_sites_map_, &origin_cookie_map); + ConvertSiteGroupMapToListValue(all_sites_map_, origin_permission_set_, + &list_value, profile); + + // Merge the origin usage and cookies number into |list_value|. + for (base::Value& site_group : list_value.GetList()) { + base::Value* origin_list = site_group.FindKey(kOriginList); + int cookie_num = 0; + + const std::string& etld_plus1 = + site_group.FindKey(kEffectiveTopLevelDomainPlus1Name)->GetString(); + const auto& etld_plus1_cookie_num_it = origin_cookie_map.find(etld_plus1); + // Add the number of eTLD+1 scoped cookies. + if (etld_plus1_cookie_num_it != origin_cookie_map.end()) + cookie_num = etld_plus1_cookie_num_it->second; + // Iterate over the origins for the ETLD+1, and set their usage and cookie + // numbers. + for (base::Value& origin_info : origin_list->GetList()) { + const std::string& origin = origin_info.FindKey("origin")->GetString(); + const auto& size_info_it = origin_size_map.find(origin); + if (size_info_it != origin_size_map.end()) + origin_info.SetKey("usage", base::Value(size_info_it->second)); + const auto& origin_cookie_num_it = + origin_cookie_map.find(GURL(origin).host()); + // Add cookies numbers for origins that isn't an eTLD+1. + if (GURL(origin).host() != etld_plus1 && + origin_cookie_num_it != origin_cookie_map.end()) { + origin_info.SetKey(kNumCookies, + base::Value(origin_cookie_num_it->second)); + cookie_num += origin_cookie_num_it->second; + } } + site_group.SetKey(kNumCookies, base::Value(cookie_num)); } - FireWebUIListener("onLocalStorageListFetched", result); + return list_value; +} + +void SiteSettingsHandler::OnStorageFetched() { + AllowJavascript(); + FireWebUIListener("onStorageListFetched", + PopulateCookiesAndUsageData(profile_)); } void SiteSettingsHandler::HandleGetFormattedBytes(const base::ListValue* args) { @@ -782,6 +891,26 @@ void SiteSettingsHandler::HandleGetExceptionList(const base::ListValue* args) { ResolveJavascriptCallback(*callback_id, *exceptions.get()); } +void SiteSettingsHandler::HandleGetChooserExceptionList( + const base::ListValue* args) { + AllowJavascript(); + + CHECK_EQ(2U, args->GetSize()); + const base::Value* callback_id; + CHECK(args->Get(0, &callback_id)); + std::string type; + CHECK(args->GetString(1, &type)); + const site_settings::ChooserTypeNameEntry* chooser_type = + site_settings::ChooserTypeFromGroupName(type); + CHECK(chooser_type); + + std::unique_ptr<base::ListValue> exceptions = + site_settings::GetChooserExceptionListFromProfile(profile_, + /*incognito=*/false, + *chooser_type); + ResolveJavascriptCallback(*callback_id, *exceptions.get()); +} + void SiteSettingsHandler::HandleGetOriginPermissions( const base::ListValue* args) { AllowJavascript(); @@ -1029,6 +1158,36 @@ void SiteSettingsHandler::HandleSetCategoryPermissionForPattern( WebSiteSettingsUmaUtil::LogPermissionChange(content_type, setting); } +void SiteSettingsHandler::HandleResetChooserExceptionForSite( + const base::ListValue* args) { + CHECK_EQ(4U, args->GetSize()); + + std::string chooser_type_str; + CHECK(args->GetString(0, &chooser_type_str)); + const site_settings::ChooserTypeNameEntry* chooser_type = + site_settings::ChooserTypeFromGroupName(chooser_type_str); + CHECK(chooser_type); + + std::string origin_str; + CHECK(args->GetString(1, &origin_str)); + GURL requesting_origin(origin_str); + CHECK(requesting_origin.is_valid()); + + // An empty embedding origin means that the user exception object was granted + // for any embedding origin. + std::string embedding_origin_str; + CHECK(args->GetString(2, &embedding_origin_str)); + GURL embedding_origin(embedding_origin_str); + CHECK(embedding_origin.is_valid() || embedding_origin.is_empty()); + + const base::DictionaryValue* object = nullptr; + CHECK(args->GetDictionary(3, &object)); + + ChooserContextBase* chooser_context = chooser_type->get_context(profile_); + chooser_context->RevokeObjectPermission(requesting_origin, embedding_origin, + *object); +} + void SiteSettingsHandler::HandleIsOriginValid(const base::ListValue* args) { AllowJavascript(); CHECK_EQ(2U, args->GetSize()); @@ -1206,9 +1365,10 @@ void SiteSettingsHandler::SendBlockAutoplayStatus() { status.SetKey("pref", std::move(pref)); // Whether the block autoplay toggle should be enabled. - status.SetKey("enabled", - base::Value(UnifiedAutoplayConfig::IsBlockAutoplayUserModifiable( - profile_))); + status.SetKey( + "enabled", + base::Value( + UnifiedAutoplayConfig::IsBlockAutoplayUserModifiable(profile_))); FireWebUIListener("onBlockAutoplayStatusChanged", status); } @@ -1227,16 +1387,129 @@ void SiteSettingsHandler::HandleSetBlockAutoplayEnabled( profile_->GetPrefs()->SetBoolean(prefs::kBlockAutoplayEnabled, value); } -void SiteSettingsHandler::SetBrowsingDataLocalStorageHelperForTesting( - scoped_refptr<BrowsingDataLocalStorageHelper> helper) { - DCHECK(!local_storage_helper_); - local_storage_helper_ = helper; +void SiteSettingsHandler::EnsureCookiesTreeModelCreated(bool omit_cookies) { + if (cookies_tree_model_) + return; + cookies_tree_model_ = + CookiesTreeModel::CreateForProfile(profile_, omit_cookies); + cookies_tree_model_->AddCookiesTreeObserver(this); } -BrowsingDataLocalStorageHelper* SiteSettingsHandler::GetLocalStorageHelper() { - if (!local_storage_helper_) - local_storage_helper_ = new BrowsingDataLocalStorageHelper(profile_); - return local_storage_helper_.get(); +void SiteSettingsHandler::ObserveSources() { + observer_.Add(HostContentSettingsMapFactory::GetForProfile(profile_)); + chooser_observer_.Add(UsbChooserContextFactory::GetForProfile(profile_)); + + if (!profile_->HasOffTheRecordProfile()) + return; + + // At the moment, off the record chooser permissions are not included in the + // chooser permissions. + // TODO(https://crbug.com/927372): When chooser permissions are included, + // attach SiteSettingsHandler as an observer to the chooser contexts. + auto* map = HostContentSettingsMapFactory::GetForProfile( + profile_->GetOffTheRecordProfile()); + if (!observer_.IsObserving(map)) + observer_.Add(map); +} + +void SiteSettingsHandler::TreeNodesAdded(ui::TreeModel* model, + ui::TreeModelNode* parent, + int start, + int count) {} + +void SiteSettingsHandler::TreeNodesRemoved(ui::TreeModel* model, + ui::TreeModelNode* parent, + int start, + int count) {} + +void SiteSettingsHandler::TreeNodeChanged(ui::TreeModel* model, + ui::TreeModelNode* node) {} + +void SiteSettingsHandler::TreeModelEndBatch(CookiesTreeModel* model) { + // The WebUI may have shut down before we get the data. + if (!IsJavascriptAllowed()) + return; + if (send_sites_list_) + OnStorageFetched(); + if (update_site_details_) + OnGetUsageInfo(); + send_sites_list_ = false; + update_site_details_ = false; +} + +void SiteSettingsHandler::GetOriginStorage( + std::map<std::string, std::set<std::string>>* all_sites_map, + std::map<std::string, int>* origin_size_map) { + CHECK(cookies_tree_model_.get()); + + const CookieTreeNode* root = cookies_tree_model_->GetRoot(); + for (int i = 0; i < root->child_count(); ++i) { + const CookieTreeNode* site = root->GetChild(i); + int64_t size = site->InclusiveSize(); + if (size == 0) + continue; + UpdateDataFromCookiesTree(all_sites_map, origin_size_map, + site->GetDetailedInfo().origin.GetURL(), size); + } +} + +void SiteSettingsHandler::GetOriginCookies( + std::map<std::string, std::set<std::string>>* all_sites_map, + std::map<std::string, int>* origin_cookie_map) { + CHECK(cookies_tree_model_.get()); + // Get sites that don't have data but have cookies. + const CookieTreeNode* root = cookies_tree_model_->GetRoot(); + for (int i = 0; i < root->child_count(); ++i) { + const CookieTreeNode* site = root->GetChild(i); + std::string title = base::UTF16ToUTF8(site->GetTitle()); + for (int j = 0; j < site->child_count(); ++j) { + const CookieTreeNode* category = site->GetChild(j); + if (category->GetDetailedInfo().node_type != + CookieTreeNode::DetailedInfo::TYPE_COOKIES) + continue; + for (int k = 0; k < category->child_count(); ++k) { + const CookieTreeNode::DetailedInfo& detailedInfo = + category->GetChild(k)->GetDetailedInfo(); + if (detailedInfo.node_type != CookieTreeNode::DetailedInfo::TYPE_COOKIE) + continue; + (*origin_cookie_map)[title] += 1; + CreateOrAppendSiteGroupEntryForCookieHost(title, all_sites_map); + } + } + } +} + +void SiteSettingsHandler::HandleClearEtldPlus1DataAndCookies( + const base::ListValue* args) { + CHECK_EQ(1U, args->GetSize()); + std::string etld_plus1_string; + CHECK(args->GetString(0, &etld_plus1_string)); + + AllowJavascript(); + CookieTreeNode* parent = cookies_tree_model_->GetRoot(); + + // Find all the nodes that contain the given etld+1. + std::vector<CookieTreeNode*> nodes_to_delete; + for (int i = 0; i < parent->child_count(); ++i) { + CookieTreeNode* node = parent->GetChild(i); + std::string cookie_node_etld_plus1 = + net::registry_controlled_domains::GetDomainAndRegistry( + base::UTF16ToUTF8(node->GetTitle()), + net::registry_controlled_domains::INCLUDE_PRIVATE_REGISTRIES); + if (etld_plus1_string == cookie_node_etld_plus1) + nodes_to_delete.push_back(node); + } + for (auto* node : nodes_to_delete) { + cookies_tree_model_->DeleteCookieNode(node); + } +} + +void SiteSettingsHandler::SetCookiesTreeModelForTesting( + std::unique_ptr<CookiesTreeModel> cookies_tree_model) { + cookies_tree_model_ = std::move(cookies_tree_model); } +void SiteSettingsHandler::ClearAllSitesMapForTesting() { + all_sites_map_.clear(); +} } // namespace settings diff --git a/chromium/chrome/browser/ui/webui/settings/site_settings_handler.h b/chromium/chrome/browser/ui/webui/settings/site_settings_handler.h index 902f8fc7b11..cac3cce681e 100644 --- a/chromium/chrome/browser/ui/webui/settings/site_settings_handler.h +++ b/chromium/chrome/browser/ui/webui/settings/site_settings_handler.h @@ -5,20 +5,20 @@ #ifndef CHROME_BROWSER_UI_WEBUI_SETTINGS_SITE_SETTINGS_HANDLER_H_ #define CHROME_BROWSER_UI_WEBUI_SETTINGS_SITE_SETTINGS_HANDLER_H_ +#include <map> #include <memory> +#include <set> #include <string> -#include <vector> #include "base/scoped_observer.h" -#include "chrome/browser/browsing_data/browsing_data_local_storage_helper.h" -#include "chrome/browser/storage/storage_info_fetcher.h" +#include "chrome/browser/browsing_data/cookies_tree_model.h" +#include "chrome/browser/permissions/chooser_context_base.h" #include "chrome/browser/ui/webui/settings/settings_page_ui_handler.h" #include "components/content_settings/core/browser/content_settings_observer.h" #include "content/public/browser/host_zoom_map.h" #include "content/public/browser/notification_observer.h" #include "content/public/browser/notification_registrar.h" #include "ppapi/buildflags/buildflags.h" -#include "third_party/blink/public/mojom/quota/quota_types.mojom.h" class HostContentSettingsMap; class Profile; @@ -34,21 +34,35 @@ namespace settings { // Chrome "ContentSettings" settings page UI handler. class SiteSettingsHandler : public SettingsPageUIHandler, public content_settings::Observer, - public content::NotificationObserver { + public content::NotificationObserver, + public ChooserContextBase::PermissionObserver, + public CookiesTreeModel::Observer { public: explicit SiteSettingsHandler(Profile* profile); ~SiteSettingsHandler() override; // SettingsPageUIHandler: void RegisterMessages() override; + void OnJavascriptAllowed() override; void OnJavascriptDisallowed() override; // Usage info. - void OnGetUsageInfo(const storage::UsageInfoEntries& entries); - void OnStorageCleared(base::OnceClosure callback, - blink::mojom::QuotaStatusCode code); - void OnUsageCleared(); + void OnGetUsageInfo(); + + // CookiesTreeModel::Observer: + // TODO(https://crbug.com/835712): Listen for backend data changes and notify + // WebUI + void TreeNodesAdded(ui::TreeModel* model, + ui::TreeModelNode* parent, + int start, + int count) override; + void TreeNodesRemoved(ui::TreeModel* model, + ui::TreeModelNode* parent, + int start, + int count) override; + void TreeNodeChanged(ui::TreeModel* model, ui::TreeModelNode* node) override; + void TreeModelEndBatch(CookiesTreeModel* model) override; #if defined(OS_CHROMEOS) // Alert the Javascript that the |kEnableDRM| pref has changed. @@ -66,12 +80,27 @@ class SiteSettingsHandler : public SettingsPageUIHandler, const content::NotificationSource& source, const content::NotificationDetails& details) override; + // ChooserContextBase::PermissionObserver implementation: + void OnChooserObjectPermissionChanged( + ContentSettingsType guard_content_settings_type, + ContentSettingsType data_content_settings_type) override; + // content::HostZoomMap subscription. void OnZoomLevelChanged(const content::HostZoomMap::ZoomLevelChange& change); private: - friend class SiteSettingsHandlerTest; + friend class SiteSettingsHandlerChooserExceptionTest; friend class SiteSettingsHandlerInfobarTest; + friend class SiteSettingsHandlerTest; + FRIEND_TEST_ALL_PREFIXES(SiteSettingsHandlerChooserExceptionTest, + HandleGetChooserExceptionListForUsb); + FRIEND_TEST_ALL_PREFIXES(SiteSettingsHandlerChooserExceptionTest, + HandleResetChooserExceptionForSiteForUsb); + FRIEND_TEST_ALL_PREFIXES(SiteSettingsHandlerInfobarTest, + SettingPermissionsTriggersInfobar); + FRIEND_TEST_ALL_PREFIXES(SiteSettingsHandlerTest, + BlockAutoplay_SendOnRequest); + FRIEND_TEST_ALL_PREFIXES(SiteSettingsHandlerTest, BlockAutoplay_Update); #if BUILDFLAG(ENABLE_PLUGINS) FRIEND_TEST_ALL_PREFIXES(SiteSettingsHandlerTest, ChangingFlashSettingForSiteIsRemembered); @@ -79,22 +108,37 @@ class SiteSettingsHandler : public SettingsPageUIHandler, FRIEND_TEST_ALL_PREFIXES(SiteSettingsHandlerTest, DefaultSettingSource); FRIEND_TEST_ALL_PREFIXES(SiteSettingsHandlerTest, ExceptionHelpers); FRIEND_TEST_ALL_PREFIXES(SiteSettingsHandlerTest, ExtensionDisplayName); + FRIEND_TEST_ALL_PREFIXES(SiteSettingsHandlerTest, GetAllSites); + FRIEND_TEST_ALL_PREFIXES(SiteSettingsHandlerTest, OnStorageFetched); FRIEND_TEST_ALL_PREFIXES(SiteSettingsHandlerTest, GetAndSetDefault); - FRIEND_TEST_ALL_PREFIXES(SiteSettingsHandlerTest, GetAndSetOriginPermissions); FRIEND_TEST_ALL_PREFIXES(SiteSettingsHandlerTest, GetAndSetForInvalidURLs); + FRIEND_TEST_ALL_PREFIXES(SiteSettingsHandlerTest, GetAndSetOriginPermissions); FRIEND_TEST_ALL_PREFIXES(SiteSettingsHandlerTest, Incognito); - FRIEND_TEST_ALL_PREFIXES(SiteSettingsHandlerTest, GetAllSites); - FRIEND_TEST_ALL_PREFIXES(SiteSettingsHandlerTest, GetAllSitesLocalStorage); FRIEND_TEST_ALL_PREFIXES(SiteSettingsHandlerTest, Origins); FRIEND_TEST_ALL_PREFIXES(SiteSettingsHandlerTest, Patterns); FRIEND_TEST_ALL_PREFIXES(SiteSettingsHandlerTest, PatternsAndContentType); - FRIEND_TEST_ALL_PREFIXES(SiteSettingsHandlerTest, ZoomLevels); - FRIEND_TEST_ALL_PREFIXES(SiteSettingsHandlerInfobarTest, - SettingPermissionsTriggersInfobar); FRIEND_TEST_ALL_PREFIXES(SiteSettingsHandlerTest, SessionOnlyException); + FRIEND_TEST_ALL_PREFIXES(SiteSettingsHandlerTest, ZoomLevels); FRIEND_TEST_ALL_PREFIXES(SiteSettingsHandlerTest, - BlockAutoplay_SendOnRequest); - FRIEND_TEST_ALL_PREFIXES(SiteSettingsHandlerTest, BlockAutoplay_Update); + HandleClearEtldPlus1DataAndCookies); + + // Creates the CookiesTreeModel if necessary. + void EnsureCookiesTreeModelCreated(bool omit_cookies = false); + + // Add this class as an observer for content settings and chooser contexts. + void ObserveSources(); + + // Calculates the data storage that has been used for each origin, and + // stores the information in the |all_sites_map| and |origin_size_map|. + void GetOriginStorage( + std::map<std::string, std::set<std::string>>* all_sites_map, + std::map<std::string, int>* origin_size_map); + + // Calculates the number of cookies for each etld+1 and each origin, and + // stores the information in the |all_sites_map| and |origin_cookie_map|. + void GetOriginCookies( + std::map<std::string, std::set<std::string>>* all_sites_map, + std::map<std::string, int>* origin_cookie_map); // Asynchronously fetches the usage for a given origin. Replies back with // OnGetUsageInfo above. @@ -113,15 +157,20 @@ class SiteSettingsHandler : public SettingsPageUIHandler, void HandleSetDefaultValueForContentType(const base::ListValue* args); void HandleGetDefaultValueForContentType(const base::ListValue* args); - // Returns a list of sites, grouped by their effective top level domain plus - // 1, affected by any of the content settings specified in |args|. + // Returns a list of sites with permissions settings, grouped by their + // eTLD+1. Recreates the cookies tree model to fetch the cookie and usage + // data, which will send the list of sites with cookies or usage data to + // the front end when fetching finished. void HandleGetAllSites(const base::ListValue* args); - // Called when the list of origins using local storage has been fetched, and - // sends this list back to the front end. - void OnLocalStorageFetched( - const std::list<BrowsingDataLocalStorageHelper::LocalStorageInfo>& - local_storage_info); + // Called when the list of origins using storage has been fetched, and sends + // this list back to the front end. + void OnStorageFetched(); + + // Returns a list of sites, grouped by their effective top level domain plus + // 1, with their cookies number and data usage information. This method will + // only be called after HandleGetAllSites is called. + base::Value PopulateCookiesAndUsageData(Profile* profile); // Converts a given number of bytes into a human-readable format, with data // units. @@ -130,6 +179,9 @@ class SiteSettingsHandler : public SettingsPageUIHandler, // Returns the list of site exceptions for a given content settings type. void HandleGetExceptionList(const base::ListValue* args); + // Returns the list of chooser exceptions for a given chooser type. + void HandleGetChooserExceptionList(const base::ListValue* args); + // Gets and sets a list of ContentSettingTypes for an origin. // TODO(https://crbug.com/739241): Investigate replacing the // '*CategoryPermissionForPattern' equivalents below with these methods. @@ -144,6 +196,9 @@ class SiteSettingsHandler : public SettingsPageUIHandler, void HandleResetCategoryPermissionForPattern(const base::ListValue* args); void HandleSetCategoryPermissionForPattern(const base::ListValue* args); + // Handles resetting a chooser exception for the given site. + void HandleResetChooserExceptionForSite(const base::ListValue* args); + // Returns whether a given string is a valid origin. void HandleIsOriginValid(const base::ListValue* args); @@ -174,10 +229,13 @@ class SiteSettingsHandler : public SettingsPageUIHandler, // Updates the block autoplay enabled pref when the UI is toggled. void HandleSetBlockAutoplayEnabled(const base::ListValue* args); - void SetBrowsingDataLocalStorageHelperForTesting( - scoped_refptr<BrowsingDataLocalStorageHelper> helper); + // Clear web storage data and cookies from cookies tree model for an ETLD+1. + void HandleClearEtldPlus1DataAndCookies(const base::ListValue* args); - BrowsingDataLocalStorageHelper* GetLocalStorageHelper(); + void SetCookiesTreeModelForTesting( + std::unique_ptr<CookiesTreeModel> cookies_tree_model); + + void ClearAllSitesMapForTesting(); Profile* profile_; @@ -196,10 +254,26 @@ class SiteSettingsHandler : public SettingsPageUIHandler, // Change observer for content settings. ScopedObserver<HostContentSettingsMap, content_settings::Observer> observer_; + // Change observer for chooser permissions. + ScopedObserver<ChooserContextBase, ChooserContextBase::PermissionObserver> + chooser_observer_; + // Change observer for prefs. std::unique_ptr<PrefChangeRegistrar> pref_change_registrar_; - scoped_refptr<BrowsingDataLocalStorageHelper> local_storage_helper_; + std::unique_ptr<CookiesTreeModel> cookies_tree_model_; + + // Whether to send all sites list on cookie tree model update. + bool send_sites_list_ = false; + + // Populated every time the user reloads the All Sites page. + std::map<std::string, std::set<std::string>> all_sites_map_; + + // Store the origins that has permission settings. + std::set<std::string> origin_permission_set_; + + // Whether to send site detail data on cookie tree model update. + bool update_site_details_ = false; DISALLOW_COPY_AND_ASSIGN(SiteSettingsHandler); }; diff --git a/chromium/chrome/browser/ui/webui/settings/site_settings_handler_unittest.cc b/chromium/chrome/browser/ui/webui/settings/site_settings_handler_unittest.cc index 577253bd64f..ba8af47af55 100644 --- a/chromium/chrome/browser/ui/webui/settings/site_settings_handler_unittest.cc +++ b/chromium/chrome/browser/ui/webui/settings/site_settings_handler_unittest.cc @@ -6,19 +6,28 @@ #include <memory> #include <string> +#include <utility> +#include "base/json/json_reader.h" #include "base/test/metrics/histogram_tester.h" #include "base/test/simple_test_clock.h" +#include "base/values.h" +#include "chrome/browser/browsing_data/browsing_data_flash_lso_helper.h" +#include "chrome/browser/browsing_data/mock_browsing_data_cookie_helper.h" #include "chrome/browser/browsing_data/mock_browsing_data_local_storage_helper.h" #include "chrome/browser/chrome_notification_types.h" #include "chrome/browser/content_settings/host_content_settings_map_factory.h" #include "chrome/browser/extensions/extension_service.h" #include "chrome/browser/extensions/test_extension_system.h" #include "chrome/browser/infobars/infobar_service.h" +#include "chrome/browser/permissions/chooser_context_base.h" +#include "chrome/browser/permissions/chooser_context_base_mock_permission_observer.h" #include "chrome/browser/permissions/permission_decision_auto_blocker.h" #include "chrome/browser/ui/browser_window.h" #include "chrome/browser/ui/tabs/tab_strip_model.h" #include "chrome/browser/ui/webui/site_settings_helper.h" +#include "chrome/browser/usb/usb_chooser_context.h" +#include "chrome/browser/usb/usb_chooser_context_factory.h" #include "chrome/common/pref_names.h" #include "chrome/test/base/browser_with_test_window_test.h" #include "chrome/test/base/testing_profile.h" @@ -33,6 +42,7 @@ #include "content/public/browser/web_ui_data_source.h" #include "content/public/test/test_browser_thread_bundle.h" #include "content/public/test/test_web_ui.h" +#include "device/usb/public/cpp/fake_usb_device_manager.h" #include "extensions/browser/extension_registry.h" #include "extensions/common/extension_builder.h" #include "ppapi/buildflags/buildflags.h" @@ -376,6 +386,71 @@ class SiteSettingsHandlerTest : public testing::Test { incognito_profile_ = nullptr; } + // TODO(https://crbug.com/835712): Currently only set up the cookies and local + // storage nodes, will update all other nodes in the future. + void SetUpCookiesTreeModel() { + scoped_refptr<MockBrowsingDataCookieHelper> + mock_browsing_data_cookie_helper; + scoped_refptr<MockBrowsingDataLocalStorageHelper> + mock_browsing_data_local_storage_helper; + + mock_browsing_data_cookie_helper = + new MockBrowsingDataCookieHelper(profile()); + mock_browsing_data_local_storage_helper = + new MockBrowsingDataLocalStorageHelper(profile()); + + auto container = std::make_unique<LocalDataContainer>( + mock_browsing_data_cookie_helper, + /*database_helper=*/nullptr, mock_browsing_data_local_storage_helper, + /*session_storage_helper=*/nullptr, + /*appcache_helper=*/nullptr, + /*indexed_db_helper=*/nullptr, + /*file_system_helper=*/nullptr, + /*quota_helper=*/nullptr, + /*service_worker_helper=*/nullptr, + /*data_shared_worker_helper=*/nullptr, + /*cache_storage_helper=*/nullptr, + /*flash_lso_helper=*/nullptr, + /*media_license_helper=*/nullptr); + auto mock_cookies_tree_model = std::make_unique<CookiesTreeModel>( + std::move(container), profile()->GetExtensionSpecialStoragePolicy()); + + mock_browsing_data_local_storage_helper->AddLocalStorageForOrigin( + GURL("https://www.example.com/"), 2); + + mock_browsing_data_local_storage_helper->AddLocalStorageForOrigin( + GURL("https://www.google.com/"), 5); + mock_browsing_data_local_storage_helper->Notify(); + + mock_browsing_data_cookie_helper->AddCookieSamples( + GURL("http://example.com"), "A=1"); + mock_browsing_data_cookie_helper->AddCookieSamples( + GURL("http://www.example.com/"), "B=1"); + mock_browsing_data_cookie_helper->AddCookieSamples( + GURL("http://abc.example.com"), "C=1"); + mock_browsing_data_cookie_helper->AddCookieSamples( + GURL("http://google.com"), "A=1"); + mock_browsing_data_cookie_helper->AddCookieSamples( + GURL("http://google.com"), "B=1"); + mock_browsing_data_cookie_helper->AddCookieSamples( + GURL("http://google.com.au"), "A=1"); + mock_browsing_data_cookie_helper->Notify(); + + handler()->SetCookiesTreeModelForTesting( + std::move(mock_cookies_tree_model)); + } + + const base::ListValue* GetOnStorageFetchedSentListValue() { + handler()->ClearAllSitesMapForTesting(); + handler()->OnStorageFetched(); + const content::TestWebUI::CallData& data = *web_ui()->call_data().back(); + std::string callback_id; + data.arg1()->GetAsString(&callback_id); + const base::ListValue* storage_and_cookie_list; + data.arg2()->GetAsList(&storage_and_cookie_list); + return storage_and_cookie_list; + } + // Content setting group name for the relevant ContentSettingsType. const std::string kNotifications; const std::string kCookies; @@ -609,59 +684,91 @@ TEST_F(SiteSettingsHandlerTest, GetAllSites) { run_loop.RunUntilIdle(); } -TEST_F(SiteSettingsHandlerTest, GetAllSitesLocalStorage) { - scoped_refptr<MockBrowsingDataLocalStorageHelper> - mock_browsing_data_local_storage_helper = - new MockBrowsingDataLocalStorageHelper(profile()); - handler()->SetBrowsingDataLocalStorageHelperForTesting( - mock_browsing_data_local_storage_helper); - - // Add local storage for |origin|. - const GURL origin("https://example.com:12378"); - mock_browsing_data_local_storage_helper->AddLocalStorageForOrigin(origin, 1); +TEST_F(SiteSettingsHandlerTest, OnStorageFetched) { + SetUpCookiesTreeModel(); - // Check these sites are included in the callback. - base::ListValue get_all_sites_args; - get_all_sites_args.AppendString(kCallbackId); - base::Value category_list(base::Value::Type::LIST); - get_all_sites_args.GetList().push_back(std::move(category_list)); - - // Wait for the fetch handler to finish, then check it includes |origin| in - // its result. - handler()->HandleGetAllSites(&get_all_sites_args); - EXPECT_EQ(1U, web_ui()->call_data().size()); - mock_browsing_data_local_storage_helper->Notify(); - EXPECT_EQ(2U, web_ui()->call_data().size()); - base::RunLoop run_loop; - run_loop.RunUntilIdle(); + handler()->ClearAllSitesMapForTesting(); + handler()->OnStorageFetched(); const content::TestWebUI::CallData& data = *web_ui()->call_data().back(); EXPECT_EQ("cr.webUIListenerCallback", data.function_name()); std::string callback_id; ASSERT_TRUE(data.arg1()->GetAsString(&callback_id)); - EXPECT_EQ("onLocalStorageListFetched", callback_id); + EXPECT_EQ("onStorageListFetched", callback_id); - const base::ListValue* local_storage_list; - ASSERT_TRUE(data.arg2()->GetAsList(&local_storage_list)); - EXPECT_EQ(1U, local_storage_list->GetSize()); + const base::ListValue* storage_and_cookie_list; + ASSERT_TRUE(data.arg2()->GetAsList(&storage_and_cookie_list)); + EXPECT_EQ(3U, storage_and_cookie_list->GetSize()); const base::DictionaryValue* site_group; - ASSERT_TRUE(local_storage_list->GetDictionary(0, &site_group)); + ASSERT_TRUE(storage_and_cookie_list->GetDictionary(0, &site_group)); std::string etld_plus1_string; ASSERT_TRUE(site_group->GetString("etldPlus1", &etld_plus1_string)); ASSERT_EQ("example.com", etld_plus1_string); + EXPECT_EQ(3, site_group->FindKey("numCookies")->GetDouble()); + const base::ListValue* origin_list; ASSERT_TRUE(site_group->GetList("origins", &origin_list)); - EXPECT_EQ(1U, origin_list->GetSize()); + // There will be 2 origins in this case. Cookie node with url + // http://www.example.com/ will be treat as https://www.example.com/ because + // this url existed in the storage nodes. + EXPECT_EQ(2U, origin_list->GetSize()); const base::DictionaryValue* origin_info; + + ASSERT_TRUE(origin_list->GetDictionary(0, &origin_info)); + EXPECT_EQ("http://abc.example.com/", + origin_info->FindKey("origin")->GetString()); + EXPECT_EQ(0, origin_info->FindKey("engagement")->GetDouble()); + EXPECT_EQ(0, origin_info->FindKey("usage")->GetDouble()); + EXPECT_EQ(1, origin_info->FindKey("numCookies")->GetDouble()); + + ASSERT_TRUE(origin_list->GetDictionary(1, &origin_info)); + // Even though in the cookies the scheme is http, it still stored as https + // because there is https data stored. + EXPECT_EQ("https://www.example.com/", + origin_info->FindKey("origin")->GetString()); + EXPECT_EQ(0, origin_info->FindKey("engagement")->GetDouble()); + EXPECT_EQ(2, origin_info->FindKey("usage")->GetDouble()); + EXPECT_EQ(1, origin_info->FindKey("numCookies")->GetDouble()); + + ASSERT_TRUE(storage_and_cookie_list->GetDictionary(1, &site_group)); + + ASSERT_TRUE(site_group->GetString("etldPlus1", &etld_plus1_string)); + ASSERT_EQ("google.com", etld_plus1_string); + + EXPECT_EQ(2, site_group->FindKey("numCookies")->GetDouble()); + + ASSERT_TRUE(site_group->GetList("origins", &origin_list)); + + EXPECT_EQ(1U, origin_list->GetSize()); + ASSERT_TRUE(origin_list->GetDictionary(0, &origin_info)); - EXPECT_EQ(origin.spec(), origin_info->FindKey("origin")->GetString()); + EXPECT_EQ("https://www.google.com/", + origin_info->FindKey("origin")->GetString()); EXPECT_EQ(0, origin_info->FindKey("engagement")->GetDouble()); - EXPECT_EQ(1, origin_info->FindKey("usage")->GetDouble()); + EXPECT_EQ(5, origin_info->FindKey("usage")->GetDouble()); + EXPECT_EQ(0, origin_info->FindKey("numCookies")->GetDouble()); + + ASSERT_TRUE(storage_and_cookie_list->GetDictionary(2, &site_group)); + + ASSERT_TRUE(site_group->GetString("etldPlus1", &etld_plus1_string)); + ASSERT_EQ("google.com.au", etld_plus1_string); + + EXPECT_EQ(1, site_group->FindKey("numCookies")->GetDouble()); + + ASSERT_TRUE(site_group->GetList("origins", &origin_list)); + EXPECT_EQ(1U, origin_list->GetSize()); + + ASSERT_TRUE(origin_list->GetDictionary(0, &origin_info)); + EXPECT_EQ("http://google.com.au/", + origin_info->FindKey("origin")->GetString()); + EXPECT_EQ(0, origin_info->FindKey("engagement")->GetDouble()); + EXPECT_EQ(0, origin_info->FindKey("usage")->GetDouble()); + EXPECT_EQ(0, origin_info->FindKey("numCookies")->GetDouble()); } TEST_F(SiteSettingsHandlerTest, Origins) { @@ -1324,4 +1431,365 @@ TEST_F(SiteSettingsHandlerTest, BlockAutoplay_Update) { EXPECT_FALSE(profile()->GetPrefs()->GetBoolean(prefs::kBlockAutoplayEnabled)); } +namespace { + +const GURL kAndroidOrigin("https://android.com"); +const GURL kChromiumOrigin("https://chromium.org"); +const GURL kGoogleOrigin("https://google.com"); + +constexpr char kUsbPolicySetting[] = R"( + [ + { + "devices": [{ "vendor_id": 6353, "product_id": 5678 }], + "urls": ["https://chromium.org"] + }, { + "devices": [{ "vendor_id": 6353 }], + "urls": ["https://google.com,https://android.com"] + }, { + "devices": [{ "vendor_id": 6354 }], + "urls": ["https://android.com,"] + }, { + "devices": [{}], + "urls": ["https://google.com,https://google.com"] + } + ])"; + +} // namespace + +class SiteSettingsHandlerChooserExceptionTest : public SiteSettingsHandlerTest { + protected: + void SetUp() override { + // Set up UsbChooserContext first, since the granting of device permissions + // causes the WebUI listener callbacks for + // contentSettingSitePermissionChanged and + // contentSettingChooserPermissionChanged to be fired. The base class SetUp + // method reset the WebUI call data. + SetUpUsbChooserContext(); + SiteSettingsHandlerTest::SetUp(); + } + + void TearDown() override { + auto* chooser_context = UsbChooserContextFactory::GetForProfile(profile()); + chooser_context->ChooserContextBase::RemoveObserver(&observer_); + } + + // Sets up the UsbChooserContext with two devices and permissions for these + // devices. It also adds three policy defined permissions. There are three + // devices that are granted user permissions. Two are covered by different + // policy permissions, while the third is not covered by policy at all. These + // unit tests will check that the WebUI is able to receive the exceptions and + // properly manipulate their permissions. + void SetUpUsbChooserContext() { + persistent_device_info_ = device_manager_.CreateAndAddDevice( + 6353, 5678, "Google", "Gizmo", "123ABC"); + ephemeral_device_info_ = + device_manager_.CreateAndAddDevice(6354, 0, "Google", "Gadget", ""); + user_granted_device_info_ = device_manager_.CreateAndAddDevice( + 6355, 0, "Google", "Widget", "789XYZ"); + + auto* chooser_context = UsbChooserContextFactory::GetForProfile(profile()); + device::mojom::UsbDeviceManagerPtr device_manager_ptr; + device_manager_.AddBinding(mojo::MakeRequest(&device_manager_ptr)); + chooser_context->SetDeviceManagerForTesting(std::move(device_manager_ptr)); + chooser_context->GetDevices( + base::DoNothing::Once<std::vector<device::mojom::UsbDeviceInfoPtr>>()); + base::RunLoop().RunUntilIdle(); + + // Add the user granted permissions for testing. + // These two persistent device permissions should be lumped together with + // the policy permissions, since they apply to the same device and URL. + chooser_context->GrantDevicePermission(kChromiumOrigin, kChromiumOrigin, + *persistent_device_info_); + chooser_context->GrantDevicePermission(kChromiumOrigin, kGoogleOrigin, + *persistent_device_info_); + chooser_context->GrantDevicePermission(kAndroidOrigin, kChromiumOrigin, + *persistent_device_info_); + chooser_context->GrantDevicePermission(kAndroidOrigin, kAndroidOrigin, + *ephemeral_device_info_); + chooser_context->GrantDevicePermission(kAndroidOrigin, kAndroidOrigin, + *user_granted_device_info_); + + // Add the policy granted permissions for testing. + auto policy_value = base::JSONReader::Read(kUsbPolicySetting); + DCHECK(policy_value); + profile()->GetPrefs()->Set(prefs::kManagedWebUsbAllowDevicesForUrls, + *policy_value); + + // Add the observer for permission changes. + chooser_context->ChooserContextBase::AddObserver(&observer_); + } + + // Call SiteSettingsHandler::HandleGetChooserExceptionList for |chooser_type| + // and return the exception list received by the WebUI. + void ValidateChooserExceptionList(const std::string& chooser_type, + size_t expected_total_calls) { + base::ListValue args; + args.AppendString(kCallbackId); + args.AppendString(chooser_type); + + handler()->HandleGetChooserExceptionList(&args); + + EXPECT_EQ(web_ui()->call_data().size(), expected_total_calls); + + const content::TestWebUI::CallData& data = *web_ui()->call_data().back(); + EXPECT_EQ("cr.webUIResponse", data.function_name()); + + ASSERT_TRUE(data.arg1()); + ASSERT_TRUE(data.arg1()->is_string()); + EXPECT_EQ(data.arg1()->GetString(), kCallbackId); + + ASSERT_TRUE(data.arg2()); + ASSERT_TRUE(data.arg2()->is_bool()); + EXPECT_TRUE(data.arg2()->GetBool()); + + ASSERT_TRUE(data.arg3()); + ASSERT_TRUE(data.arg3()->is_list()); + } + + const base::Value& GetChooserExceptionListFromWebUiCallData( + const std::string& chooser_type, + size_t expected_total_calls) { + ValidateChooserExceptionList(chooser_type, expected_total_calls); + return *web_ui()->call_data().back()->arg3(); + } + + // Iterate through the exception's sites array and return true if a site + // exception matches |requesting_origin| and |embedding_origin|. + bool ChooserExceptionContainsSiteException( + const base::Value& exception, + const std::string& requesting_origin, + const std::string& embedding_origin) { + const base::Value* site_value = exception.FindKey(site_settings::kSites); + for (const auto& site : site_value->GetList()) { + const base::Value* origin_value = site.FindKey(site_settings::kOrigin); + if (origin_value->GetString() != requesting_origin) + continue; + + const base::Value* embedding_origin_value = + site.FindKey(site_settings::kEmbeddingOrigin); + if (embedding_origin_value->GetString() == embedding_origin) + return true; + } + return false; + } + + // Iterate through the |exception_list| array and return true if there is a + // chooser exception with |display_name| that contains a site exception for + // |requesting_origin| and |embedding_origin|. + bool ChooserExceptionContainsSiteException( + const base::Value& exception_list, + const std::string& display_name, + const std::string& requesting_origin, + const std::string& embedding_origin) { + for (const auto& exception : exception_list.GetList()) { + const base::Value* display_name_value = + exception.FindKey(site_settings::kDisplayName); + if (display_name_value->GetString() == display_name) { + return ChooserExceptionContainsSiteException( + exception, requesting_origin, embedding_origin); + } + } + return false; + } + + device::mojom::UsbDeviceInfoPtr persistent_device_info_; + device::mojom::UsbDeviceInfoPtr ephemeral_device_info_; + device::mojom::UsbDeviceInfoPtr user_granted_device_info_; + + MockPermissionObserver observer_; + + private: + device::FakeUsbDeviceManager device_manager_; +}; + +TEST_F(SiteSettingsHandlerChooserExceptionTest, + HandleGetChooserExceptionListForUsb) { + const std::string kUsbChooserGroupName = + site_settings::ContentSettingsTypeToGroupName( + CONTENT_SETTINGS_TYPE_USB_CHOOSER_DATA); + + const base::Value& exceptions = GetChooserExceptionListFromWebUiCallData( + kUsbChooserGroupName, /*expected_total_calls=*/1u); + EXPECT_EQ(exceptions.GetList().size(), 5u); +} + +TEST_F(SiteSettingsHandlerChooserExceptionTest, + HandleResetChooserExceptionForSiteForUsb) { + const std::string kUsbChooserGroupName = + site_settings::ContentSettingsTypeToGroupName( + CONTENT_SETTINGS_TYPE_USB_CHOOSER_DATA); + const std::string kAndroidOriginStr = kAndroidOrigin.GetOrigin().spec(); + const std::string kChromiumOriginStr = kChromiumOrigin.GetOrigin().spec(); + + { + const base::Value& exceptions = GetChooserExceptionListFromWebUiCallData( + kUsbChooserGroupName, /*expected_total_calls=*/1u); + EXPECT_EQ(exceptions.GetList().size(), 5u); + } + + // User granted USB permissions for devices also containing policy permissions + // should be able to be reset without removing the chooser exception object + // from the list. + base::ListValue args; + args.AppendString(kUsbChooserGroupName); + args.AppendString(kAndroidOriginStr); + args.AppendString(kChromiumOriginStr); + args.Append( + UsbChooserContext::DeviceInfoToDictValue(*persistent_device_info_)); + + EXPECT_CALL(observer_, OnChooserObjectPermissionChanged( + CONTENT_SETTINGS_TYPE_USB_GUARD, + CONTENT_SETTINGS_TYPE_USB_CHOOSER_DATA)); + EXPECT_CALL(observer_, OnPermissionRevoked(kAndroidOrigin, kChromiumOrigin)); + handler()->HandleResetChooserExceptionForSite(&args); + + // The HandleResetChooserExceptionForSite() method should have also caused the + // WebUIListenerCallbacks for contentSettingSitePermissionChanged and + // contentSettingChooserPermissionChanged to fire. + EXPECT_EQ(web_ui()->call_data().size(), 3u); + { + // The exception list size should not have been reduced since there is still + // a policy granted permission for the "Gizmo" device. + const base::Value& exceptions = GetChooserExceptionListFromWebUiCallData( + kUsbChooserGroupName, /*expected_total_calls=*/4u); + EXPECT_EQ(exceptions.GetList().size(), 5u); + + // Ensure that the sites list does not contain the URLs of the removed + // permission. + EXPECT_FALSE(ChooserExceptionContainsSiteException( + exceptions, "Gizmo", kAndroidOriginStr, kChromiumOriginStr)); + } + + // User granted USB permissions that are also granted by policy should not + // be able to be reset. + args.Clear(); + args.AppendString(kUsbChooserGroupName); + args.AppendString(kChromiumOriginStr); + args.AppendString(kChromiumOriginStr); + args.Append( + UsbChooserContext::DeviceInfoToDictValue(*persistent_device_info_)); + + { + const base::Value& exceptions = + GetChooserExceptionListFromWebUiCallData(kUsbChooserGroupName, 5u); + EXPECT_EQ(exceptions.GetList().size(), 5u); + + // User granted exceptions that are also granted by policy are only + // displayed through the policy granted site exception, so ensure that a + // site exception entry for a requesting and embedding origin of + // kChromiumOriginStr does not exist. + EXPECT_TRUE(ChooserExceptionContainsSiteException( + exceptions, "Gizmo", kChromiumOriginStr, std::string())); + EXPECT_FALSE(ChooserExceptionContainsSiteException( + exceptions, "Gizmo", kChromiumOriginStr, kChromiumOriginStr)); + } + + EXPECT_CALL(observer_, OnChooserObjectPermissionChanged( + CONTENT_SETTINGS_TYPE_USB_GUARD, + CONTENT_SETTINGS_TYPE_USB_CHOOSER_DATA)); + EXPECT_CALL(observer_, OnPermissionRevoked(kChromiumOrigin, kChromiumOrigin)); + handler()->HandleResetChooserExceptionForSite(&args); + + // The HandleResetChooserExceptionForSite() method should have also caused the + // WebUIListenerCallbacks for contentSettingSitePermissionChanged and + // contentSettingChooserPermissionChanged to fire. + EXPECT_EQ(web_ui()->call_data().size(), 7u); + { + const base::Value& exceptions = GetChooserExceptionListFromWebUiCallData( + kUsbChooserGroupName, /*expected_total_calls=*/8u); + EXPECT_EQ(exceptions.GetList().size(), 5u); + + // Ensure that the sites list still displays a site exception entry for a + // requesting origin of kChromiumOriginStr and a wildcard embedding origin. + EXPECT_TRUE(ChooserExceptionContainsSiteException( + exceptions, "Gizmo", kChromiumOriginStr, std::string())); + EXPECT_FALSE(ChooserExceptionContainsSiteException( + exceptions, "Gizmo", kChromiumOriginStr, kChromiumOriginStr)); + } + + // User granted USB permissions that are not covered by policy should be able + // to be reset and the chooser exception entry should be removed from the list + // when the exception only has one site exception granted to it.. + args.Clear(); + args.AppendString(kUsbChooserGroupName); + args.AppendString(kAndroidOriginStr); + args.AppendString(kAndroidOriginStr); + args.Append( + UsbChooserContext::DeviceInfoToDictValue(*user_granted_device_info_)); + + { + const base::Value& exceptions = + GetChooserExceptionListFromWebUiCallData(kUsbChooserGroupName, 9u); + EXPECT_EQ(exceptions.GetList().size(), 5u); + EXPECT_TRUE(ChooserExceptionContainsSiteException( + exceptions, "Widget", kAndroidOriginStr, kAndroidOriginStr)); + } + + EXPECT_CALL(observer_, OnChooserObjectPermissionChanged( + CONTENT_SETTINGS_TYPE_USB_GUARD, + CONTENT_SETTINGS_TYPE_USB_CHOOSER_DATA)); + EXPECT_CALL(observer_, OnPermissionRevoked(kAndroidOrigin, kAndroidOrigin)); + handler()->HandleResetChooserExceptionForSite(&args); + + // The HandleResetChooserExceptionForSite() method should have also caused the + // WebUIListenerCallbacks for contentSettingSitePermissionChanged and + // contentSettingChooserPermissionChanged to fire. + EXPECT_EQ(web_ui()->call_data().size(), 11u); + { + const base::Value& exceptions = GetChooserExceptionListFromWebUiCallData( + kUsbChooserGroupName, /*expected_total_calls=*/12u); + EXPECT_EQ(exceptions.GetList().size(), 4u); + EXPECT_FALSE(ChooserExceptionContainsSiteException( + exceptions, "Widget", kAndroidOriginStr, kAndroidOriginStr)); + } +} + +TEST_F(SiteSettingsHandlerTest, HandleClearEtldPlus1DataAndCookies) { + SetUpCookiesTreeModel(); + + EXPECT_EQ(22, handler()->cookies_tree_model_->GetRoot()->GetTotalNodeCount()); + + const base::ListValue* storage_and_cookie_list = + GetOnStorageFetchedSentListValue(); + EXPECT_EQ(3U, storage_and_cookie_list->GetSize()); + const base::DictionaryValue* site_group; + ASSERT_TRUE(storage_and_cookie_list->GetDictionary(0, &site_group)); + std::string etld_plus1_string; + ASSERT_TRUE(site_group->GetString("etldPlus1", &etld_plus1_string)); + ASSERT_EQ("example.com", etld_plus1_string); + + base::ListValue args; + args.AppendString("example.com"); + handler()->HandleClearEtldPlus1DataAndCookies(&args); + EXPECT_EQ(11, handler()->cookies_tree_model_->GetRoot()->GetTotalNodeCount()); + + storage_and_cookie_list = GetOnStorageFetchedSentListValue(); + EXPECT_EQ(2U, storage_and_cookie_list->GetSize()); + ASSERT_TRUE(storage_and_cookie_list->GetDictionary(0, &site_group)); + ASSERT_TRUE(site_group->GetString("etldPlus1", &etld_plus1_string)); + ASSERT_EQ("google.com", etld_plus1_string); + + args.Clear(); + args.AppendString("google.com"); + + handler()->HandleClearEtldPlus1DataAndCookies(&args); + + EXPECT_EQ(4, handler()->cookies_tree_model_->GetRoot()->GetTotalNodeCount()); + + storage_and_cookie_list = GetOnStorageFetchedSentListValue(); + EXPECT_EQ(1U, storage_and_cookie_list->GetSize()); + ASSERT_TRUE(storage_and_cookie_list->GetDictionary(0, &site_group)); + ASSERT_TRUE(site_group->GetString("etldPlus1", &etld_plus1_string)); + ASSERT_EQ("google.com.au", etld_plus1_string); + + args.Clear(); + args.AppendString("google.com.au"); + + handler()->HandleClearEtldPlus1DataAndCookies(&args); + + EXPECT_EQ(1, handler()->cookies_tree_model_->GetRoot()->GetTotalNodeCount()); + + storage_and_cookie_list = GetOnStorageFetchedSentListValue(); + EXPECT_EQ(0U, storage_and_cookie_list->GetSize()); +} } // namespace settings diff --git a/chromium/chrome/browser/ui/webui/settings/tts_handler.cc b/chromium/chrome/browser/ui/webui/settings/tts_handler.cc index 9ac54fa35a3..c3f553c2ed5 100644 --- a/chromium/chrome/browser/ui/webui/settings/tts_handler.cc +++ b/chromium/chrome/browser/ui/webui/settings/tts_handler.cc @@ -98,7 +98,7 @@ void TtsHandler::OnVoicesChanged() { response.SetString("languageCode", language_code); response.SetString("fullLanguageCode", voice.lang); response.SetInteger("languageScore", language_score); - response.SetString("extensionId", voice.extension_id); + response.SetString("extensionId", voice.engine_id); responses.GetList().push_back(std::move(response)); } AllowJavascript(); @@ -108,6 +108,18 @@ void TtsHandler::OnVoicesChanged() { HandleGetTtsExtensions(nullptr); } +void TtsHandler::OnTtsEvent(content::TtsUtterance* utterance, + content::TtsEventType event_type, + int char_index, + const std::string& error_message) { + if (event_type == content::TTS_EVENT_END || + event_type == content::TTS_EVENT_INTERRUPTED || + event_type == content::TTS_EVENT_ERROR) { + base::Value result(false /* preview stopped */); + FireWebUIListener("tts-preview-state-changed", result); + } +} + void TtsHandler::HandlePreviewTtsVoice(const base::ListValue* args) { DCHECK_EQ(2U, args->GetSize()); std::string text; @@ -125,14 +137,17 @@ void TtsHandler::HandlePreviewTtsVoice(const base::ListValue* args) { json->GetString("name", &name); json->GetString("extension", &extension_id); - content::Utterance* utterance = - new content::Utterance(Profile::FromWebUI(web_ui())); - utterance->set_text(text); - utterance->set_voice_name(name); - utterance->set_extension_id(extension_id); - utterance->set_src_url(GURL("chrome://settings/manageAccessibility/tts")); - utterance->set_event_delegate(nullptr); + content::TtsUtterance* utterance = + content::TtsUtterance::Create((Profile::FromWebUI(web_ui()))); + utterance->SetText(text); + utterance->SetVoiceName(name); + utterance->SetEngineId(extension_id); + utterance->SetSrcUrl(GURL("chrome://settings/manageAccessibility/tts")); + utterance->SetEventDelegate(this); content::TtsController::GetInstance()->Stop(); + + base::Value result(true /* preview started */); + FireWebUIListener("tts-preview-state-changed", result); content::TtsController::GetInstance()->SpeakOrEnqueue(utterance); } @@ -159,6 +174,7 @@ void TtsHandler::OnJavascriptAllowed() { void TtsHandler::OnJavascriptDisallowed() { content::TtsController::GetInstance()->RemoveVoicesChangedDelegate(this); + content::TtsController::GetInstance()->RemoveUtteranceEventDelegate(this); } int TtsHandler::GetVoiceLangMatchScore(const content::VoiceData* voice, @@ -175,7 +191,7 @@ int TtsHandler::GetVoiceLangMatchScore(const content::VoiceData* voice, void TtsHandler::WakeTtsEngine(const base::ListValue* args) { Profile* profile = Profile::FromWebUI(web_ui()); - TtsExtensionEngine::GetInstance()->LoadBuiltInTtsExtension(profile); + TtsExtensionEngine::GetInstance()->LoadBuiltInTtsEngine(profile); extensions::ProcessManager::Get(profile)->WakeEventPage( extension_misc::kGoogleSpeechSynthesisExtensionId, base::BindOnce(&TtsHandler::OnTtsEngineAwake, diff --git a/chromium/chrome/browser/ui/webui/settings/tts_handler.h b/chromium/chrome/browser/ui/webui/settings/tts_handler.h index 3263578a4b8..93fd5b90acc 100644 --- a/chromium/chrome/browser/ui/webui/settings/tts_handler.h +++ b/chromium/chrome/browser/ui/webui/settings/tts_handler.h @@ -15,7 +15,8 @@ namespace settings { // Chrome "/manageAccessibility/tts/*" settings page UI handler. class TtsHandler : public SettingsPageUIHandler, - public content::VoicesChangedDelegate { + public content::VoicesChangedDelegate, + public content::UtteranceEventDelegate { public: TtsHandler(); ~TtsHandler() override; @@ -32,6 +33,12 @@ class TtsHandler : public SettingsPageUIHandler, // VoicesChangedDelegate implementation. void OnVoicesChanged() override; + // UtteranceEventDelegate implementation. + void OnTtsEvent(content::TtsUtterance* utterance, + content::TtsEventType event_type, + int char_index, + const std::string& error_message) override; + private: void WakeTtsEngine(const base::ListValue* args); void OnTtsEngineAwake(bool success); |