diff --git a/.gn b/.gn index bee1495..4e07d8f5 100644 --- a/.gn +++ b/.gn
@@ -28,6 +28,11 @@ # repo should define a flag that toggles on a behavior that implements the # additional logic required by Chrome to set the variables. default_args = { + # TODO(brettw) bug 684096: Chrome on iOS does not build v8, so "gn gen" prints + # a warning that "Build argument has no effect". When adding a v8 variable, it + # also needs to be defined to src/ios/BUILD.gn (respectively removed from both + # location when it is removed). + v8_extra_library_files = [ # Dependencies used by the extra libraries. Putting them here causes them # to be executed first during snapshot creation.
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/ntp/ContentSuggestionsNotificationHelper.java b/chrome/android/java/src/org/chromium/chrome/browser/ntp/ContentSuggestionsNotificationHelper.java index 3c26b3e..39fcce6b 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/ntp/ContentSuggestionsNotificationHelper.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/ntp/ContentSuggestionsNotificationHelper.java
@@ -19,7 +19,7 @@ import org.chromium.base.ContextUtils; import org.chromium.base.annotations.CalledByNative; import org.chromium.base.annotations.JNINamespace; -import org.chromium.base.library_loader.LibraryLoader; +import org.chromium.base.library_loader.LibraryProcessType; import org.chromium.chrome.R; import org.chromium.chrome.browser.IntentHandler; import org.chromium.chrome.browser.ShortcutHelper; @@ -30,6 +30,8 @@ import org.chromium.chrome.browser.notifications.channels.ChannelDefinitions; import org.chromium.chrome.browser.ntp.snippets.ContentSuggestionsNotificationAction; import org.chromium.chrome.browser.ntp.snippets.ContentSuggestionsNotificationOptOut; +import org.chromium.content.browser.BrowserStartupController; +import org.chromium.content.browser.BrowserStartupController.StartupCallback; import java.util.Collection; import java.util.Collections; @@ -417,19 +419,31 @@ .putInt(PREF_CACHED_CONSECUTIVE_IGNORED, consecutiveIgnored) .apply(); - if (LibraryLoader.isInitialized()) { - flushCachedMetrics(); - } + flushCachedMetrics(); } /** * Invokes nativeReceiveFlushedMetrics() with cached metrics and resets them. * - * It may be called from either native or Java code, as long as the native libray is loaded. + * It may be called from either native or Java code. If the browser has not been started-up, or + * startup has not completed (as when the native component flushes metrics during creation of + * the keyed service) the flush will be deferred until startup is complete. */ @CalledByNative private static void flushCachedMetrics() { - assert LibraryLoader.isInitialized(); + BrowserStartupController browserStartup = + BrowserStartupController.get(LibraryProcessType.PROCESS_BROWSER); + if (!browserStartup.isStartupSuccessfullyCompleted()) { + browserStartup.addStartupCompletedObserver(new StartupCallback() { + @Override + public void onSuccess(boolean alreadyStarted) { + flushCachedMetrics(); + } + @Override + public void onFailure() {} + }); + return; + } SharedPreferences prefs = ContextUtils.getAppSharedPreferences(); int tapCount = prefs.getInt(PREF_CACHED_ACTION_TAP, 0);
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/preferences/ClearBrowsingDataTabCheckBoxPreference.java b/chrome/android/java/src/org/chromium/chrome/browser/preferences/ClearBrowsingDataTabCheckBoxPreference.java index c56152a..9dabfe6 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/preferences/ClearBrowsingDataTabCheckBoxPreference.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/preferences/ClearBrowsingDataTabCheckBoxPreference.java
@@ -19,6 +19,7 @@ import org.chromium.base.ApiCompatibilityUtils; import org.chromium.chrome.R; +import org.chromium.chrome.browser.util.AccessibilityUtil; import org.chromium.ui.text.NoUnderlineClickableSpan; import org.chromium.ui.text.SpanApplier; @@ -51,7 +52,6 @@ final TextView textView = (TextView) view.findViewById(android.R.id.summary); - // TODO(dullweber): Rethink how the link can be made accessible to TalkBack before launch. // Create custom onTouch listener to be able to respond to click events inside the summary. textView.setOnTouchListener(new View.OnTouchListener() { @Override @@ -95,13 +95,19 @@ @Override public void setSummary(CharSequence summary) { - // If there is no link in the summary, invoke the default behavior. + // If there is no link in the summary invoke the default behavior. String summaryString = summary.toString(); if (!summaryString.contains("<link>") || !summaryString.contains("</link>")) { super.setSummary(summary); return; } - + // Talkback users can't select links inside the summary because it is already a target + // that toggles the checkbox. Links will still be read out and users can manually + // navigate to them. + if (AccessibilityUtil.isAccessibilityEnabled()) { + super.setSummary(summaryString.replaceAll("</?link>", "")); + return; + } // Linkify <link></link> span. final SpannableString summaryWithLink = SpanApplier.applySpans(summaryString, new SpanApplier.SpanInfo("<link>", "</link>", new NoUnderlineClickableSpan() {
diff --git a/chrome/browser/chromeos/extensions/file_manager/private_api_file_system.cc b/chrome/browser/chromeos/extensions/file_manager/private_api_file_system.cc index cfdd9e3b..a6f6c46 100644 --- a/chrome/browser/chromeos/extensions/file_manager/private_api_file_system.cc +++ b/chrome/browser/chromeos/extensions/file_manager/private_api_file_system.cc
@@ -28,7 +28,6 @@ #include "chrome/browser/chromeos/file_manager/path_util.h" #include "chrome/browser/chromeos/file_manager/volume_manager.h" #include "chrome/browser/chromeos/fileapi/file_system_backend.h" -#include "chrome/browser/extensions/extension_util.h" #include "chrome/browser/metrics/chrome_metrics_service_accessor.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/profiles/profile_manager.h" @@ -46,6 +45,7 @@ #include "content/public/browser/storage_partition.h" #include "content/public/common/url_constants.h" #include "device/media_transfer_protocol/media_transfer_protocol_manager.h" +#include "extensions/browser/extension_util.h" #include "net/base/escape.h" #include "storage/browser/fileapi/file_stream_reader.h" #include "storage/browser/fileapi/file_system_context.h"
diff --git a/chrome/browser/chromeos/file_manager/fileapi_util.cc b/chrome/browser/chromeos/file_manager/fileapi_util.cc index 2de343f8..9d23921 100644 --- a/chrome/browser/chromeos/file_manager/fileapi_util.cc +++ b/chrome/browser/chromeos/file_manager/fileapi_util.cc
@@ -13,7 +13,6 @@ #include "chrome/browser/chromeos/drive/file_system_util.h" #include "chrome/browser/chromeos/file_manager/app_id.h" #include "chrome/browser/chromeos/file_manager/filesystem_api_util.h" -#include "chrome/browser/extensions/extension_util.h" #include "chrome/browser/profiles/profile.h" #include "components/drive/file_system_core_util.h" #include "content/public/browser/browser_thread.h" @@ -21,6 +20,7 @@ #include "content/public/browser/site_instance.h" #include "content/public/browser/storage_partition.h" #include "content/public/common/file_chooser_file_info.h" +#include "extensions/browser/extension_util.h" #include "extensions/common/extension.h" #include "google_apis/drive/task_util.h" #include "net/base/escape.h"
diff --git a/chrome/browser/extensions/BUILD.gn b/chrome/browser/extensions/BUILD.gn index 1a59b4a..89ad558 100644 --- a/chrome/browser/extensions/BUILD.gn +++ b/chrome/browser/extensions/BUILD.gn
@@ -458,8 +458,6 @@ "blacklist_factory.h", "blacklist_state_fetcher.cc", "blacklist_state_fetcher.h", - "blob_reader.cc", - "blob_reader.h", "bookmark_app_helper.cc", "bookmark_app_helper.h", "browser_action_test_util.h",
diff --git a/chrome/browser/extensions/api/feedback_private/feedback_service.cc b/chrome/browser/extensions/api/feedback_private/feedback_service.cc index c00f6dc..1b934920 100644 --- a/chrome/browser/extensions/api/feedback_private/feedback_service.cc +++ b/chrome/browser/extensions/api/feedback_private/feedback_service.cc
@@ -13,6 +13,7 @@ #include "chrome/browser/profiles/profile.h" #include "chrome/common/chrome_content_client.h" #include "content/public/browser/browser_thread.h" +#include "extensions/browser/blob_reader.h" #include "net/base/network_change_notifier.h" using content::BrowserThread;
diff --git a/chrome/browser/extensions/api/feedback_private/feedback_service.h b/chrome/browser/extensions/api/feedback_private/feedback_service.h index e0b44055..aa3e86b 100644 --- a/chrome/browser/extensions/api/feedback_private/feedback_service.h +++ b/chrome/browser/extensions/api/feedback_private/feedback_service.h
@@ -12,7 +12,6 @@ #include "base/callback.h" #include "base/macros.h" #include "base/memory/weak_ptr.h" -#include "chrome/browser/extensions/blob_reader.h" #include "chrome/browser/feedback/system_logs/scrubbed_system_logs_fetcher.h" #include "components/feedback/feedback_data.h"
diff --git a/chrome/browser/extensions/api/file_system/file_system_api.cc b/chrome/browser/extensions/api/file_system/file_system_api.cc index 09b87c5..c5f365a9 100644 --- a/chrome/browser/extensions/api/file_system/file_system_api.cc +++ b/chrome/browser/extensions/api/file_system/file_system_api.cc
@@ -27,8 +27,6 @@ #include "base/value_conversions.h" #include "base/values.h" #include "build/build_config.h" -#include "chrome/browser/extensions/extension_service.h" -#include "chrome/browser/extensions/extension_util.h" #include "chrome/browser/extensions/path_util.h" #include "chrome/browser/platform_util.h" #include "chrome/browser/profiles/profile.h" @@ -48,6 +46,7 @@ #include "extensions/browser/app_window/app_window_registry.h" #include "extensions/browser/extension_prefs.h" #include "extensions/browser/extension_system.h" +#include "extensions/browser/extension_util.h" #include "extensions/browser/granted_file_entry.h" #include "extensions/common/permissions/api_permission.h" #include "extensions/common/permissions/permissions_data.h"
diff --git a/chrome/browser/extensions/api/media_galleries/media_galleries_api.cc b/chrome/browser/extensions/api/media_galleries/media_galleries_api.cc index dd6ccd57..826edf29 100644 --- a/chrome/browser/extensions/api/media_galleries/media_galleries_api.cc +++ b/chrome/browser/extensions/api/media_galleries/media_galleries_api.cc
@@ -25,7 +25,6 @@ #include "base/values.h" #include "chrome/browser/browser_process.h" #include "chrome/browser/extensions/api/file_system/file_system_api.h" -#include "chrome/browser/extensions/blob_reader.h" #include "chrome/browser/extensions/chrome_extension_function_details.h" #include "chrome/browser/extensions/extension_tab_util.h" #include "chrome/browser/media_galleries/fileapi/safe_media_metadata_parser.h" @@ -53,6 +52,7 @@ #include "extensions/browser/app_window/app_window.h" #include "extensions/browser/app_window/app_window_registry.h" #include "extensions/browser/blob_holder.h" +#include "extensions/browser/blob_reader.h" #include "extensions/browser/extension_prefs.h" #include "extensions/browser/extension_system.h" #include "extensions/common/extension.h"
diff --git a/chrome/browser/extensions/data_deleter.cc b/chrome/browser/extensions/data_deleter.cc index 158afb2..643af139 100644 --- a/chrome/browser/extensions/data_deleter.cc +++ b/chrome/browser/extensions/data_deleter.cc
@@ -6,7 +6,6 @@ #include "chrome/browser/extensions/extension_service.h" #include "chrome/browser/extensions/extension_special_storage_policy.h" -#include "chrome/browser/extensions/extension_util.h" #include "chrome/browser/profiles/profile.h" #include "chrome/common/extensions/manifest_handlers/app_launch_info.h" #include "content/public/browser/browser_context.h" @@ -16,6 +15,7 @@ #include "extensions/browser/api/storage/storage_frontend.h" #include "extensions/browser/extension_prefs.h" #include "extensions/browser/extension_system.h" +#include "extensions/browser/extension_util.h" #include "extensions/common/constants.h" #include "extensions/common/extension.h" #include "extensions/common/manifest_handlers/app_isolation_info.h"
diff --git a/chrome/browser/extensions/extension_garbage_collector.cc b/chrome/browser/extensions/extension_garbage_collector.cc index 782e302..0ccf5b8 100644 --- a/chrome/browser/extensions/extension_garbage_collector.cc +++ b/chrome/browser/extensions/extension_garbage_collector.cc
@@ -22,7 +22,6 @@ #include "base/time/time.h" #include "chrome/browser/extensions/extension_garbage_collector_factory.h" #include "chrome/browser/extensions/extension_service.h" -#include "chrome/browser/extensions/extension_util.h" #include "chrome/browser/extensions/install_tracker.h" #include "chrome/browser/extensions/pending_extension_manager.h" #include "components/crx_file/id_util.h" @@ -32,6 +31,7 @@ #include "extensions/browser/extension_prefs.h" #include "extensions/browser/extension_registry.h" #include "extensions/browser/extension_system.h" +#include "extensions/browser/extension_util.h" #include "extensions/common/extension.h" #include "extensions/common/file_util.h" #include "extensions/common/manifest_handlers/app_isolation_info.h"
diff --git a/chrome/browser/extensions/extension_service.cc b/chrome/browser/extensions/extension_service.cc index a77c73d..66bbac7 100644 --- a/chrome/browser/extensions/extension_service.cc +++ b/chrome/browser/extensions/extension_service.cc
@@ -76,6 +76,7 @@ #include "extensions/browser/extension_host.h" #include "extensions/browser/extension_registry.h" #include "extensions/browser/extension_system.h" +#include "extensions/browser/extension_util.h" #include "extensions/browser/extensions_browser_client.h" #include "extensions/browser/external_install_info.h" #include "extensions/browser/install_flag.h"
diff --git a/chrome/browser/extensions/extension_storage_monitor.cc b/chrome/browser/extensions/extension_storage_monitor.cc index 530adf8cb..b9bcfbd 100644 --- a/chrome/browser/extensions/extension_storage_monitor.cc +++ b/chrome/browser/extensions/extension_storage_monitor.cc
@@ -26,6 +26,7 @@ #include "extensions/browser/extension_prefs.h" #include "extensions/browser/extension_registry.h" #include "extensions/browser/extension_system.h" +#include "extensions/browser/extension_util.h" #include "extensions/browser/image_loader.h" #include "extensions/browser/uninstall_reason.h" #include "extensions/common/extension.h"
diff --git a/chrome/browser/extensions/extension_util.cc b/chrome/browser/extensions/extension_util.cc index dc9ae66..001061a 100644 --- a/chrome/browser/extensions/extension_util.cc +++ b/chrome/browser/extensions/extension_util.cc
@@ -36,6 +36,7 @@ #include "extensions/common/permissions/permissions_data.h" #include "extensions/grit/extensions_browser_resources.h" #include "ui/base/resource/resource_bundle.h" +#include "url/gurl.h" #if defined(OS_CHROMEOS) #include "chrome/browser/chromeos/file_manager/app_id.h" @@ -268,12 +269,6 @@ return true; } -GURL GetSiteForExtensionId(const std::string& extension_id, - content::BrowserContext* context) { - return content::SiteInstance::GetSiteForURL( - context, Extension::GetBaseURLFromExtensionId(extension_id)); -} - std::unique_ptr<base::DictionaryValue> GetExtensionInfo( const Extension* extension) { DCHECK(extension);
diff --git a/chrome/browser/extensions/extension_util.h b/chrome/browser/extensions/extension_util.h index 848bb34..544a641 100644 --- a/chrome/browser/extensions/extension_util.h +++ b/chrome/browser/extensions/extension_util.h
@@ -8,8 +8,6 @@ #include <memory> #include <string> -#include "url/gurl.h" - namespace base { class DictionaryValue; } @@ -88,11 +86,6 @@ bool IsExtensionIdle(const std::string& extension_id, content::BrowserContext* context); -// Returns the site of the |extension_id|, given the associated |context|. -// Suitable for use with BrowserContext::GetStoragePartitionForSite(). -GURL GetSiteForExtensionId(const std::string& extension_id, - content::BrowserContext* context); - // Sets the name, id, and icon resource path of the given extension into the // returned dictionary. std::unique_ptr<base::DictionaryValue> GetExtensionInfo(
diff --git a/chrome/browser/media_galleries/fileapi/safe_media_metadata_parser.cc b/chrome/browser/media_galleries/fileapi/safe_media_metadata_parser.cc index c0883f7..cb0cd03ab 100644 --- a/chrome/browser/media_galleries/fileapi/safe_media_metadata_parser.cc +++ b/chrome/browser/media_galleries/fileapi/safe_media_metadata_parser.cc
@@ -7,9 +7,10 @@ #include <utility> #include "base/memory/ptr_util.h" -#include "chrome/browser/extensions/blob_reader.h" #include "chrome/grit/generated_resources.h" +#include "content/public/browser/browser_context.h" #include "content/public/browser/browser_thread.h" +#include "extensions/browser/blob_reader.h" #include "mojo/public/cpp/bindings/binding.h" #include "ui/base/l10n/l10n_util.h" @@ -42,12 +43,13 @@ DISALLOW_COPY_AND_ASSIGN(MediaDataSourceImpl); }; -SafeMediaMetadataParser::SafeMediaMetadataParser(Profile* profile, - const std::string& blob_uuid, - int64_t blob_size, - const std::string& mime_type, - bool get_attached_images) - : profile_(profile), +SafeMediaMetadataParser::SafeMediaMetadataParser( + content::BrowserContext* browser_context, + const std::string& blob_uuid, + int64_t blob_size, + const std::string& mime_type, + bool get_attached_images) + : browser_context_(browser_context), blob_uuid_(blob_uuid), blob_size_(blob_size), mime_type_(mime_type), @@ -146,7 +148,7 @@ DCHECK_CURRENTLY_ON(content::BrowserThread::UI); BlobReader* reader = new BlobReader( // BlobReader is self-deleting. - profile_, blob_uuid_, + browser_context_, blob_uuid_, base::Bind(&SafeMediaMetadataParser::BlobReaderDoneOnUIThread, this, base::Passed(&callback))); reader->SetByteRange(position, length);
diff --git a/chrome/browser/media_galleries/fileapi/safe_media_metadata_parser.h b/chrome/browser/media_galleries/fileapi/safe_media_metadata_parser.h index 5152aa3fb..3963b545 100644 --- a/chrome/browser/media_galleries/fileapi/safe_media_metadata_parser.h +++ b/chrome/browser/media_galleries/fileapi/safe_media_metadata_parser.h
@@ -20,7 +20,9 @@ #include "chrome/common/media_galleries/metadata_types.h" #include "content/public/browser/utility_process_mojo_client.h" -class Profile; +namespace content { +class BrowserContext; +} namespace metadata { @@ -37,7 +39,7 @@ std::unique_ptr<std::vector<AttachedImage>> attached_images)> DoneCallback; - SafeMediaMetadataParser(Profile* profile, + SafeMediaMetadataParser(content::BrowserContext* browser_context, const std::string& blob_uuid, int64_t blob_size, const std::string& mime_type, @@ -87,7 +89,7 @@ std::unique_ptr<std::string> data); // All member variables are only accessed on the IO thread. - Profile* const profile_; + content::BrowserContext* const browser_context_; const std::string blob_uuid_; const int64_t blob_size_; const std::string mime_type_;
diff --git a/chrome/browser/password_manager/chrome_password_manager_client.cc b/chrome/browser/password_manager/chrome_password_manager_client.cc index 19c012e16..b6c0edbd 100644 --- a/chrome/browser/password_manager/chrome_password_manager_client.cc +++ b/chrome/browser/password_manager/chrome_password_manager_client.cc
@@ -254,7 +254,7 @@ } bool ChromePasswordManagerClient::PromptUserToSaveOrUpdatePassword( - scoped_refptr<password_manager::PasswordFormManager> form_to_save, + std::unique_ptr<password_manager::PasswordFormManager> form_to_save, bool update_password) { // Save password infobar and the password bubble prompts in case of // "webby" URLs and do not prompt in case of "non-webby" URLS (e.g. file://). @@ -374,7 +374,7 @@ } void ChromePasswordManagerClient::AutomaticPasswordSave( - scoped_refptr<password_manager::PasswordFormManager> saved_form) { + std::unique_ptr<password_manager::PasswordFormManager> saved_form) { #if defined(OS_ANDROID) GeneratedPasswordSavedInfoBarDelegateAndroid::Create(web_contents()); #else
diff --git a/chrome/browser/password_manager/chrome_password_manager_client.h b/chrome/browser/password_manager/chrome_password_manager_client.h index 017652e..9ec30cf 100644 --- a/chrome/browser/password_manager/chrome_password_manager_client.h +++ b/chrome/browser/password_manager/chrome_password_manager_client.h
@@ -10,7 +10,6 @@ #include "base/compiler_specific.h" #include "base/macros.h" -#include "base/memory/ref_counted.h" #include "components/autofill/content/common/autofill_driver.mojom.h" #include "components/password_manager/content/browser/content_password_manager_driver_factory.h" #include "components/password_manager/content/browser/credential_manager_impl.h" @@ -54,7 +53,7 @@ const HSTSCallback& callback) const override; bool OnCredentialManagerUsed() override; bool PromptUserToSaveOrUpdatePassword( - scoped_refptr<password_manager::PasswordFormManager> form_to_save, + std::unique_ptr<password_manager::PasswordFormManager> form_to_save, bool update_password) override; bool PromptUserToChooseCredentials( std::vector<std::unique_ptr<autofill::PasswordForm>> local_forms, @@ -71,7 +70,7 @@ const autofill::PasswordForm& form) override; void NotifyStorePasswordCalled() override; void AutomaticPasswordSave( - scoped_refptr<password_manager::PasswordFormManager> saved_form_manager) + std::unique_ptr<password_manager::PasswordFormManager> saved_form_manager) override; void PasswordWasAutofilled( const std::map<base::string16, const autofill::PasswordForm*>&
diff --git a/chrome/browser/password_manager/password_manager_test_base.cc b/chrome/browser/password_manager/password_manager_test_base.cc index b1f3c17f..5a5fa13 100644 --- a/chrome/browser/password_manager/password_manager_test_base.cc +++ b/chrome/browser/password_manager/password_manager_test_base.cc
@@ -65,8 +65,9 @@ private: // PasswordsClientUIDelegate: - void OnPasswordSubmitted(scoped_refptr<password_manager::PasswordFormManager> - form_manager) override; + void OnPasswordSubmitted( + std::unique_ptr<password_manager::PasswordFormManager> form_manager) + override; bool OnChooseCredentials( std::vector<std::unique_ptr<autofill::PasswordForm>> local_credentials, const GURL& origin, @@ -109,7 +110,7 @@ } void CustomManagePasswordsUIController::OnPasswordSubmitted( - scoped_refptr<password_manager::PasswordFormManager> form_manager) { + std::unique_ptr<password_manager::PasswordFormManager> form_manager) { if (target_state_ == password_manager::ui::PENDING_PASSWORD_STATE) { run_loop_->Quit(); run_loop_ = nullptr;
diff --git a/chrome/browser/password_manager/save_password_infobar_delegate_android.cc b/chrome/browser/password_manager/save_password_infobar_delegate_android.cc index 0ae082b..9e98b2a 100644 --- a/chrome/browser/password_manager/save_password_infobar_delegate_android.cc +++ b/chrome/browser/password_manager/save_password_infobar_delegate_android.cc
@@ -24,7 +24,7 @@ // static void SavePasswordInfoBarDelegate::Create( content::WebContents* web_contents, - scoped_refptr<password_manager::PasswordFormManager> form_to_save) { + std::unique_ptr<password_manager::PasswordFormManager> form_to_save) { Profile* profile = Profile::FromBrowserContext(web_contents->GetBrowserContext()); syncer::SyncService* sync_service = @@ -45,7 +45,7 @@ SavePasswordInfoBarDelegate::SavePasswordInfoBarDelegate( content::WebContents* web_contents, - scoped_refptr<password_manager::PasswordFormManager> form_to_save, + std::unique_ptr<password_manager::PasswordFormManager> form_to_save, bool is_smartlock_branding_enabled) : PasswordManagerInfoBarDelegate(), form_to_save_(std::move(form_to_save)),
diff --git a/chrome/browser/password_manager/save_password_infobar_delegate_android.h b/chrome/browser/password_manager/save_password_infobar_delegate_android.h index c6c1403..f805016 100644 --- a/chrome/browser/password_manager/save_password_infobar_delegate_android.h +++ b/chrome/browser/password_manager/save_password_infobar_delegate_android.h
@@ -8,7 +8,6 @@ #include <memory> #include "base/macros.h" -#include "base/memory/ref_counted.h" #include "base/timer/elapsed_timer.h" #include "chrome/browser/password_manager/password_manager_infobar_delegate_android.h" #include "components/infobars/core/confirm_infobar_delegate.h" @@ -33,7 +32,7 @@ // for |web_contents|. static void Create( content::WebContents* web_contents, - scoped_refptr<password_manager::PasswordFormManager> form_to_save); + std::unique_ptr<password_manager::PasswordFormManager> form_to_save); ~SavePasswordInfoBarDelegate() override; @@ -48,13 +47,13 @@ // Makes a ctor available in tests. SavePasswordInfoBarDelegate( content::WebContents* web_contents, - scoped_refptr<password_manager::PasswordFormManager> form_to_save, + std::unique_ptr<password_manager::PasswordFormManager> form_to_save, bool is_smartlock_branding_enabled); private: // The PasswordFormManager managing the form we're asking the user about, // and should update as per their decision. - scoped_refptr<password_manager::PasswordFormManager> form_to_save_; + std::unique_ptr<password_manager::PasswordFormManager> form_to_save_; // Used to track the results we get from the info bar. password_manager::metrics_util::UIDismissalReason infobar_response_;
diff --git a/chrome/browser/password_manager/save_password_infobar_delegate_android_unittest.cc b/chrome/browser/password_manager/save_password_infobar_delegate_android_unittest.cc index 8bfe74f..0ffd7a9 100644 --- a/chrome/browser/password_manager/save_password_infobar_delegate_android_unittest.cc +++ b/chrome/browser/password_manager/save_password_infobar_delegate_android_unittest.cc
@@ -45,9 +45,9 @@ base::WrapUnique(new password_manager::StubFormSaver), form_fetcher) {} - private: ~MockPasswordFormManager() override {} + private: DISALLOW_COPY_AND_ASSIGN(MockPasswordFormManager); }; @@ -55,7 +55,7 @@ public: TestSavePasswordInfobarDelegate( content::WebContents* web_contents, - scoped_refptr<password_manager::PasswordFormManager> form_to_save) + std::unique_ptr<password_manager::PasswordFormManager> form_to_save) : SavePasswordInfoBarDelegate(web_contents, std::move(form_to_save), true /* is_smartlock_branding_enabled */) {} @@ -75,12 +75,12 @@ PrefService* prefs(); const autofill::PasswordForm& test_form() { return test_form_; } - scoped_refptr<MockPasswordFormManager> CreateMockFormManager(); + std::unique_ptr<MockPasswordFormManager> CreateMockFormManager(); protected: std::unique_ptr<ConfirmInfoBarDelegate> CreateDelegate( - scoped_refptr<password_manager::PasswordFormManager> - password_form_manager); + std::unique_ptr<password_manager::PasswordFormManager> + password_form_manager); password_manager::StubPasswordManagerClient client_; password_manager::StubPasswordManagerDriver driver_; @@ -108,16 +108,16 @@ return profile->GetPrefs(); } -scoped_refptr<MockPasswordFormManager> +std::unique_ptr<MockPasswordFormManager> SavePasswordInfoBarDelegateTest::CreateMockFormManager() { - return scoped_refptr<MockPasswordFormManager>( + return std::unique_ptr<MockPasswordFormManager>( new MockPasswordFormManager(&password_manager_, &client_, driver_.AsWeakPtr(), test_form(), &fetcher_)); } std::unique_ptr<ConfirmInfoBarDelegate> SavePasswordInfoBarDelegateTest::CreateDelegate( - scoped_refptr<password_manager::PasswordFormManager> + std::unique_ptr<password_manager::PasswordFormManager> password_form_manager) { std::unique_ptr<ConfirmInfoBarDelegate> delegate( new TestSavePasswordInfobarDelegate(web_contents(), @@ -134,7 +134,7 @@ } TEST_F(SavePasswordInfoBarDelegateTest, CancelTestCredentialSourceAPI) { - scoped_refptr<MockPasswordFormManager> password_form_manager( + std::unique_ptr<MockPasswordFormManager> password_form_manager( CreateMockFormManager()); EXPECT_CALL(*password_form_manager.get(), PermanentlyBlacklist()); std::unique_ptr<ConfirmInfoBarDelegate> infobar( @@ -144,7 +144,7 @@ TEST_F(SavePasswordInfoBarDelegateTest, CancelTestCredentialSourcePasswordManager) { - scoped_refptr<MockPasswordFormManager> password_form_manager( + std::unique_ptr<MockPasswordFormManager> password_form_manager( CreateMockFormManager()); EXPECT_CALL(*password_form_manager.get(), PermanentlyBlacklist()); std::unique_ptr<ConfirmInfoBarDelegate> infobar(
diff --git a/chrome/browser/password_manager/update_password_infobar_delegate_android.cc b/chrome/browser/password_manager/update_password_infobar_delegate_android.cc index 9e6e7a5..ebc381ad 100644 --- a/chrome/browser/password_manager/update_password_infobar_delegate_android.cc +++ b/chrome/browser/password_manager/update_password_infobar_delegate_android.cc
@@ -24,7 +24,7 @@ // static void UpdatePasswordInfoBarDelegate::Create( content::WebContents* web_contents, - scoped_refptr<password_manager::PasswordFormManager> form_to_save) { + std::unique_ptr<password_manager::PasswordFormManager> form_to_save) { const bool is_smartlock_branding_enabled = password_bubble_experiment::IsSmartLockUser( ProfileSyncServiceFactory::GetForProfile( @@ -59,7 +59,7 @@ UpdatePasswordInfoBarDelegate::UpdatePasswordInfoBarDelegate( content::WebContents* web_contents, - scoped_refptr<password_manager::PasswordFormManager> form_to_update, + std::unique_ptr<password_manager::PasswordFormManager> form_to_update, bool is_smartlock_branding_enabled) : is_smartlock_branding_enabled_(is_smartlock_branding_enabled) { base::string16 message;
diff --git a/chrome/browser/password_manager/update_password_infobar_delegate_android.h b/chrome/browser/password_manager/update_password_infobar_delegate_android.h index b759f80..7bdf489 100644 --- a/chrome/browser/password_manager/update_password_infobar_delegate_android.h +++ b/chrome/browser/password_manager/update_password_infobar_delegate_android.h
@@ -9,7 +9,6 @@ #include <vector> #include "base/macros.h" -#include "base/memory/ref_counted.h" #include "chrome/browser/password_manager/password_manager_infobar_delegate_android.h" #include "chrome/browser/ui/passwords/manage_passwords_state.h" #include "components/password_manager/core/browser/password_form_manager.h" @@ -27,7 +26,7 @@ public: static void Create( content::WebContents* web_contents, - scoped_refptr<password_manager::PasswordFormManager> form_to_update); + std::unique_ptr<password_manager::PasswordFormManager> form_to_update); ~UpdatePasswordInfoBarDelegate() override; @@ -55,7 +54,7 @@ private: UpdatePasswordInfoBarDelegate( content::WebContents* web_contents, - scoped_refptr<password_manager::PasswordFormManager> form_to_update, + std::unique_ptr<password_manager::PasswordFormManager> form_to_update, bool is_smartlock_branding_enabled); // ConfirmInfoBarDelegate:
diff --git a/chrome/browser/sync_file_system/local/local_file_sync_service.cc b/chrome/browser/sync_file_system/local/local_file_sync_service.cc index 9b96290..d606cd858 100644 --- a/chrome/browser/sync_file_system/local/local_file_sync_service.cc +++ b/chrome/browser/sync_file_system/local/local_file_sync_service.cc
@@ -8,7 +8,6 @@ #include "base/single_thread_task_runner.h" #include "base/stl_util.h" #include "base/threading/thread_task_runner_handle.h" -#include "chrome/browser/extensions/extension_util.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/sync_file_system/file_change.h" #include "chrome/browser/sync_file_system/local/local_file_change_tracker.h" @@ -22,6 +21,7 @@ #include "content/public/browser/site_instance.h" #include "content/public/browser/storage_partition.h" #include "extensions/browser/extension_registry.h" +#include "extensions/browser/extension_util.h" #include "extensions/common/extension_set.h" #include "storage/browser/blob/scoped_file.h" #include "storage/browser/fileapi/file_system_context.h"
diff --git a/chrome/browser/ui/android/tab_model/tab_model_list_unittest.cc b/chrome/browser/ui/android/tab_model/tab_model_list_unittest.cc index 653d3f19..44c0215 100644 --- a/chrome/browser/ui/android/tab_model/tab_model_list_unittest.cc +++ b/chrome/browser/ui/android/tab_model/tab_model_list_unittest.cc
@@ -11,7 +11,6 @@ namespace { class TabModelListTest : public ChromeRenderViewHostTestHarness {}; -} // namespace class TestTabModel : public TabModel { public: @@ -37,6 +36,7 @@ // A fake value for the current number of tabs. int tab_count_; }; +} // namespace // Regression test for http://crbug.com/432685. TEST_F(TabModelListTest, TestGetTabModelForWebContents) {
diff --git a/chrome/browser/ui/android/tab_model/tab_model_unittest.cc b/chrome/browser/ui/android/tab_model/tab_model_unittest.cc index 8329591..a42a1219 100644 --- a/chrome/browser/ui/android/tab_model/tab_model_unittest.cc +++ b/chrome/browser/ui/android/tab_model/tab_model_unittest.cc
@@ -25,7 +25,6 @@ MOCK_METHOD0(GetOffTheRecordProfile, Profile*()); MOCK_METHOD0(HasOffTheRecordProfile, bool()); }; -} // namespace class TestTabModel : public TabModel { public: @@ -47,6 +46,7 @@ void SetActiveIndex(int index) override {} void CloseTabAt(int index) override {} }; +} // namespace TEST_F(TabModelTest, TestProfileHandling) { // Construct TabModel with standard Profile.
diff --git a/chrome/browser/ui/passwords/manage_passwords_state.cc b/chrome/browser/ui/passwords/manage_passwords_state.cc index 81e1421..b99c9fca 100644 --- a/chrome/browser/ui/passwords/manage_passwords_state.cc +++ b/chrome/browser/ui/passwords/manage_passwords_state.cc
@@ -80,7 +80,7 @@ ManagePasswordsState::~ManagePasswordsState() {} void ManagePasswordsState::OnPendingPassword( - scoped_refptr<password_manager::PasswordFormManager> form_manager) { + std::unique_ptr<password_manager::PasswordFormManager> form_manager) { ClearData(); form_manager_ = std::move(form_manager); local_credentials_forms_ = @@ -92,7 +92,7 @@ } void ManagePasswordsState::OnUpdatePassword( - scoped_refptr<password_manager::PasswordFormManager> form_manager) { + std::unique_ptr<password_manager::PasswordFormManager> form_manager) { ClearData(); form_manager_ = std::move(form_manager); local_credentials_forms_ = @@ -123,7 +123,7 @@ } void ManagePasswordsState::OnAutomaticPasswordSave( - scoped_refptr<PasswordFormManager> form_manager) { + std::unique_ptr<PasswordFormManager> form_manager) { ClearData(); form_manager_ = std::move(form_manager); local_credentials_forms_.reserve(form_manager_->best_matches().size()); @@ -222,7 +222,7 @@ } void ManagePasswordsState::ClearData() { - form_manager_ = nullptr; + form_manager_.reset(); local_credentials_forms_.clear(); credentials_callback_.Reset(); }
diff --git a/chrome/browser/ui/passwords/manage_passwords_state.h b/chrome/browser/ui/passwords/manage_passwords_state.h index 03a7a1b6..62de544 100644 --- a/chrome/browser/ui/passwords/manage_passwords_state.h +++ b/chrome/browser/ui/passwords/manage_passwords_state.h
@@ -11,7 +11,6 @@ #include "base/callback.h" #include "base/macros.h" -#include "base/memory/ref_counted.h" #include "base/strings/string16.h" #include "components/autofill/core/common/password_form.h" #include "components/password_manager/core/browser/password_store_change.h" @@ -45,11 +44,11 @@ // Move to PENDING_PASSWORD_STATE. void OnPendingPassword( - scoped_refptr<password_manager::PasswordFormManager> form_manager); + std::unique_ptr<password_manager::PasswordFormManager> form_manager); // Move to PENDING_PASSWORD_UPDATE_STATE. void OnUpdatePassword( - scoped_refptr<password_manager::PasswordFormManager> form_manager); + std::unique_ptr<password_manager::PasswordFormManager> form_manager); // Move to CREDENTIAL_REQUEST_STATE. void OnRequestCredentials( @@ -63,7 +62,7 @@ // Move to CONFIRMATION_STATE. void OnAutomaticPasswordSave( - scoped_refptr<password_manager::PasswordFormManager> form_manager); + std::unique_ptr<password_manager::PasswordFormManager> form_manager); // Move to MANAGE_STATE or INACTIVE_STATE for PSL matched passwords. // |password_form_map| contains best matches from the password store for the @@ -128,7 +127,7 @@ GURL origin_; // Contains the password that was submitted. - scoped_refptr<password_manager::PasswordFormManager> form_manager_; + std::unique_ptr<password_manager::PasswordFormManager> form_manager_; // Contains all the current forms. std::vector<std::unique_ptr<autofill::PasswordForm>> local_credentials_forms_;
diff --git a/chrome/browser/ui/passwords/manage_passwords_state_unittest.cc b/chrome/browser/ui/passwords/manage_passwords_state_unittest.cc index 9b989a7..de13dcf5 100644 --- a/chrome/browser/ui/passwords/manage_passwords_state_unittest.cc +++ b/chrome/browser/ui/passwords/manage_passwords_state_unittest.cc
@@ -86,11 +86,11 @@ // Returns a PasswordFormManager containing |test_stored_forms_| as the best // matches. - scoped_refptr<password_manager::PasswordFormManager> CreateFormManager(); + std::unique_ptr<password_manager::PasswordFormManager> CreateFormManager(); // Returns a PasswordFormManager containing test_local_federated_form() as a // stored federated credential. - scoped_refptr<password_manager::PasswordFormManager> + std::unique_ptr<password_manager::PasswordFormManager> CreateFormManagerWithFederation(); // Pushes irrelevant updates to |passwords_data_| and checks that they don't @@ -107,7 +107,7 @@ private: // Implements both CreateFormManager and CreateFormManagerWithFederation. - scoped_refptr<password_manager::PasswordFormManager> + std::unique_ptr<password_manager::PasswordFormManager> CreateFormManagerInternal(bool include_federated); password_manager::StubPasswordManagerClient stub_client_; @@ -123,19 +123,19 @@ std::vector<const autofill::PasswordForm*> test_stored_forms_; }; -scoped_refptr<password_manager::PasswordFormManager> +std::unique_ptr<password_manager::PasswordFormManager> ManagePasswordsStateTest::CreateFormManager() { return CreateFormManagerInternal(false); } -scoped_refptr<password_manager::PasswordFormManager> +std::unique_ptr<password_manager::PasswordFormManager> ManagePasswordsStateTest::CreateFormManagerWithFederation() { return CreateFormManagerInternal(true); } -scoped_refptr<password_manager::PasswordFormManager> +std::unique_ptr<password_manager::PasswordFormManager> ManagePasswordsStateTest::CreateFormManagerInternal(bool include_federated) { - scoped_refptr<password_manager::PasswordFormManager> test_form_manager( + std::unique_ptr<password_manager::PasswordFormManager> test_form_manager( new password_manager::PasswordFormManager( &password_manager_, &stub_client_, driver_.AsWeakPtr(), test_local_form(), @@ -271,7 +271,7 @@ TEST_F(ManagePasswordsStateTest, PasswordSubmitted) { test_stored_forms().push_back(&test_local_form()); test_stored_forms().push_back(&test_psl_form()); - scoped_refptr<password_manager::PasswordFormManager> test_form_manager( + std::unique_ptr<password_manager::PasswordFormManager> test_form_manager( CreateFormManager()); test_form_manager->ProvisionallySave( test_submitted_form(), @@ -291,7 +291,7 @@ TEST_F(ManagePasswordsStateTest, PasswordSaved) { test_stored_forms().push_back(&test_local_form()); - scoped_refptr<password_manager::PasswordFormManager> test_form_manager( + std::unique_ptr<password_manager::PasswordFormManager> test_form_manager( CreateFormManager()); test_form_manager->ProvisionallySave( test_submitted_form(), @@ -310,7 +310,7 @@ } TEST_F(ManagePasswordsStateTest, PasswordSubmittedFederationsPresent) { - scoped_refptr<password_manager::PasswordFormManager> test_form_manager( + std::unique_ptr<password_manager::PasswordFormManager> test_form_manager( CreateFormManagerWithFederation()); test_form_manager->ProvisionallySave( test_submitted_form(), @@ -366,7 +366,7 @@ TEST_F(ManagePasswordsStateTest, AutomaticPasswordSave) { test_stored_forms().push_back(&test_psl_form()); - scoped_refptr<password_manager::PasswordFormManager> test_form_manager( + std::unique_ptr<password_manager::PasswordFormManager> test_form_manager( CreateFormManager()); test_form_manager->ProvisionallySave( test_submitted_form(), @@ -389,7 +389,7 @@ } TEST_F(ManagePasswordsStateTest, AutomaticPasswordSaveWithFederations) { - scoped_refptr<password_manager::PasswordFormManager> test_form_manager( + std::unique_ptr<password_manager::PasswordFormManager> test_form_manager( CreateFormManagerWithFederation()); test_form_manager->ProvisionallySave( test_submitted_form(), @@ -462,7 +462,7 @@ } TEST_F(ManagePasswordsStateTest, OnInactive) { - scoped_refptr<password_manager::PasswordFormManager> test_form_manager( + std::unique_ptr<password_manager::PasswordFormManager> test_form_manager( CreateFormManager()); test_form_manager->ProvisionallySave( test_submitted_form(), @@ -479,7 +479,7 @@ } TEST_F(ManagePasswordsStateTest, PendingPasswordAddBlacklisted) { - scoped_refptr<password_manager::PasswordFormManager> test_form_manager( + std::unique_ptr<password_manager::PasswordFormManager> test_form_manager( CreateFormManager()); test_form_manager->ProvisionallySave( test_submitted_form(), @@ -515,7 +515,7 @@ } TEST_F(ManagePasswordsStateTest, AutomaticPasswordSaveAddBlacklisted) { - scoped_refptr<password_manager::PasswordFormManager> test_form_manager( + std::unique_ptr<password_manager::PasswordFormManager> test_form_manager( CreateFormManager()); test_form_manager->ProvisionallySave( test_submitted_form(), @@ -538,7 +538,7 @@ } TEST_F(ManagePasswordsStateTest, PasswordUpdateAddBlacklisted) { - scoped_refptr<password_manager::PasswordFormManager> test_form_manager( + std::unique_ptr<password_manager::PasswordFormManager> test_form_manager( CreateFormManager()); test_form_manager->ProvisionallySave( test_submitted_form(), @@ -553,7 +553,7 @@ TEST_F(ManagePasswordsStateTest, PasswordUpdateSubmitted) { test_stored_forms().push_back(&test_local_form()); test_stored_forms().push_back(&test_psl_form()); - scoped_refptr<password_manager::PasswordFormManager> test_form_manager( + std::unique_ptr<password_manager::PasswordFormManager> test_form_manager( CreateFormManager()); test_form_manager->ProvisionallySave( test_submitted_form(), @@ -578,7 +578,7 @@ android_form.username_value = test_submitted_form().username_value; android_form.password_value = base::ASCIIToUTF16("old pass"); test_stored_forms().push_back(&android_form); - scoped_refptr<password_manager::PasswordFormManager> test_form_manager( + std::unique_ptr<password_manager::PasswordFormManager> test_form_manager( CreateFormManager()); test_form_manager->ProvisionallySave( test_submitted_form(), @@ -599,7 +599,7 @@ TEST_F(ManagePasswordsStateTest, PasswordUpdateSubmittedWithFederations) { test_stored_forms().push_back(&test_local_form()); - scoped_refptr<password_manager::PasswordFormManager> test_form_manager( + std::unique_ptr<password_manager::PasswordFormManager> test_form_manager( CreateFormManagerWithFederation()); test_form_manager->ProvisionallySave( test_submitted_form(),
diff --git a/chrome/browser/ui/passwords/manage_passwords_test.cc b/chrome/browser/ui/passwords/manage_passwords_test.cc index 5970331..6e3ff50b 100644 --- a/chrome/browser/ui/passwords/manage_passwords_test.cc +++ b/chrome/browser/ui/passwords/manage_passwords_test.cc
@@ -9,7 +9,6 @@ #include "base/bind.h" #include "base/memory/ptr_util.h" -#include "base/memory/ref_counted.h" #include "base/strings/string16.h" #include "base/strings/utf_string_conversions.h" #include "chrome/app/chrome_command_ids.h" @@ -68,7 +67,7 @@ } void ManagePasswordsTest::SetupPendingPassword() { - scoped_refptr<password_manager::PasswordFormManager> test_form_manager( + std::unique_ptr<password_manager::PasswordFormManager> test_form_manager( new password_manager::PasswordFormManager( nullptr, &client_, driver_.AsWeakPtr(), *test_form(), base::WrapUnique(new password_manager::StubFormSaver), &fetcher_)); @@ -77,7 +76,7 @@ } void ManagePasswordsTest::SetupAutomaticPassword() { - scoped_refptr<password_manager::PasswordFormManager> test_form_manager( + std::unique_ptr<password_manager::PasswordFormManager> test_form_manager( new password_manager::PasswordFormManager( nullptr, &client_, driver_.AsWeakPtr(), *test_form(), base::WrapUnique(new password_manager::StubFormSaver), &fetcher_));
diff --git a/chrome/browser/ui/passwords/manage_passwords_ui_controller.cc b/chrome/browser/ui/passwords/manage_passwords_ui_controller.cc index a73c046..25c5cf770 100644 --- a/chrome/browser/ui/passwords/manage_passwords_ui_controller.cc +++ b/chrome/browser/ui/passwords/manage_passwords_ui_controller.cc
@@ -69,7 +69,7 @@ ManagePasswordsUIController::~ManagePasswordsUIController() {} void ManagePasswordsUIController::OnPasswordSubmitted( - scoped_refptr<PasswordFormManager> form_manager) { + std::unique_ptr<PasswordFormManager> form_manager) { bool show_bubble = !form_manager->IsBlacklisted(); DestroyAccountChooser(); passwords_data_.OnPendingPassword(std::move(form_manager)); @@ -87,7 +87,7 @@ } void ManagePasswordsUIController::OnUpdatePasswordSubmitted( - scoped_refptr<PasswordFormManager> form_manager) { + std::unique_ptr<PasswordFormManager> form_manager) { DestroyAccountChooser(); passwords_data_.OnUpdatePassword(std::move(form_manager)); bubble_status_ = SHOULD_POP_UP; @@ -142,7 +142,7 @@ } void ManagePasswordsUIController::OnAutomaticPasswordSave( - scoped_refptr<PasswordFormManager> form_manager) { + std::unique_ptr<PasswordFormManager> form_manager) { DestroyAccountChooser(); passwords_data_.OnAutomaticPasswordSave(std::move(form_manager)); bubble_status_ = SHOULD_POP_UP;
diff --git a/chrome/browser/ui/passwords/manage_passwords_ui_controller.h b/chrome/browser/ui/passwords/manage_passwords_ui_controller.h index 4408e02..dfcfa146 100644 --- a/chrome/browser/ui/passwords/manage_passwords_ui_controller.h +++ b/chrome/browser/ui/passwords/manage_passwords_ui_controller.h
@@ -9,7 +9,6 @@ #include <vector> #include "base/macros.h" -#include "base/memory/ref_counted.h" #include "chrome/browser/ui/passwords/manage_passwords_state.h" #include "chrome/browser/ui/passwords/passwords_client_ui_delegate.h" #include "chrome/browser/ui/passwords/passwords_model_delegate.h" @@ -45,10 +44,11 @@ ~ManagePasswordsUIController() override; // PasswordsClientUIDelegate: - void OnPasswordSubmitted(scoped_refptr<password_manager::PasswordFormManager> - form_manager) override; + void OnPasswordSubmitted( + std::unique_ptr<password_manager::PasswordFormManager> form_manager) + override; void OnUpdatePasswordSubmitted( - scoped_refptr<password_manager::PasswordFormManager> form_manager) + std::unique_ptr<password_manager::PasswordFormManager> form_manager) override; bool OnChooseCredentials( std::vector<std::unique_ptr<autofill::PasswordForm>> local_credentials, @@ -59,7 +59,7 @@ const GURL& origin) override; void OnPromptEnableAutoSignin() override; void OnAutomaticPasswordSave( - scoped_refptr<password_manager::PasswordFormManager> form_manager) + std::unique_ptr<password_manager::PasswordFormManager> form_manager) override; void OnPasswordAutofilled( const std::map<base::string16, const autofill::PasswordForm*>&
diff --git a/chrome/browser/ui/passwords/manage_passwords_ui_controller_unittest.cc b/chrome/browser/ui/passwords/manage_passwords_ui_controller_unittest.cc index a48451f..2bf5bbf 100644 --- a/chrome/browser/ui/passwords/manage_passwords_ui_controller_unittest.cc +++ b/chrome/browser/ui/passwords/manage_passwords_ui_controller_unittest.cc
@@ -180,12 +180,12 @@ void ExpectIconStateIs(password_manager::ui::State state); void ExpectIconAndControllerStateIs(password_manager::ui::State state); - scoped_refptr<password_manager::PasswordFormManager> + std::unique_ptr<password_manager::PasswordFormManager> CreateFormManagerWithBestMatches( const autofill::PasswordForm& observed_form, const std::vector<const autofill::PasswordForm*>& best_matches); - scoped_refptr<password_manager::PasswordFormManager> CreateFormManager(); + std::unique_ptr<password_manager::PasswordFormManager> CreateFormManager(); // Tests that the state is not changed when the password is autofilled. void TestNotChangingStateOnAutofill( @@ -241,11 +241,11 @@ EXPECT_EQ(state, controller()->GetState()); } -scoped_refptr<password_manager::PasswordFormManager> +std::unique_ptr<password_manager::PasswordFormManager> ManagePasswordsUIControllerTest::CreateFormManagerWithBestMatches( const autofill::PasswordForm& observed_form, const std::vector<const autofill::PasswordForm*>& best_matches) { - scoped_refptr<password_manager::PasswordFormManager> test_form_manager( + std::unique_ptr<password_manager::PasswordFormManager> test_form_manager( new password_manager::PasswordFormManager( &password_manager_, &client_, driver_.AsWeakPtr(), observed_form, base::WrapUnique(new password_manager::StubFormSaver), &fetcher_)); @@ -253,7 +253,7 @@ return test_form_manager; } -scoped_refptr<password_manager::PasswordFormManager> +std::unique_ptr<password_manager::PasswordFormManager> ManagePasswordsUIControllerTest::CreateFormManager() { return CreateFormManagerWithBestMatches(test_local_form(), {&test_local_form()}); @@ -266,7 +266,7 @@ state == password_manager::ui::CONFIRMATION_STATE); // Set the bubble state to |state|. - scoped_refptr<password_manager::PasswordFormManager> test_form_manager( + std::unique_ptr<password_manager::PasswordFormManager> test_form_manager( CreateFormManager()); test_form_manager->ProvisionallySave( test_local_form(), @@ -318,7 +318,7 @@ } TEST_F(ManagePasswordsUIControllerTest, PasswordSubmitted) { - scoped_refptr<password_manager::PasswordFormManager> test_form_manager( + std::unique_ptr<password_manager::PasswordFormManager> test_form_manager( CreateFormManager()); test_form_manager->ProvisionallySave( test_local_form(), @@ -338,7 +338,7 @@ blacklisted.origin = test_local_form().origin; blacklisted.signon_realm = blacklisted.origin.spec(); blacklisted.blacklisted_by_user = true; - scoped_refptr<password_manager::PasswordFormManager> test_form_manager = + std::unique_ptr<password_manager::PasswordFormManager> test_form_manager = CreateFormManagerWithBestMatches(test_local_form(), {&blacklisted}); EXPECT_CALL(*controller(), OnUpdateBubbleAndIconVisibility()); controller()->OnPasswordSubmitted(std::move(test_form_manager)); @@ -351,7 +351,7 @@ TEST_F(ManagePasswordsUIControllerTest, PasswordSubmittedBubbleSuppressed) { CreateSmartBubbleFieldTrial(); - scoped_refptr<password_manager::PasswordFormManager> test_form_manager( + std::unique_ptr<password_manager::PasswordFormManager> test_form_manager( CreateFormManager()); std::vector<password_manager::InteractionsStats> stats(1); stats[0].origin_domain = test_local_form().origin.GetOrigin(); @@ -375,7 +375,7 @@ TEST_F(ManagePasswordsUIControllerTest, PasswordSubmittedBubbleNotSuppressed) { CreateSmartBubbleFieldTrial(); - scoped_refptr<password_manager::PasswordFormManager> test_form_manager( + std::unique_ptr<password_manager::PasswordFormManager> test_form_manager( CreateFormManager()); std::vector<password_manager::InteractionsStats> stats(1); stats[0].origin_domain = test_local_form().origin.GetOrigin(); @@ -397,7 +397,7 @@ } TEST_F(ManagePasswordsUIControllerTest, PasswordSaved) { - scoped_refptr<password_manager::PasswordFormManager> test_form_manager( + std::unique_ptr<password_manager::PasswordFormManager> test_form_manager( CreateFormManager()); test_form_manager->ProvisionallySave( test_local_form(), @@ -410,7 +410,7 @@ } TEST_F(ManagePasswordsUIControllerTest, PasswordBlacklisted) { - scoped_refptr<password_manager::PasswordFormManager> test_form_manager( + std::unique_ptr<password_manager::PasswordFormManager> test_form_manager( CreateFormManager()); test_form_manager->ProvisionallySave( test_local_form(), @@ -423,7 +423,7 @@ } TEST_F(ManagePasswordsUIControllerTest, NormalNavigations) { - scoped_refptr<password_manager::PasswordFormManager> test_form_manager( + std::unique_ptr<password_manager::PasswordFormManager> test_form_manager( CreateFormManager()); EXPECT_CALL(*controller(), OnUpdateBubbleAndIconVisibility()); controller()->OnPasswordSubmitted(std::move(test_form_manager)); @@ -442,7 +442,7 @@ } TEST_F(ManagePasswordsUIControllerTest, NormalNavigationsClosedBubble) { - scoped_refptr<password_manager::PasswordFormManager> test_form_manager( + std::unique_ptr<password_manager::PasswordFormManager> test_form_manager( CreateFormManager()); EXPECT_CALL(*controller(), OnUpdateBubbleAndIconVisibility()); controller()->OnPasswordSubmitted(std::move(test_form_manager)); @@ -467,7 +467,7 @@ content::WebContentsTester::For(web_contents()) ->NavigateAndCommit(GURL("chrome://sign-in")); - scoped_refptr<password_manager::PasswordFormManager> test_form_manager( + std::unique_ptr<password_manager::PasswordFormManager> test_form_manager( CreateFormManager()); test_form_manager->ProvisionallySave( test_local_form(), @@ -500,7 +500,7 @@ } TEST_F(ManagePasswordsUIControllerTest, AutomaticPasswordSave) { - scoped_refptr<password_manager::PasswordFormManager> test_form_manager( + std::unique_ptr<password_manager::PasswordFormManager> test_form_manager( CreateFormManager()); EXPECT_CALL(*controller(), OnUpdateBubbleAndIconVisibility()); controller()->OnAutomaticPasswordSave(std::move(test_form_manager)); @@ -744,7 +744,7 @@ } TEST_F(ManagePasswordsUIControllerTest, UpdatePasswordSubmitted) { - scoped_refptr<password_manager::PasswordFormManager> test_form_manager( + std::unique_ptr<password_manager::PasswordFormManager> test_form_manager( CreateFormManager()); EXPECT_CALL(*controller(), OnUpdateBubbleAndIconVisibility()); controller()->OnUpdatePasswordSubmitted(std::move(test_form_manager)); @@ -755,7 +755,7 @@ } TEST_F(ManagePasswordsUIControllerTest, PasswordUpdated) { - scoped_refptr<password_manager::PasswordFormManager> test_form_manager( + std::unique_ptr<password_manager::PasswordFormManager> test_form_manager( CreateFormManager()); test_form_manager->ProvisionallySave( test_local_form(),
diff --git a/chrome/browser/ui/passwords/passwords_client_ui_delegate.h b/chrome/browser/ui/passwords/passwords_client_ui_delegate.h index 2174249..b2b5928 100644 --- a/chrome/browser/ui/passwords/passwords_client_ui_delegate.h +++ b/chrome/browser/ui/passwords/passwords_client_ui_delegate.h
@@ -10,7 +10,6 @@ #include <vector> #include "base/callback.h" -#include "base/memory/ref_counted.h" #include "base/strings/string16.h" #include "components/autofill/core/common/password_form.h" @@ -31,13 +30,13 @@ // This stores the provided object and triggers the UI to prompt the user // about whether they would like to save the password. virtual void OnPasswordSubmitted( - scoped_refptr<password_manager::PasswordFormManager> form_manager) = 0; + std::unique_ptr<password_manager::PasswordFormManager> form_manager) = 0; // Called when the user submits a new password for an existing credential. // This stores the provided object and triggers the UI to prompt the user // about whether they would like to update the password. virtual void OnUpdatePasswordSubmitted( - scoped_refptr<password_manager::PasswordFormManager> form_manager) = 0; + std::unique_ptr<password_manager::PasswordFormManager> form_manager) = 0; // Called when the site asks user to choose from credentials. This triggers // the UI to prompt the user. |local_credentials| shouldn't be empty. |origin| @@ -62,7 +61,7 @@ // Called when the password will be saved automatically, but we still wish to // visually inform the user that the save has occured. virtual void OnAutomaticPasswordSave( - scoped_refptr<password_manager::PasswordFormManager> form_manager) = 0; + std::unique_ptr<password_manager::PasswordFormManager> form_manager) = 0; // Called when a form is autofilled with login information, so we can manage // password credentials for the current site which are stored in
diff --git a/components/password_manager/content/browser/credential_manager_impl.cc b/components/password_manager/content/browser/credential_manager_impl.cc index 9d903e7..608ccbb 100644 --- a/components/password_manager/content/browser/credential_manager_impl.cc +++ b/components/password_manager/content/browser/credential_manager_impl.cc
@@ -83,7 +83,7 @@ // is only available on HTTPS origins. auto form_fetcher = base::MakeUnique<FormFetcherImpl>( PasswordStore::FormDigest(*observed_form), client_, false, false); - form_manager_ = base::MakeRefCounted<CredentialManagerPasswordFormManager>( + form_manager_ = base::MakeUnique<CredentialManagerPasswordFormManager>( client_, GetDriver(), *observed_form, std::move(form), this, nullptr, std::move(form_fetcher)); }
diff --git a/components/password_manager/content/browser/credential_manager_impl.h b/components/password_manager/content/browser/credential_manager_impl.h index dd8acbe..6db0b99 100644 --- a/components/password_manager/content/browser/credential_manager_impl.h +++ b/components/password_manager/content/browser/credential_manager_impl.h
@@ -9,7 +9,6 @@ #include "base/callback.h" #include "base/macros.h" -#include "base/memory/ref_counted.h" #include "base/memory/weak_ptr.h" #include "components/password_manager/content/common/credential_manager.mojom.h" #include "components/password_manager/core/browser/credential_manager_password_form_manager.h" @@ -85,7 +84,7 @@ virtual base::WeakPtr<PasswordManagerDriver> GetDriver(); PasswordManagerClient* client_; - scoped_refptr<CredentialManagerPasswordFormManager> form_manager_; + std::unique_ptr<CredentialManagerPasswordFormManager> form_manager_; // Set to false to disable automatic signing in. BooleanPrefMember auto_signin_enabled_;
diff --git a/components/password_manager/content/browser/credential_manager_impl_unittest.cc b/components/password_manager/content/browser/credential_manager_impl_unittest.cc index 5feb29ed..0e7a132f 100644 --- a/components/password_manager/content/browser/credential_manager_impl_unittest.cc +++ b/components/password_manager/content/browser/credential_manager_impl_unittest.cc
@@ -81,7 +81,7 @@ ~MockPasswordManagerClient() override {} bool PromptUserToSaveOrUpdatePassword( - scoped_refptr<PasswordFormManager> manager, + std::unique_ptr<PasswordFormManager> manager, bool update_password) override { manager_.swap(manager); PromptUserToSavePasswordPtr(manager_.get()); @@ -136,7 +136,7 @@ private: TestingPrefServiceSimple prefs_; PasswordStore* store_; - scoped_refptr<PasswordFormManager> manager_; + std::unique_ptr<PasswordFormManager> manager_; DISALLOW_COPY_AND_ASSIGN(MockPasswordManagerClient); };
diff --git a/components/password_manager/core/browser/credential_manager_password_form_manager.cc b/components/password_manager/core/browser/credential_manager_password_form_manager.cc index ffdeb11a..4406d19 100644 --- a/components/password_manager/core/browser/credential_manager_password_form_manager.cc +++ b/components/password_manager/core/browser/credential_manager_password_form_manager.cc
@@ -45,6 +45,9 @@ GrabFetcher(std::move(form_fetcher)); } +CredentialManagerPasswordFormManager::~CredentialManagerPasswordFormManager() { +} + void CredentialManagerPasswordFormManager::ProcessMatches( const std::vector<const PasswordForm*>& non_federated, size_t filtered_count) { @@ -65,8 +68,6 @@ weak_factory_.GetWeakPtr())); } -CredentialManagerPasswordFormManager::~CredentialManagerPasswordFormManager() {} - void CredentialManagerPasswordFormManager::NotifyDelegate() { delegate_->OnProvisionalSaveComplete(); }
diff --git a/components/password_manager/core/browser/credential_manager_password_form_manager.h b/components/password_manager/core/browser/credential_manager_password_form_manager.h index 556bb18..4816e17 100644 --- a/components/password_manager/core/browser/credential_manager_password_form_manager.h +++ b/components/password_manager/core/browser/credential_manager_password_form_manager.h
@@ -6,7 +6,6 @@ #define COMPONENTS_PASSWORD_MANAGER_CORE_BROWSER_CREDENTIAL_MANAGER_PASSWORD_FORM_MANAGER_H_ #include "base/macros.h" -#include "base/memory/ref_counted.h" #include "base/memory/weak_ptr.h" #include "components/password_manager/core/browser/password_form_manager.h" @@ -47,14 +46,12 @@ CredentialManagerPasswordFormManagerDelegate* delegate, std::unique_ptr<FormSaver> form_saver, std::unique_ptr<FormFetcher> form_fetcher); + ~CredentialManagerPasswordFormManager() override; void ProcessMatches( const std::vector<const autofill::PasswordForm*>& non_federated, size_t filtered_count) override; - protected: - ~CredentialManagerPasswordFormManager() override; - private: // Calls OnProvisionalSaveComplete on |delegate_|. void NotifyDelegate();
diff --git a/components/password_manager/core/browser/credential_manager_password_form_manager_unittest.cc b/components/password_manager/core/browser/credential_manager_password_form_manager_unittest.cc index df684b27..88caa117 100644 --- a/components/password_manager/core/browser/credential_manager_password_form_manager_unittest.cc +++ b/components/password_manager/core/browser/credential_manager_password_form_manager_unittest.cc
@@ -50,14 +50,12 @@ TEST_F(CredentialManagerPasswordFormManagerTest, AbortEarly) { PasswordForm observed_form; MockDelegate delegate; - auto form_manager = - base::MakeRefCounted<CredentialManagerPasswordFormManager>( - &client_, driver_.AsWeakPtr(), observed_form, - base::MakeUnique<PasswordForm>(observed_form), &delegate, - base::MakeUnique<StubFormSaver>(), - base::MakeUnique<FakeFormFetcher>()); + auto form_manager = base::MakeUnique<CredentialManagerPasswordFormManager>( + &client_, driver_.AsWeakPtr(), observed_form, + base::MakeUnique<PasswordForm>(observed_form), &delegate, + base::MakeUnique<StubFormSaver>(), base::MakeUnique<FakeFormFetcher>()); - auto deleter = [&form_manager]() { form_manager = nullptr; }; + auto deleter = [&form_manager]() { form_manager.reset(); }; // Simulate that the PasswordStore responded to the FormFetcher. As a result, // |form_manager| should call the delegate's OnProvisionalSaveComplete, which
diff --git a/components/password_manager/core/browser/password_form_manager.h b/components/password_manager/core/browser/password_form_manager.h index 932fb67c..2bc3bb2 100644 --- a/components/password_manager/core/browser/password_form_manager.h +++ b/components/password_manager/core/browser/password_form_manager.h
@@ -13,7 +13,6 @@ #include <vector> #include "base/macros.h" -#include "base/memory/ref_counted.h" #include "base/memory/weak_ptr.h" #include "base/optional.h" #include "base/strings/string16.h" @@ -39,8 +38,7 @@ // This class helps with filling the observed form (both HTML and from HTTP // auth) and with saving/updating the stored information about it. -class PasswordFormManager : public FormFetcher::Consumer, - public base::RefCounted<PasswordFormManager> { +class PasswordFormManager : public FormFetcher::Consumer { public: // |password_manager| owns |this|, |client| and |driver| serve to // communicate with embedder, |observed_form| is the associated form |this| @@ -58,6 +56,7 @@ const autofill::PasswordForm& observed_form, std::unique_ptr<FormSaver> form_saver, FormFetcher* form_fetcher); + ~PasswordFormManager() override; // Flags describing the result of comparing two forms as performed by // DoesMatch. Individual flags are only relevant for HTML forms, but @@ -256,16 +255,12 @@ void GrabFetcher(std::unique_ptr<FormFetcher> fetcher); protected: - ~PasswordFormManager() override; - // FormFetcher::Consumer: void ProcessMatches( const std::vector<const autofill::PasswordForm*>& non_federated, size_t filtered_count) override; private: - friend class base::RefCounted<PasswordFormManager>; - // ManagerAction - What does the manager do with this form? Either it // fills it, or it doesn't. If it doesn't fill it, that's either // because it has no match or it is disabled via the AUTOCOMPLETE=off
diff --git a/components/password_manager/core/browser/password_form_manager_unittest.cc b/components/password_manager/core/browser/password_form_manager_unittest.cc index ebef05d..e4ed9f70 100644 --- a/components/password_manager/core/browser/password_form_manager_unittest.cc +++ b/components/password_manager/core/browser/password_form_manager_unittest.cc
@@ -387,9 +387,9 @@ saved_match_.form_data.fields.push_back(field); password_manager_.reset(new PasswordManager(&client_)); - form_manager_ = base::MakeRefCounted<PasswordFormManager>( + form_manager_.reset(new PasswordFormManager( password_manager_.get(), &client_, client_.driver(), observed_form_, - base::MakeUnique<NiceMock<MockFormSaver>>(), &fake_form_fetcher_); + base::MakeUnique<NiceMock<MockFormSaver>>(), &fake_form_fetcher_)); } // Save saved_match() for observed_form() where |observed_form_data|, @@ -406,10 +406,9 @@ FakeFormFetcher fetcher; fetcher.Fetch(); - scoped_refptr<PasswordFormManager> form_manager( - base::MakeRefCounted<PasswordFormManager>( - password_manager(), client(), client()->driver(), form, - base::MakeUnique<NiceMock<MockFormSaver>>(), &fetcher)); + PasswordFormManager form_manager( + password_manager(), client(), client()->driver(), form, + base::MakeUnique<NiceMock<MockFormSaver>>(), &fetcher); PasswordForm match = CreateSavedMatch(false); match.generation_upload_status = status; match.times_used = times_used; @@ -438,8 +437,8 @@ if (field_type) { // Show the password generation popup to check that the generation vote // would be ignored. - form_manager->set_generation_element(saved_match()->password_element); - form_manager->set_generation_popup_was_shown(true); + form_manager.set_generation_element(saved_match()->password_element); + form_manager.set_generation_popup_was_shown(true); expect_generation_vote = *field_type != autofill::ACCOUNT_CREATION_PASSWORD; @@ -460,9 +459,9 @@ StartUploadRequest(_, _, _, _, _)) .Times(0); } - form_manager->ProvisionallySave( + form_manager.ProvisionallySave( form_to_save, PasswordFormManager::IGNORE_OTHER_POSSIBLE_USERNAMES); - form_manager->Save(); + form_manager.Save(); Mock::VerifyAndClearExpectations( client()->mock_driver()->mock_autofill_download_manager()); } @@ -496,10 +495,9 @@ FakeFormFetcher fetcher; fetcher.Fetch(); - scoped_refptr<PasswordFormManager> form_manager( - base::MakeRefCounted<PasswordFormManager>( - password_manager(), client(), client()->driver(), *observed_form(), - base::MakeUnique<NiceMock<MockFormSaver>>(), &fetcher)); + PasswordFormManager form_manager( + password_manager(), client(), client()->driver(), *observed_form(), + base::MakeUnique<NiceMock<MockFormSaver>>(), &fetcher); fetcher.SetNonFederated({saved_match()}, 0u); // User submits current and new credentials to the observed form. @@ -509,21 +507,21 @@ submitted_form.password_value = saved_match()->password_value; submitted_form.new_password_value = ASCIIToUTF16("test2"); submitted_form.preferred = true; - form_manager->ProvisionallySave( + form_manager.ProvisionallySave( submitted_form, PasswordFormManager::IGNORE_OTHER_POSSIBLE_USERNAMES); // Successful login. The PasswordManager would instruct PasswordFormManager // to update. - EXPECT_FALSE(form_manager->IsNewLogin()); + EXPECT_FALSE(form_manager.IsNewLogin()); EXPECT_FALSE( - form_manager->is_possible_change_password_form_without_username()); + form_manager.is_possible_change_password_form_without_username()); // By now, the PasswordFormManager should have promoted the new password // value already to be the current password, and should no longer maintain // any info about the new password value. EXPECT_EQ(submitted_form.new_password_value, - form_manager->pending_credentials().password_value); - EXPECT_TRUE(form_manager->pending_credentials().new_password_value.empty()); + form_manager.pending_credentials().password_value); + EXPECT_TRUE(form_manager.pending_credentials().new_password_value.empty()); std::map<base::string16, autofill::ServerFieldType> expected_types; expected_types[ASCIIToUTF16("full_name")] = autofill::UNKNOWN_TYPE; @@ -559,13 +557,13 @@ switch (field_type) { case autofill::NEW_PASSWORD: - form_manager->Update(*saved_match()); + form_manager.Update(*saved_match()); break; case autofill::PROBABLY_NEW_PASSWORD: - form_manager->OnNoInteraction(true /* it is an update */); + form_manager.OnNoInteraction(true /* it is an update */); break; case autofill::NOT_NEW_PASSWORD: - form_manager->OnNopeUpdateClicked(); + form_manager.OnNopeUpdateClicked(); break; default: NOTREACHED(); @@ -640,10 +638,9 @@ FakeFormFetcher fetcher; fetcher.Fetch(); - scoped_refptr<PasswordFormManager> form_manager( - base::MakeRefCounted<PasswordFormManager>( - password_manager(), client(), client()->driver(), form, - base::MakeUnique<NiceMock<MockFormSaver>>(), &fetcher)); + PasswordFormManager form_manager( + password_manager(), client(), client()->driver(), form, + base::MakeUnique<NiceMock<MockFormSaver>>(), &fetcher); fetcher.SetNonFederated(std::vector<const PasswordForm*>(), 0u); @@ -652,13 +649,13 @@ if (interaction == SAVE) expected_available_field_types.insert(autofill::PASSWORD); - form_manager->set_is_manual_generation(is_manual_generation); + form_manager.set_is_manual_generation(is_manual_generation); base::string16 generation_element = is_change_password_form ? form.new_password_element : form.password_element; - form_manager->set_generation_element(generation_element); - form_manager->set_generation_popup_was_shown(true); - form_manager->set_has_generated_password(has_generated_password); + form_manager.set_generation_element(generation_element); + form_manager.set_generation_popup_was_shown(true); + form_manager.set_has_generated_password(has_generated_password); // Figure out expected generation event type. autofill::AutofillUploadContents::Field::PasswordGenerationType @@ -679,17 +676,17 @@ form_structure.FormSignatureAsStr(), expected_generation_types), false, expected_available_field_types, std::string(), true)); - form_manager->ProvisionallySave( + form_manager.ProvisionallySave( submitted_form, PasswordFormManager::IGNORE_OTHER_POSSIBLE_USERNAMES); switch (interaction) { case SAVE: - form_manager->Save(); + form_manager.Save(); break; case NEVER: - form_manager->OnNeverClicked(); + form_manager.OnNeverClicked(); break; case NO_INTERACTION: - form_manager->OnNoInteraction(false /* not an update prompt*/); + form_manager.OnNoInteraction(false /* not an update prompt*/); break; } Mock::VerifyAndClearExpectations( @@ -753,10 +750,9 @@ const char* filled_username, const char* filled_password, const char* submitted_password = nullptr) { - scoped_refptr<PasswordFormManager> form_manager( - base::MakeRefCounted<PasswordFormManager>( - password_manager(), client(), client()->driver(), *observed_form(), - base::MakeUnique<NiceMock<MockFormSaver>>(), fetcher)); + PasswordFormManager form_manager( + password_manager(), client(), client()->driver(), *observed_form(), + base::MakeUnique<NiceMock<MockFormSaver>>(), fetcher); EXPECT_CALL(*client()->mock_driver()->mock_autofill_download_manager(), StartUploadRequest(_, _, _, _, _)) @@ -792,13 +788,13 @@ submitted_password ? base::ASCIIToUTF16(submitted_password) : base::ASCIIToUTF16(filled_password); - form_manager->ProvisionallySave( + form_manager.ProvisionallySave( submitted_form, PasswordFormManager::IGNORE_OTHER_POSSIBLE_USERNAMES); if (submit_result == SimulatedSubmitResult::PASSED) { - form_manager->LogSubmitPassed(); - form_manager->Save(); + form_manager.LogSubmitPassed(); + form_manager.Save(); } else { - form_manager->LogSubmitFailed(); + form_manager.LogSubmitFailed(); } } } @@ -815,7 +811,7 @@ // Define |fake_form_fetcher_| before |form_manager_|, because the former // needs to outlive the latter. FakeFormFetcher fake_form_fetcher_; - scoped_refptr<PasswordFormManager> form_manager_; + std::unique_ptr<PasswordFormManager> form_manager_; }; class PasswordFormManagerFillOnAccountSelectTest @@ -934,10 +930,9 @@ observed_form()->signon_realm = "http://accounts.google.com"; FakeFormFetcher fetcher; fetcher.Fetch(); - scoped_refptr<PasswordFormManager> form_manager( - base::MakeRefCounted<PasswordFormManager>( - password_manager(), client(), client()->driver(), *observed_form(), - base::MakeUnique<MockFormSaver>(), &fetcher)); + PasswordFormManager form_manager(password_manager(), client(), + client()->driver(), *observed_form(), + base::MakeUnique<MockFormSaver>(), &fetcher); // Doesn't apply because it is just a PSL match of the observed form. PasswordForm blacklisted_psl = *observed_form(); @@ -980,12 +975,12 @@ saved_match()}; fetcher.SetNonFederated(matches, 0u); - EXPECT_TRUE(form_manager->IsBlacklisted()); - EXPECT_THAT(form_manager->blacklisted_matches(), + EXPECT_TRUE(form_manager.IsBlacklisted()); + EXPECT_THAT(form_manager.blacklisted_matches(), UnorderedElementsAre(Pointee(blacklisted_match), Pointee(blacklisted_match2))); - EXPECT_EQ(1u, form_manager->best_matches().size()); - EXPECT_EQ(*saved_match(), *form_manager->preferred_match()); + EXPECT_EQ(1u, form_manager.best_matches().size()); + EXPECT_EQ(*saved_match(), *form_manager.preferred_match()); } // Test that even in the presence of blacklisted matches, the non-blacklisted @@ -1075,10 +1070,9 @@ FakeFormFetcher fetcher; fetcher.Fetch(); - scoped_refptr<PasswordFormManager> form_manager( - base::MakeRefCounted<PasswordFormManager>( - password_manager(), client(), client()->driver(), *observed_form(), - base::MakeUnique<MockFormSaver>(), &fetcher)); + PasswordFormManager form_manager(password_manager(), client(), + client()->driver(), *observed_form(), + base::MakeUnique<MockFormSaver>(), &fetcher); fetcher.SetNonFederated(std::vector<const PasswordForm*>(), 0u); // User enters current and new credentials to the observed form. @@ -1087,28 +1081,28 @@ credentials.password_value = ASCIIToUTF16("oldpassword"); credentials.new_password_value = ASCIIToUTF16("newpassword"); credentials.preferred = true; - form_manager->ProvisionallySave( + form_manager.ProvisionallySave( credentials, PasswordFormManager::IGNORE_OTHER_POSSIBLE_USERNAMES); // Successful login. The PasswordManager would instruct PasswordFormManager // to save, which should know this is a new login. - EXPECT_TRUE(form_manager->IsNewLogin()); - EXPECT_EQ(credentials.origin, form_manager->pending_credentials().origin); + EXPECT_TRUE(form_manager.IsNewLogin()); + EXPECT_EQ(credentials.origin, form_manager.pending_credentials().origin); EXPECT_EQ(credentials.signon_realm, - form_manager->pending_credentials().signon_realm); - EXPECT_EQ(credentials.action, form_manager->pending_credentials().action); - EXPECT_TRUE(form_manager->pending_credentials().preferred); + form_manager.pending_credentials().signon_realm); + EXPECT_EQ(credentials.action, form_manager.pending_credentials().action); + EXPECT_TRUE(form_manager.pending_credentials().preferred); EXPECT_EQ(credentials.username_value, - form_manager->pending_credentials().username_value); + form_manager.pending_credentials().username_value); // By this point, the PasswordFormManager should have promoted the new // password value to be the current password, and should have wiped the // password element name: it is likely going to be different on a login // form, so it is not worth remembering them. EXPECT_EQ(credentials.new_password_value, - form_manager->pending_credentials().password_value); - EXPECT_TRUE(form_manager->pending_credentials().password_element.empty()); - EXPECT_TRUE(form_manager->pending_credentials().new_password_value.empty()); + form_manager.pending_credentials().password_value); + EXPECT_TRUE(form_manager.pending_credentials().password_element.empty()); + EXPECT_TRUE(form_manager.pending_credentials().new_password_value.empty()); } TEST_F(PasswordFormManagerTest, TestUpdatePassword) { @@ -1159,10 +1153,9 @@ FakeFormFetcher fetcher; fetcher.Fetch(); - scoped_refptr<PasswordFormManager> form_manager( - base::MakeRefCounted<PasswordFormManager>( - password_manager(), client(), client()->driver(), *observed_form(), - base::MakeUnique<MockFormSaver>(), &fetcher)); + PasswordFormManager form_manager(password_manager(), client(), + client()->driver(), *observed_form(), + base::MakeUnique<MockFormSaver>(), &fetcher); fetcher.SetNonFederated({saved_match()}, 0u); // User submits current and new credentials to the observed form. @@ -1171,28 +1164,28 @@ credentials.password_value = saved_match()->password_value; credentials.new_password_value = ASCIIToUTF16("test2"); credentials.preferred = true; - form_manager->ProvisionallySave( + form_manager.ProvisionallySave( credentials, PasswordFormManager::IGNORE_OTHER_POSSIBLE_USERNAMES); // Successful login. The PasswordManager would instruct PasswordFormManager // to save, and since this is an update, it should know not to save as a new // login. - EXPECT_FALSE(form_manager->IsNewLogin()); + EXPECT_FALSE(form_manager.IsNewLogin()); // By now, the PasswordFormManager should have promoted the new password value // already to be the current password, and should no longer maintain any info // about the new password. EXPECT_EQ(credentials.new_password_value, - form_manager->pending_credentials().password_value); - EXPECT_TRUE(form_manager->pending_credentials().new_password_element.empty()); - EXPECT_TRUE(form_manager->pending_credentials().new_password_value.empty()); + form_manager.pending_credentials().password_value); + EXPECT_TRUE(form_manager.pending_credentials().new_password_element.empty()); + EXPECT_TRUE(form_manager.pending_credentials().new_password_value.empty()); // Trigger saving to exercise some special case handling for updating. PasswordForm new_credentials; - EXPECT_CALL(MockFormSaver::Get(form_manager.get()), Update(_, _, _, nullptr)) + EXPECT_CALL(MockFormSaver::Get(&form_manager), Update(_, _, _, nullptr)) .WillOnce(testing::SaveArg<0>(&new_credentials)); - form_manager->Save(); + form_manager.Save(); // No meta-information should be updated, only the password. EXPECT_EQ(credentials.new_password_value, new_credentials.password_value); @@ -1211,10 +1204,9 @@ FakeFormFetcher fetcher; fetcher.Fetch(); - scoped_refptr<PasswordFormManager> form_manager( - base::MakeRefCounted<PasswordFormManager>( - password_manager(), client(), client()->driver(), observed, - base::MakeUnique<MockFormSaver>(), &fetcher)); + PasswordFormManager form_manager(password_manager(), client(), + client()->driver(), observed, + base::MakeUnique<MockFormSaver>(), &fetcher); PasswordForm saved_form = observed; saved_form.origin = GURL("https://accounts.google.com/a/OtherLoginAuth"); @@ -1222,8 +1214,8 @@ fetcher.SetNonFederated({&saved_form}, 0u); // Different paths for action / origin are okay. - EXPECT_EQ(1u, form_manager->best_matches().size()); - EXPECT_EQ(*form_manager->best_matches().begin()->second, saved_form); + EXPECT_EQ(1u, form_manager.best_matches().size()); + EXPECT_EQ(*form_manager.best_matches().begin()->second, saved_form); } // Test that saved empty action URL is updated with the submitted action URL. @@ -1383,10 +1375,9 @@ FakeFormFetcher fetcher; fetcher.Fetch(); - scoped_refptr<PasswordFormManager> form_manager( - base::MakeRefCounted<PasswordFormManager>( - password_manager(), client(), client()->driver(), signup_form, - base::MakeUnique<MockFormSaver>(), &fetcher)); + PasswordFormManager form_manager(password_manager(), client(), + client()->driver(), signup_form, + base::MakeUnique<MockFormSaver>(), &fetcher); EXPECT_CALL(*(client()->mock_driver()), AllowPasswordGenerationForForm(_)); PasswordForm simulated_result = CreateSavedMatch(false); fetcher.SetNonFederated({&simulated_result}, 0u); @@ -1536,10 +1527,9 @@ FakeFormFetcher fetcher; fetcher.Fetch(); - scoped_refptr<PasswordFormManager> form_manager( - base::MakeRefCounted<PasswordFormManager>( - password_manager(), client(), client()->driver(), encountered_form, - base::MakeUnique<MockFormSaver>(), &fetcher)); + PasswordFormManager form_manager(password_manager(), client(), + client()->driver(), encountered_form, + base::MakeUnique<MockFormSaver>(), &fetcher); PasswordForm incomplete_form; incomplete_form.origin = GURL("http://accounts.google.com/LoginAuth"); @@ -1565,16 +1555,16 @@ // Feed the incomplete credentials to the manager. fetcher.SetNonFederated({&incomplete_form}, 0u); - form_manager->ProvisionallySave( + form_manager.ProvisionallySave( complete_form, PasswordFormManager::IGNORE_OTHER_POSSIBLE_USERNAMES); // By now that form has been used once. complete_form.times_used = 1; obsolete_form.times_used = 1; // Check that PasswordStore receives an update request with the complete form. - EXPECT_CALL(MockFormSaver::Get(form_manager.get()), + EXPECT_CALL(MockFormSaver::Get(&form_manager), Update(complete_form, _, _, Pointee(obsolete_form))); - form_manager->Save(); + form_manager.Save(); } // Test that public-suffix-matched credentials score lower than same-origin @@ -1716,11 +1706,10 @@ PasswordFormManager::RESULT_ACTION_MATCH); // Then when the observed form has an invalid URL: PasswordForm valid_action_form(*observed_form()); - scoped_refptr<PasswordFormManager> invalid_manager( - base::MakeRefCounted<PasswordFormManager>( - password_manager(), client(), client()->driver(), invalid_action_form, - base::MakeUnique<MockFormSaver>(), fake_form_fetcher())); - EXPECT_EQ(0, invalid_manager->DoesManage(valid_action_form, nullptr) & + PasswordFormManager invalid_manager( + password_manager(), client(), client()->driver(), invalid_action_form, + base::MakeUnique<MockFormSaver>(), fake_form_fetcher()); + EXPECT_EQ(0, invalid_manager.DoesManage(valid_action_form, nullptr) & PasswordFormManager::RESULT_ACTION_MATCH); } @@ -1734,11 +1723,10 @@ PasswordFormManager::RESULT_ACTION_MATCH); // Then when the observed form has an empty URL: PasswordForm valid_action_form(*observed_form()); - scoped_refptr<PasswordFormManager> empty_action_manager( - base::MakeRefCounted<PasswordFormManager>( - password_manager(), client(), client()->driver(), empty_action_form, - base::MakeUnique<MockFormSaver>(), fake_form_fetcher())); - EXPECT_EQ(0, empty_action_manager->DoesManage(valid_action_form, nullptr) & + PasswordFormManager empty_action_manager( + password_manager(), client(), client()->driver(), empty_action_form, + base::MakeUnique<MockFormSaver>(), fake_form_fetcher()); + EXPECT_EQ(0, empty_action_manager.DoesManage(valid_action_form, nullptr) & PasswordFormManager::RESULT_ACTION_MATCH); } @@ -1751,11 +1739,10 @@ // The other way round: observing a non-HTML form, don't match a HTML form. PasswordForm html_form(*observed_form()); - scoped_refptr<PasswordFormManager> non_html_manager( - base::MakeRefCounted<PasswordFormManager>( - password_manager(), client(), kNoDriver, non_html_form, - base::MakeUnique<MockFormSaver>(), fake_form_fetcher())); - EXPECT_EQ(0, non_html_manager->DoesManage(html_form, nullptr) & + PasswordFormManager non_html_manager( + password_manager(), client(), kNoDriver, non_html_form, + base::MakeUnique<MockFormSaver>(), fake_form_fetcher()); + EXPECT_EQ(0, non_html_manager.DoesManage(html_form, nullptr) & PasswordFormManager::RESULT_HTML_ATTRIBUTES_MATCH); } @@ -1789,18 +1776,16 @@ PasswordForm secure_observed_form(*observed_form()); secure_observed_form.origin = GURL("https://accounts.google.com/a/LoginAuth"); - scoped_refptr<PasswordFormManager> secure_manager( - base::MakeRefCounted<PasswordFormManager>( - password_manager(), client(), client()->driver(), - secure_observed_form, base::MakeUnique<MockFormSaver>(), - fake_form_fetcher())); + PasswordFormManager secure_manager( + password_manager(), client(), client()->driver(), secure_observed_form, + base::MakeUnique<MockFormSaver>(), fake_form_fetcher()); // Also for HTTPS in the observed form, and HTTP in the compared form, an // exact path match is expected. - EXPECT_EQ(0, secure_manager->DoesManage(form_longer_path, nullptr) & + EXPECT_EQ(0, secure_manager.DoesManage(form_longer_path, nullptr) & PasswordFormManager::RESULT_HTML_ATTRIBUTES_MATCH); // Not even upgrade to HTTPS in the compared form should help. form_longer_path.origin = GURL("https://accounts.google.com/a/LoginAuth/sec"); - EXPECT_EQ(0, secure_manager->DoesManage(form_longer_path, nullptr) & + EXPECT_EQ(0, secure_manager.DoesManage(form_longer_path, nullptr) & PasswordFormManager::RESULT_HTML_ATTRIBUTES_MATCH); } @@ -1888,10 +1873,9 @@ // Don't vote for the username field yet. FakeFormFetcher fetcher; fetcher.Fetch(); - scoped_refptr<PasswordFormManager> form_manager( - base::MakeRefCounted<PasswordFormManager>( - password_manager(), client(), client()->driver(), *saved_match(), - base::MakeUnique<NiceMock<MockFormSaver>>(), &fetcher)); + PasswordFormManager form_manager( + password_manager(), client(), client()->driver(), *saved_match(), + base::MakeUnique<NiceMock<MockFormSaver>>(), &fetcher); fetcher.SetNonFederated(std::vector<const PasswordForm*>(), 0u); PasswordForm form_to_save(*saved_match()); @@ -1904,19 +1888,18 @@ EXPECT_CALL( *client()->mock_driver()->mock_autofill_download_manager(), StartUploadRequest(_, false, expected_available_field_types, _, true)); - form_manager->ProvisionallySave( + form_manager.ProvisionallySave( form_to_save, PasswordFormManager::IGNORE_OTHER_POSSIBLE_USERNAMES); - form_manager->Save(); + form_manager.Save(); } TEST_F(PasswordFormManagerTest, UploadFormData_NewPassword_Blacklist) { // Do not upload a vote if the user is blacklisting the form. FakeFormFetcher fetcher; fetcher.Fetch(); - scoped_refptr<PasswordFormManager> blacklist_form_manager( - base::MakeRefCounted<PasswordFormManager>( - password_manager(), client(), client()->driver(), *saved_match(), - base::MakeUnique<NiceMock<MockFormSaver>>(), &fetcher)); + PasswordFormManager blacklist_form_manager( + password_manager(), client(), client()->driver(), *saved_match(), + base::MakeUnique<NiceMock<MockFormSaver>>(), &fetcher); fetcher.SetNonFederated(std::vector<const PasswordForm*>(), 0u); autofill::ServerFieldTypeSet expected_available_field_types; @@ -1925,7 +1908,7 @@ EXPECT_CALL(*client()->mock_driver()->mock_autofill_download_manager(), StartUploadRequest(_, _, expected_available_field_types, _, true)) .Times(0); - blacklist_form_manager->PermanentlyBlacklist(); + blacklist_form_manager.PermanentlyBlacklist(); } TEST_F(PasswordFormManagerTest, UploadPasswordForm) { @@ -2010,10 +1993,9 @@ FakeFormFetcher fetcher; fetcher.Fetch(); - scoped_refptr<PasswordFormManager> form_manager( - base::MakeRefCounted<PasswordFormManager>( - password_manager(), client(), client()->driver(), form, - base::MakeUnique<MockFormSaver>(), &fetcher)); + PasswordFormManager form_manager(password_manager(), client(), + client()->driver(), form, + base::MakeUnique<MockFormSaver>(), &fetcher); // Suddenly, the frame and its driver disappear. client()->KillDriver(); @@ -2091,11 +2073,10 @@ base::ASCIIToUTF16("new_pwd"); FakeFormFetcher fetcher; fetcher.Fetch(); - scoped_refptr<PasswordFormManager> manager_creds( - base::MakeRefCounted<PasswordFormManager>( - password_manager(), client(), client()->driver(), - observed_change_password_form, base::MakeUnique<MockFormSaver>(), - &fetcher)); + PasswordFormManager manager_creds( + password_manager(), client(), client()->driver(), + observed_change_password_form, base::MakeUnique<MockFormSaver>(), + &fetcher); autofill::PasswordFormFillData fill_data; EXPECT_CALL(*client()->mock_driver(), FillPasswordForm(_)) @@ -2103,7 +2084,7 @@ PasswordForm result = CreateSavedMatch(false); fetcher.SetNonFederated({&result}, 0u); - EXPECT_EQ(1u, manager_creds->best_matches().size()); + EXPECT_EQ(1u, manager_creds.best_matches().size()); EXPECT_EQ(0u, fill_data.additional_logins.size()); EXPECT_TRUE(fill_data.wait_for_username); } @@ -2129,10 +2110,9 @@ FakeFormFetcher fetcher; fetcher.Fetch(); - scoped_refptr<PasswordFormManager> form_manager( - base::MakeRefCounted<PasswordFormManager>( - password_manager(), client(), client()->driver(), *observed_form(), - base::MakeUnique<MockFormSaver>(), &fetcher)); + PasswordFormManager form_manager(password_manager(), client(), + client()->driver(), *observed_form(), + base::MakeUnique<MockFormSaver>(), &fetcher); fetcher.SetNonFederated({saved_match()}, 0u); @@ -2142,29 +2122,29 @@ credentials.password_value = saved_match()->password_value; credentials.new_password_value = ASCIIToUTF16("test2"); credentials.preferred = true; - form_manager->ProvisionallySave( + form_manager.ProvisionallySave( credentials, PasswordFormManager::IGNORE_OTHER_POSSIBLE_USERNAMES); // Successful login. The PasswordManager would instruct PasswordFormManager // to save, and since this is an update, it should know not to save as a new // login. - EXPECT_FALSE(form_manager->IsNewLogin()); + EXPECT_FALSE(form_manager.IsNewLogin()); EXPECT_FALSE( - form_manager->is_possible_change_password_form_without_username()); + form_manager.is_possible_change_password_form_without_username()); // By now, the PasswordFormManager should have promoted the new password value // already to be the current password, and should no longer maintain any info // about the new password value. EXPECT_EQ(credentials.new_password_value, - form_manager->pending_credentials().password_value); - EXPECT_TRUE(form_manager->pending_credentials().new_password_value.empty()); + form_manager.pending_credentials().password_value); + EXPECT_TRUE(form_manager.pending_credentials().new_password_value.empty()); // Trigger saving to exercise some special case handling during updating. PasswordForm new_credentials; - EXPECT_CALL(MockFormSaver::Get(form_manager.get()), Update(_, _, _, nullptr)) + EXPECT_CALL(MockFormSaver::Get(&form_manager), Update(_, _, _, nullptr)) .WillOnce(SaveArg<0>(&new_credentials)); - form_manager->Update(*saved_match()); + form_manager.Update(*saved_match()); // No meta-information should be updated, only the password. EXPECT_EQ(credentials.new_password_value, new_credentials.password_value); @@ -2195,10 +2175,9 @@ FakeFormFetcher fetcher; fetcher.Fetch(); - scoped_refptr<PasswordFormManager> form_manager( - base::MakeRefCounted<PasswordFormManager>( - password_manager(), client(), client()->driver(), *observed_form(), - base::MakeUnique<MockFormSaver>(), &fetcher)); + PasswordFormManager form_manager(password_manager(), client(), + client()->driver(), *observed_form(), + base::MakeUnique<MockFormSaver>(), &fetcher); fetcher.SetNonFederated({saved_match()}, 0u); @@ -2209,31 +2188,30 @@ credentials.password_value = saved_match()->password_value; credentials.new_password_value = ASCIIToUTF16("test2"); credentials.preferred = true; - form_manager->ProvisionallySave( + form_manager.ProvisionallySave( credentials, PasswordFormManager::IGNORE_OTHER_POSSIBLE_USERNAMES); // Successful login. The PasswordManager would instruct PasswordFormManager // to save, and since this is an update, it should know not to save as a new // login. - EXPECT_FALSE(form_manager->IsNewLogin()); - EXPECT_TRUE( - form_manager->is_possible_change_password_form_without_username()); + EXPECT_FALSE(form_manager.IsNewLogin()); + EXPECT_TRUE(form_manager.is_possible_change_password_form_without_username()); // By now, the PasswordFormManager should have promoted the new password value // already to be the current password, and should no longer maintain any info // about the new password value. EXPECT_EQ(saved_match()->username_value, - form_manager->pending_credentials().username_value); + form_manager.pending_credentials().username_value); EXPECT_EQ(credentials.new_password_value, - form_manager->pending_credentials().password_value); - EXPECT_TRUE(form_manager->pending_credentials().new_password_value.empty()); + form_manager.pending_credentials().password_value); + EXPECT_TRUE(form_manager.pending_credentials().new_password_value.empty()); // Trigger saving to exercise some special case handling during updating. PasswordForm new_credentials; - EXPECT_CALL(MockFormSaver::Get(form_manager.get()), Update(_, _, _, nullptr)) + EXPECT_CALL(MockFormSaver::Get(&form_manager), Update(_, _, _, nullptr)) .WillOnce(SaveArg<0>(&new_credentials)); - form_manager->Update(form_manager->pending_credentials()); + form_manager.Update(form_manager.pending_credentials()); // No other information than password value should be updated. In particular // not the username. @@ -2252,22 +2230,21 @@ FakeFormFetcher fetcher; fetcher.Fetch(); - scoped_refptr<PasswordFormManager> form_manager( - base::MakeRefCounted<PasswordFormManager>( - password_manager(), client(), client()->driver(), form, - base::MakeUnique<MockFormSaver>(), &fetcher)); + PasswordFormManager form_manager(password_manager(), client(), + client()->driver(), form, + base::MakeUnique<MockFormSaver>(), &fetcher); // The creation of |fetcher| keeps it waiting for store results. This test // keeps the fetcher waiting on purpose. PasswordForm submitted_form(form); submitted_form.password_value += ASCIIToUTF16("add stuff, make it different"); - form_manager->ProvisionallySave( + form_manager.ProvisionallySave( submitted_form, PasswordFormManager::IGNORE_OTHER_POSSIBLE_USERNAMES); base::HistogramTester histogram_tester; - EXPECT_CALL(MockFormSaver::Get(form_manager.get()), - WipeOutdatedCopies(form_manager->pending_credentials(), _, _)); - form_manager->WipeStoreCopyIfOutdated(); + EXPECT_CALL(MockFormSaver::Get(&form_manager), + WipeOutdatedCopies(form_manager.pending_credentials(), _, _)); + form_manager.WipeStoreCopyIfOutdated(); histogram_tester.ExpectUniqueSample("PasswordManager.StoreReadyWhenWiping", 0, 1); } @@ -2386,10 +2363,9 @@ TEST_F(PasswordFormManagerTest, TestUpdatePSLMatchedCredentials) { FakeFormFetcher fetcher; fetcher.Fetch(); - scoped_refptr<PasswordFormManager> form_manager( - base::MakeRefCounted<PasswordFormManager>( - password_manager(), client(), client()->driver(), *observed_form(), - base::MakeUnique<MockFormSaver>(), &fetcher)); + PasswordFormManager form_manager(password_manager(), client(), + client()->driver(), *observed_form(), + base::MakeUnique<MockFormSaver>(), &fetcher); fetcher.SetNonFederated({saved_match(), psl_saved_match()}, 0u); // User submits a credentials with an old username and a new password. @@ -2397,24 +2373,24 @@ credentials.username_value = saved_match()->username_value; credentials.password_value = ASCIIToUTF16("new_password"); credentials.preferred = true; - form_manager->ProvisionallySave( + form_manager.ProvisionallySave( credentials, PasswordFormManager::IGNORE_OTHER_POSSIBLE_USERNAMES); // Successful login. The PasswordManager would instruct PasswordFormManager // to save, and since this is an update, it should know not to save as a new // login. - EXPECT_FALSE(form_manager->IsNewLogin()); + EXPECT_FALSE(form_manager.IsNewLogin()); // Trigger saving to exercise some special case handling during updating. PasswordForm new_credentials; std::vector<autofill::PasswordForm> credentials_to_update; - EXPECT_CALL(MockFormSaver::Get(form_manager.get()), Update(_, _, _, nullptr)) + EXPECT_CALL(MockFormSaver::Get(&form_manager), Update(_, _, _, nullptr)) .WillOnce(testing::DoAll(SaveArg<0>(&new_credentials), SaveArgPointee<2>(&credentials_to_update))); EXPECT_CALL(*client()->mock_driver()->mock_autofill_download_manager(), StartUploadRequest(_, false, _, _, true)); - form_manager->Save(); + form_manager.Save(); // No meta-information should be updated, only the password. EXPECT_EQ(credentials.password_value, new_credentials.password_value); @@ -2439,10 +2415,9 @@ TestNotUpdatePSLMatchedCredentialsWithAnotherUsername) { FakeFormFetcher fetcher; fetcher.Fetch(); - scoped_refptr<PasswordFormManager> form_manager( - base::MakeRefCounted<PasswordFormManager>( - password_manager(), client(), client()->driver(), *observed_form(), - base::MakeUnique<MockFormSaver>(), &fetcher)); + PasswordFormManager form_manager(password_manager(), client(), + client()->driver(), *observed_form(), + base::MakeUnique<MockFormSaver>(), &fetcher); psl_saved_match()->username_value += ASCIIToUTF16("1"); fetcher.SetNonFederated({saved_match(), psl_saved_match()}, 0u); @@ -2451,23 +2426,23 @@ credentials.username_value = saved_match()->username_value; credentials.password_value = ASCIIToUTF16("new_password"); credentials.preferred = true; - form_manager->ProvisionallySave( + form_manager.ProvisionallySave( credentials, PasswordFormManager::IGNORE_OTHER_POSSIBLE_USERNAMES); // Successful login. The PasswordManager would instruct PasswordFormManager // to save, and since this is an update, it should know not to save as a new // login. - EXPECT_FALSE(form_manager->IsNewLogin()); + EXPECT_FALSE(form_manager.IsNewLogin()); // Trigger saving to exercise some special case handling during updating. PasswordForm new_credentials; - EXPECT_CALL(MockFormSaver::Get(form_manager.get()), + EXPECT_CALL(MockFormSaver::Get(&form_manager), Update(_, _, Pointee(IsEmpty()), nullptr)) .WillOnce(testing::SaveArg<0>(&new_credentials)); EXPECT_CALL(*client()->mock_driver()->mock_autofill_download_manager(), StartUploadRequest(_, false, _, _, true)); - form_manager->Save(); + form_manager.Save(); // No meta-information should be updated, only the password. EXPECT_EQ(credentials.password_value, new_credentials.password_value); @@ -2481,10 +2456,9 @@ TestNotUpdatePSLMatchedCredentialsWithAnotherPassword) { FakeFormFetcher fetcher; fetcher.Fetch(); - scoped_refptr<PasswordFormManager> form_manager( - base::MakeRefCounted<PasswordFormManager>( - password_manager(), client(), client()->driver(), *observed_form(), - base::MakeUnique<MockFormSaver>(), &fetcher)); + PasswordFormManager form_manager(password_manager(), client(), + client()->driver(), *observed_form(), + base::MakeUnique<MockFormSaver>(), &fetcher); psl_saved_match()->password_value += ASCIIToUTF16("1"); fetcher.SetNonFederated({saved_match(), psl_saved_match()}, 0u); @@ -2493,23 +2467,23 @@ credentials.username_value = saved_match()->username_value; credentials.password_value = ASCIIToUTF16("new_password"); credentials.preferred = true; - form_manager->ProvisionallySave( + form_manager.ProvisionallySave( credentials, PasswordFormManager::IGNORE_OTHER_POSSIBLE_USERNAMES); // Successful login. The PasswordManager would instruct PasswordFormManager // to save, and since this is an update, it should know not to save as a new // login. - EXPECT_FALSE(form_manager->IsNewLogin()); + EXPECT_FALSE(form_manager.IsNewLogin()); // Trigger saving to exercise some special case handling during updating. PasswordForm new_credentials; - EXPECT_CALL(MockFormSaver::Get(form_manager.get()), + EXPECT_CALL(MockFormSaver::Get(&form_manager), Update(_, _, Pointee(IsEmpty()), nullptr)) .WillOnce(testing::SaveArg<0>(&new_credentials)); EXPECT_CALL(*client()->mock_driver()->mock_autofill_download_manager(), StartUploadRequest(_, false, _, _, true)); - form_manager->Save(); + form_manager.Save(); // No meta-information should be updated, only the password. EXPECT_EQ(credentials.password_value, new_credentials.password_value); @@ -2522,10 +2496,9 @@ TEST_F(PasswordFormManagerTest, TestNotUpdateWhenOnlyPSLMatched) { FakeFormFetcher fetcher; fetcher.Fetch(); - scoped_refptr<PasswordFormManager> form_manager( - base::MakeRefCounted<PasswordFormManager>( - password_manager(), client(), client()->driver(), *observed_form(), - base::MakeUnique<MockFormSaver>(), &fetcher)); + PasswordFormManager form_manager(password_manager(), client(), + client()->driver(), *observed_form(), + base::MakeUnique<MockFormSaver>(), &fetcher); fetcher.SetNonFederated({psl_saved_match()}, 0u); // User submits a credentials with an old username and a new password. @@ -2533,18 +2506,18 @@ credentials.username_value = saved_match()->username_value; credentials.password_value = ASCIIToUTF16("new_password"); credentials.preferred = true; - form_manager->ProvisionallySave( + form_manager.ProvisionallySave( credentials, PasswordFormManager::IGNORE_OTHER_POSSIBLE_USERNAMES); - EXPECT_TRUE(form_manager->IsNewLogin()); + EXPECT_TRUE(form_manager.IsNewLogin()); // PSL matched credential should not be updated, since we are not sure that // this is the same credential as submitted one. PasswordForm new_credentials; - EXPECT_CALL(MockFormSaver::Get(form_manager.get()), Save(_, _, nullptr)) + EXPECT_CALL(MockFormSaver::Get(&form_manager), Save(_, _, nullptr)) .WillOnce(testing::SaveArg<0>(&new_credentials)); - form_manager->Save(); + form_manager.Save(); EXPECT_EQ(credentials.password_value, new_credentials.password_value); EXPECT_EQ(credentials.username_value, new_credentials.username_value); @@ -2679,10 +2652,9 @@ FakeFormFetcher fetcher; fetcher.Fetch(); - scoped_refptr<PasswordFormManager> form_manager( - base::MakeRefCounted<PasswordFormManager>( - password_manager(), client(), client()->driver(), *observed_form(), - base::MakeUnique<MockFormSaver>(), &fetcher)); + PasswordFormManager form_manager(password_manager(), client(), + client()->driver(), *observed_form(), + base::MakeUnique<MockFormSaver>(), &fetcher); fetcher.SetNonFederated({saved_match()}, 0u); // User submits current and new credentials to the observed form. @@ -2690,21 +2662,20 @@ submitted_form.password_value = saved_match()->password_value; submitted_form.new_password_value = ASCIIToUTF16("test2"); submitted_form.preferred = true; - form_manager->ProvisionallySave( + form_manager.ProvisionallySave( submitted_form, PasswordFormManager::IGNORE_OTHER_POSSIBLE_USERNAMES); // Successful login. The PasswordManager would instruct PasswordFormManager // to update. - EXPECT_FALSE(form_manager->IsNewLogin()); - EXPECT_TRUE( - form_manager->is_possible_change_password_form_without_username()); + EXPECT_FALSE(form_manager.IsNewLogin()); + EXPECT_TRUE(form_manager.is_possible_change_password_form_without_username()); // By now, the PasswordFormManager should have promoted the new password // value already to be the current password, and should no longer maintain // any info about the new password value. EXPECT_EQ(submitted_form.new_password_value, - form_manager->pending_credentials().password_value); - EXPECT_TRUE(form_manager->pending_credentials().new_password_value.empty()); + form_manager.pending_credentials().password_value); + EXPECT_TRUE(form_manager.pending_credentials().new_password_value.empty()); std::map<base::string16, autofill::ServerFieldType> expected_types; expected_types[observed_form()->password_element] = autofill::PASSWORD; @@ -2728,7 +2699,7 @@ false, expected_available_field_types, expected_login_signature, true)); - form_manager->Update(*saved_match()); + form_manager.Update(*saved_match()); } // Checks uploading a vote about the usage of the password generation popup. @@ -2764,15 +2735,14 @@ FakeFormFetcher fetcher; fetcher.Fetch(); - scoped_refptr<PasswordFormManager> form_manager( - base::MakeRefCounted<PasswordFormManager>( - password_manager(), client(), client()->driver(), form, - base::MakeUnique<NiceMock<MockFormSaver>>(), &fetcher)); + PasswordFormManager form_manager( + password_manager(), client(), client()->driver(), form, + base::MakeUnique<NiceMock<MockFormSaver>>(), &fetcher); base::string16 generation_element = form.password_element; if (found_generation_element) - form_manager->SaveGenerationFieldDetectedByClassifier(generation_element); + form_manager.SaveGenerationFieldDetectedByClassifier(generation_element); else - form_manager->SaveGenerationFieldDetectedByClassifier(base::string16()); + form_manager.SaveGenerationFieldDetectedByClassifier(base::string16()); fetcher.SetNonFederated(std::vector<const PasswordForm*>(), 0u); @@ -2784,9 +2754,9 @@ found_generation_element, generation_element), false, _, _, true)); - form_manager->ProvisionallySave( + form_manager.ProvisionallySave( submitted_form, PasswordFormManager::IGNORE_OTHER_POSSIBLE_USERNAMES); - form_manager->Save(); + form_manager.Save(); } } @@ -2802,10 +2772,9 @@ FakeFormFetcher fetcher; fetcher.Fetch(); - scoped_refptr<PasswordFormManager> form_manager( - base::MakeRefCounted<PasswordFormManager>( - password_manager(), client(), client()->driver(), form, - base::MakeUnique<NiceMock<MockFormSaver>>(), &fetcher)); + PasswordFormManager form_manager( + password_manager(), client(), client()->driver(), form, + base::MakeUnique<NiceMock<MockFormSaver>>(), &fetcher); fetcher.SetNonFederated(std::vector<const PasswordForm*>(), 0u); DCHECK_EQ(3U, form.form_data.fields.size()); @@ -2824,9 +2793,9 @@ StartUploadRequest( CheckFieldPropertiesMasksUpload(expected_field_properties), false, _, _, true)); - form_manager->ProvisionallySave( + form_manager.ProvisionallySave( submitted_form, PasswordFormManager::IGNORE_OTHER_POSSIBLE_USERNAMES); - form_manager->Save(); + form_manager.Save(); } TEST_F(PasswordFormManagerTest, TestSavingAPIFormsWithSamePassword) { @@ -2838,10 +2807,9 @@ FakeFormFetcher fetcher; fetcher.Fetch(); - scoped_refptr<PasswordFormManager> form_manager( - base::MakeRefCounted<PasswordFormManager>( - password_manager(), client(), client()->driver(), *observed_form(), - base::MakeUnique<MockFormSaver>(), &fetcher)); + PasswordFormManager form_manager(password_manager(), client(), + client()->driver(), *observed_form(), + base::MakeUnique<MockFormSaver>(), &fetcher); fetcher.SetNonFederated({saved_match()}, 0u); // User submits new credentials with the same password as in already saved @@ -2852,16 +2820,16 @@ credentials.password_value = saved_match()->password_value; credentials.preferred = true; - form_manager->ProvisionallySave( + form_manager.ProvisionallySave( credentials, PasswordFormManager::IGNORE_OTHER_POSSIBLE_USERNAMES); - EXPECT_TRUE(form_manager->IsNewLogin()); + EXPECT_TRUE(form_manager.IsNewLogin()); PasswordForm new_credentials; - EXPECT_CALL(MockFormSaver::Get(form_manager.get()), Save(_, _, nullptr)) + EXPECT_CALL(MockFormSaver::Get(&form_manager), Save(_, _, nullptr)) .WillOnce(SaveArg<0>(&new_credentials)); - form_manager->Save(); + form_manager.Save(); EXPECT_EQ(saved_match()->username_value + ASCIIToUTF16("1"), new_credentials.username_value); @@ -2905,10 +2873,9 @@ FakeFormFetcher fetcher; fetcher.Fetch(); - scoped_refptr<PasswordFormManager> form_manager( - base::MakeRefCounted<PasswordFormManager>( - password_manager(), client(), client()->driver(), form, - base::MakeUnique<NiceMock<MockFormSaver>>(), &fetcher)); + PasswordFormManager form_manager( + password_manager(), client(), client()->driver(), form, + base::MakeUnique<NiceMock<MockFormSaver>>(), &fetcher); PasswordForm form_to_save(form); form_to_save.preferred = true; @@ -2936,9 +2903,9 @@ false /* expect_generation_vote */), false, expected_available_field_types, std::string(), true)); - form_manager->ProvisionallySave( + form_manager.ProvisionallySave( form_to_save, PasswordFormManager::IGNORE_OTHER_POSSIBLE_USERNAMES); - form_manager->Save(); + form_manager.Save(); } TEST_F(PasswordFormManagerFillOnAccountSelectTest, ProcessFrame) { @@ -2994,12 +2961,11 @@ observed.scheme = kCorrectScheme; FakeFormFetcher fetcher; fetcher.Fetch(); - scoped_refptr<PasswordFormManager> form_manager( - base::MakeRefCounted<PasswordFormManager>( - password_manager(), client(), - (kCorrectScheme == PasswordForm::SCHEME_HTML ? client()->driver() - : nullptr), - observed, base::MakeUnique<NiceMock<MockFormSaver>>(), &fetcher)); + PasswordFormManager form_manager( + password_manager(), client(), + (kCorrectScheme == PasswordForm::SCHEME_HTML ? client()->driver() + : nullptr), + observed, base::MakeUnique<NiceMock<MockFormSaver>>(), &fetcher); PasswordForm match = *saved_match(); match.scheme = kCorrectScheme; @@ -3008,20 +2974,20 @@ non_match.scheme = kWrongScheme; // First try putting the correct scheme first in returned matches. - static_cast<FormFetcher::Consumer*>(form_manager.get()) + static_cast<FormFetcher::Consumer*>(&form_manager) ->ProcessMatches({&match, &non_match}, 0u); - EXPECT_EQ(1u, form_manager->best_matches().size()); + EXPECT_EQ(1u, form_manager.best_matches().size()); EXPECT_EQ(kCorrectScheme, - form_manager->best_matches().begin()->second->scheme); + form_manager.best_matches().begin()->second->scheme); // Now try putting the correct scheme last in returned matches. - static_cast<FormFetcher::Consumer*>(form_manager.get()) + static_cast<FormFetcher::Consumer*>(&form_manager) ->ProcessMatches({&non_match, &match}, 0u); - EXPECT_EQ(1u, form_manager->best_matches().size()); + EXPECT_EQ(1u, form_manager.best_matches().size()); EXPECT_EQ(kCorrectScheme, - form_manager->best_matches().begin()->second->scheme); + form_manager.best_matches().begin()->second->scheme); } } } @@ -3166,13 +3132,13 @@ MockFormFetcher fetcher; FormFetcher::Consumer* added_consumer = nullptr; EXPECT_CALL(fetcher, AddConsumer(_)).WillOnce(SaveArg<0>(&added_consumer)); - auto form_manager = base::MakeRefCounted<PasswordFormManager>( + auto form_manager = base::MakeUnique<PasswordFormManager>( password_manager(), client(), client()->driver(), *observed_form(), base::MakeUnique<MockFormSaver>(), &fetcher); EXPECT_EQ(form_manager.get(), added_consumer); EXPECT_CALL(fetcher, RemoveConsumer(form_manager.get())); - form_manager = nullptr; + form_manager.reset(); } // Check that if asked to take ownership of the same FormFetcher which it had @@ -3181,18 +3147,17 @@ TEST_F(PasswordFormManagerTest, GrabFetcher_Same) { auto fetcher = base::MakeUnique<MockFormFetcher>(); fetcher->Fetch(); - scoped_refptr<PasswordFormManager> form_manager( - base::MakeRefCounted<PasswordFormManager>( - password_manager(), client(), client()->driver(), *observed_form(), - base::MakeUnique<MockFormSaver>(), fetcher.get())); + PasswordFormManager form_manager( + password_manager(), client(), client()->driver(), *observed_form(), + base::MakeUnique<MockFormSaver>(), fetcher.get()); EXPECT_CALL(*fetcher, AddConsumer(_)).Times(0); EXPECT_CALL(*fetcher, RemoveConsumer(_)).Times(0); - form_manager->GrabFetcher(std::move(fetcher)); + form_manager.GrabFetcher(std::move(fetcher)); // There will be a RemoveConsumer call as soon as form_manager goes out of // scope, but the test needs to ensure that there is none as a result of // GrabFetcher. - Mock::VerifyAndClearExpectations(form_manager->form_fetcher()); + Mock::VerifyAndClearExpectations(form_manager.form_fetcher()); } // Check that if asked to take ownership of a different FormFetcher than which @@ -3224,16 +3189,15 @@ FormFetcher::Consumer* added_consumer = nullptr; EXPECT_CALL(old_fetcher, AddConsumer(_)) .WillOnce(SaveArg<0>(&added_consumer)); - scoped_refptr<PasswordFormManager> form_manager( - base::MakeRefCounted<PasswordFormManager>( - password_manager(), client(), client()->driver(), *observed_form(), - base::MakeUnique<MockFormSaver>(), &old_fetcher)); - EXPECT_EQ(form_manager.get(), added_consumer); + PasswordFormManager form_manager( + password_manager(), client(), client()->driver(), *observed_form(), + base::MakeUnique<MockFormSaver>(), &old_fetcher); + EXPECT_EQ(&form_manager, added_consumer); auto new_fetcher = base::MakeUnique<MockFormFetcher>(); - EXPECT_CALL(*new_fetcher, AddConsumer(form_manager.get())); - EXPECT_CALL(old_fetcher, RemoveConsumer(form_manager.get())); - form_manager->GrabFetcher(std::move(new_fetcher)); + EXPECT_CALL(*new_fetcher, AddConsumer(&form_manager)); + EXPECT_CALL(old_fetcher, RemoveConsumer(&form_manager)); + form_manager.GrabFetcher(std::move(new_fetcher)); } TEST_F(PasswordFormManagerTest, UploadSignInForm_WithAutofillTypes) { @@ -3250,10 +3214,9 @@ FakeFormFetcher fetcher; fetcher.Fetch(); - scoped_refptr<PasswordFormManager> form_manager( - base::MakeRefCounted<PasswordFormManager>( - password_manager(), client(), client()->driver(), *observed_form(), - base::MakeUnique<NiceMock<MockFormSaver>>(), &fetcher)); + PasswordFormManager form_manager( + password_manager(), client(), client()->driver(), *observed_form(), + base::MakeUnique<NiceMock<MockFormSaver>>(), &fetcher); fetcher.SetNonFederated(std::vector<const PasswordForm*>(), 0u); PasswordForm form_to_save(*observed_form()); @@ -3266,9 +3229,9 @@ client()->mock_driver()->mock_autofill_manager(); EXPECT_CALL(*mock_autofill_manager, StartUploadProcessPtr(_, _, true)) .WillOnce(WithArg<0>(SaveToUniquePtr(&uploaded_form_structure))); - form_manager->ProvisionallySave( + form_manager.ProvisionallySave( form_to_save, PasswordFormManager::IGNORE_OTHER_POSSIBLE_USERNAMES); - form_manager->Save(); + form_manager.Save(); ASSERT_EQ(2u, uploaded_form_structure->field_count()); autofill::ServerFieldTypeSet expected_types = {autofill::PASSWORD}; @@ -3288,10 +3251,9 @@ FakeFormFetcher fetcher; fetcher.Fetch(); - scoped_refptr<PasswordFormManager> form_manager( - base::MakeRefCounted<PasswordFormManager>( - password_manager(), client(), client()->driver(), *observed_form(), - base::MakeUnique<NiceMock<MockFormSaver>>(), &fetcher)); + PasswordFormManager form_manager( + password_manager(), client(), client()->driver(), *observed_form(), + base::MakeUnique<NiceMock<MockFormSaver>>(), &fetcher); fetcher.SetNonFederated(std::vector<const PasswordForm*>(), 0u); PasswordForm form_to_save(*observed_form()); @@ -3301,9 +3263,9 @@ auto* mock_autofill_manager = client()->mock_driver()->mock_autofill_manager(); EXPECT_CALL(*mock_autofill_manager, StartUploadProcessPtr(_, _, _)).Times(0); - form_manager->ProvisionallySave( + form_manager.ProvisionallySave( form_to_save, PasswordFormManager::IGNORE_OTHER_POSSIBLE_USERNAMES); - form_manager->Save(); + form_manager.Save(); } TEST_F(PasswordFormManagerTest, @@ -3312,12 +3274,12 @@ fake_form_fetcher()->set_did_complete_querying_suppressed_forms(false); fake_form_fetcher()->Fetch(); - scoped_refptr<PasswordFormManager> form_manager( - base::MakeRefCounted<PasswordFormManager>( + std::unique_ptr<PasswordFormManager> form_manager = + base::MakeUnique<PasswordFormManager>( password_manager(), client(), client()->driver(), *observed_form(), - base::MakeUnique<NiceMock<MockFormSaver>>(), fake_form_fetcher())); + base::MakeUnique<NiceMock<MockFormSaver>>(), fake_form_fetcher()); fake_form_fetcher()->SetNonFederated(std::vector<const PasswordForm*>(), 0u); - form_manager = nullptr; + form_manager.reset(); histogram_tester.ExpectUniqueSample( "PasswordManager.QueryingSuppressedAccountsFinished", false, 1); @@ -3510,12 +3472,12 @@ fetcher.set_did_complete_querying_suppressed_forms(true); fetcher.Fetch(); - scoped_refptr<PasswordFormManager> form_manager = - base::MakeRefCounted<PasswordFormManager>( + std::unique_ptr<PasswordFormManager> form_manager = + base::MakeUnique<PasswordFormManager>( password_manager(), client(), client()->driver(), https_observed_form, base::MakeUnique<NiceMock<MockFormSaver>>(), &fetcher); fetcher.SetNonFederated(std::vector<const PasswordForm*>(), 0u); - form_manager = nullptr; + form_manager.reset(); histogram_tester.ExpectUniqueSample( "PasswordManager.QueryingSuppressedAccountsFinished", true, 1);
diff --git a/components/password_manager/core/browser/password_manager.cc b/components/password_manager/core/browser/password_manager.cc index df1208d..804aa5d 100644 --- a/components/password_manager/core/browser/password_manager.cc +++ b/components/password_manager/core/browser/password_manager.cc
@@ -238,7 +238,7 @@ // If there is no corresponding PasswordFormManager, we create one. This is // not the common case, and should only happen when there is a bug in our // ability to detect forms. - auto manager = base::MakeRefCounted<PasswordFormManager>( + auto manager = base::MakeUnique<PasswordFormManager>( this, client_, driver->AsWeakPtr(), form, base::WrapUnique(new FormSaverImpl(client_->GetPasswordStore())), nullptr); @@ -349,9 +349,11 @@ return; } - // Copy ownership of the manager from |pending_login_managers_| to + std::unique_ptr<PasswordFormManager> manager; + // Transfer ownership of the manager from |pending_login_managers_| to // |manager|. - scoped_refptr<PasswordFormManager> manager(*matched_manager_it); + manager.swap(*matched_manager_it); + pending_login_managers_.erase(matched_manager_it); PasswordForm submitted_form(form); submitted_form.preferred = true; @@ -408,7 +410,7 @@ void PasswordManager::DropFormManagers() { pending_login_managers_.clear(); - provisional_save_manager_ = nullptr; + provisional_save_manager_.reset(); all_visible_forms_.clear(); } @@ -565,7 +567,7 @@ if (logger) logger->LogFormSignatures(Logger::STRING_ADDING_SIGNATURE, *iter); - auto manager = base::MakeRefCounted<PasswordFormManager>( + auto manager = base::MakeUnique<PasswordFormManager>( this, client_, (driver ? driver->AsWeakPtr() : base::WeakPtr<PasswordManagerDriver>()), *iter, base::WrapUnique(new FormSaverImpl(client_->GetPasswordStore())), @@ -601,7 +603,7 @@ RecordFailure(MATCHING_NOT_COMPLETE, provisional_save_manager_->observed_form().origin, logger.get()); - provisional_save_manager_ = nullptr; + provisional_save_manager_.reset(); return false; } return true; @@ -648,7 +650,7 @@ if (logger) logger->LogMessage(Logger::STRING_DECISION_DROP); provisional_save_manager_->LogSubmitFailed(); - provisional_save_manager_ = nullptr; + provisional_save_manager_.reset(); return; } @@ -685,7 +687,7 @@ all_visible_forms_[i]); logger->LogMessage(Logger::STRING_DECISION_DROP); } - provisional_save_manager_ = nullptr; + provisional_save_manager_.reset(); // Clear all_visible_forms_ once we found the match. all_visible_forms_.clear(); return; @@ -752,7 +754,7 @@ RecordFailure(SYNC_CREDENTIAL, provisional_save_manager_->observed_form().origin, logger.get()); - provisional_save_manager_ = nullptr; + provisional_save_manager_.reset(); return; } } @@ -792,7 +794,7 @@ if (provisional_save_manager_->has_generated_password()) { client_->AutomaticPasswordSave(std::move(provisional_save_manager_)); } else { - provisional_save_manager_ = nullptr; + provisional_save_manager_.reset(); } } }
diff --git a/components/password_manager/core/browser/password_manager.h b/components/password_manager/core/browser/password_manager.h index 30990f69..b85165d 100644 --- a/components/password_manager/core/browser/password_manager.h +++ b/components/password_manager/core/browser/password_manager.h
@@ -13,7 +13,6 @@ #include "base/callback.h" #include "base/gtest_prod_util.h" #include "base/macros.h" -#include "base/memory/ref_counted.h" #include "base/observer_list.h" #include "base/strings/string16.h" #include "build/build_config.h" @@ -185,7 +184,7 @@ #if defined(UNIT_TEST) // TODO(crbug.com/639786): Replace using this by quering the factory for // mocked PasswordFormManagers. - const std::vector<scoped_refptr<PasswordFormManager>>& + const std::vector<std::unique_ptr<PasswordFormManager>>& pending_login_managers() { return pending_login_managers_; } @@ -267,7 +266,7 @@ // When a form is "seen" on a page, a PasswordFormManager is created // and stored in this collection until user navigates away from page. - std::vector<scoped_refptr<PasswordFormManager>> pending_login_managers_; + std::vector<std::unique_ptr<PasswordFormManager>> pending_login_managers_; // When the user submits a password/credential, this contains the // PasswordFormManager for the form in question until we deem the login @@ -275,7 +274,7 @@ // send the PasswordFormManager back to the pending_login_managers_ set. // Scoped in case PasswordManager gets deleted (e.g tab closes) between the // time a user submits a login form and gets to the next page. - scoped_refptr<PasswordFormManager> provisional_save_manager_; + std::unique_ptr<PasswordFormManager> provisional_save_manager_; // The embedder-level client. Must outlive this class. PasswordManagerClient* const client_;
diff --git a/components/password_manager/core/browser/password_manager_client.h b/components/password_manager/core/browser/password_manager_client.h index 405202d..7004aee79 100644 --- a/components/password_manager/core/browser/password_manager_client.h +++ b/components/password_manager/core/browser/password_manager_client.h
@@ -9,7 +9,6 @@ #include "base/callback.h" #include "base/macros.h" -#include "base/memory/ref_counted.h" #include "components/autofill/core/common/password_form.h" #include "components/password_manager/core/browser/credentials_filter.h" #include "components/password_manager/core/browser/password_store.h" @@ -92,7 +91,7 @@ // and form_to_save.pending_credentials() should correspond to the credential // that was overidden. virtual bool PromptUserToSaveOrUpdatePassword( - scoped_refptr<PasswordFormManager> form_to_save, + std::unique_ptr<PasswordFormManager> form_to_save, bool update_password) = 0; // Informs the embedder of a password forms that the user should choose from. @@ -137,7 +136,7 @@ // Called when a password is saved in an automated fashion. Embedder may // inform the user that this save has occured. virtual void AutomaticPasswordSave( - scoped_refptr<PasswordFormManager> saved_form_manager) = 0; + std::unique_ptr<PasswordFormManager> saved_form_manager) = 0; // Called when a password is autofilled. |best_matches| contains the // PasswordForm into which a password was filled: the client may choose to
diff --git a/components/password_manager/core/browser/password_manager_unittest.cc b/components/password_manager/core/browser/password_manager_unittest.cc index f1b9c07..d0895e8c8 100644 --- a/components/password_manager/core/browser/password_manager_unittest.cc +++ b/components/password_manager/core/browser/password_manager_unittest.cc
@@ -61,8 +61,9 @@ MOCK_CONST_METHOD0(IsSavingAndFillingEnabledForCurrentPage, bool()); MOCK_CONST_METHOD0(DidLastPageLoadEncounterSSLErrors, bool()); MOCK_CONST_METHOD0(GetPasswordStore, PasswordStore*()); - MOCK_METHOD2(PromptUserToSaveOrUpdatePassword, - bool(scoped_refptr<PasswordFormManager>, bool)); + // The code inside EXPECT_CALL for PromptUserToSaveOrUpdatePasswordPtr owns + // the PasswordFormManager* argument. + MOCK_METHOD1(PromptUserToSaveOrUpdatePasswordPtr, void(PasswordFormManager*)); MOCK_METHOD1(NotifySuccessfulLoginWithExistingPassword, void(const autofill::PasswordForm&)); MOCK_METHOD0(AutomaticPasswordSaveIndicator, void()); @@ -71,8 +72,15 @@ MOCK_METHOD0(GetDriver, PasswordManagerDriver*()); MOCK_CONST_METHOD0(GetStoreResultFilter, const MockStoreResultFilter*()); + // Workaround for std::unique_ptr<> lacking a copy constructor. + bool PromptUserToSaveOrUpdatePassword( + std::unique_ptr<PasswordFormManager> manager, + bool update_password) override { + PromptUserToSaveOrUpdatePasswordPtr(manager.release()); + return false; + } void AutomaticPasswordSave( - scoped_refptr<PasswordFormManager> manager) override { + std::unique_ptr<PasswordFormManager> manager) override { AutomaticPasswordSaveIndicator(); } @@ -102,6 +110,8 @@ arg0->OnGetPasswordStoreResults(std::vector<std::unique_ptr<PasswordForm>>()); } +ACTION_P(SaveToScopedPtr, scoped) { scoped->reset(arg0); } + } // namespace class PasswordManagerTest : public testing::Test { @@ -261,9 +271,9 @@ .WillRepeatedly(Return(true)); OnPasswordFormSubmitted(form); - scoped_refptr<PasswordFormManager> form_manager_to_save; - EXPECT_CALL(client_, PromptUserToSaveOrUpdatePassword(_, _)) - .WillOnce(DoAll(SaveArg<0>(&form_manager_to_save), Return(false))); + std::unique_ptr<PasswordFormManager> form_manager_to_save; + EXPECT_CALL(client_, PromptUserToSaveOrUpdatePasswordPtr(_)) + .WillOnce(WithArg<0>(SaveToScopedPtr(&form_manager_to_save))); // Now the password manager waits for the navigation to complete. observed.clear(); @@ -303,7 +313,7 @@ // consent by using the generated password. The form should be saved once // navigation occurs. The client will be informed that automatic saving has // occured. - EXPECT_CALL(client_, PromptUserToSaveOrUpdatePassword(_, _)).Times(0); + EXPECT_CALL(client_, PromptUserToSaveOrUpdatePasswordPtr(_)).Times(0); PasswordForm form_to_save; EXPECT_CALL(*store_, AddLogin(_)).WillOnce(SaveArg<0>(&form_to_save)); EXPECT_CALL(client_, AutomaticPasswordSaveIndicator()); @@ -339,9 +349,9 @@ OnPasswordFormSubmitted(form); // We still expect an add, since we didn't have a good match. - scoped_refptr<PasswordFormManager> form_manager_to_save; - EXPECT_CALL(client_, PromptUserToSaveOrUpdatePassword(_, _)) - .WillOnce(DoAll(SaveArg<0>(&form_manager_to_save), Return(false))); + std::unique_ptr<PasswordFormManager> form_manager_to_save; + EXPECT_CALL(client_, PromptUserToSaveOrUpdatePasswordPtr(_)) + .WillOnce(WithArg<0>(SaveToScopedPtr(&form_manager_to_save))); // Now the password manager waits for the navigation to complete. observed.clear(); @@ -365,7 +375,7 @@ // No message from the renderer that a password was submitted. No // expected calls. - EXPECT_CALL(client_, PromptUserToSaveOrUpdatePassword(_, _)).Times(0); + EXPECT_CALL(client_, PromptUserToSaveOrUpdatePasswordPtr(_)).Times(0); observed.clear(); manager()->OnPasswordFormsParsed(&driver_, observed); manager()->OnPasswordFormsRendered(&driver_, observed, true); @@ -387,9 +397,9 @@ .WillRepeatedly(Return(true)); OnPasswordFormSubmitted(form); - scoped_refptr<PasswordFormManager> form_manager_to_save; - EXPECT_CALL(client_, PromptUserToSaveOrUpdatePassword(_, _)) - .WillOnce(DoAll(SaveArg<0>(&form_manager_to_save), Return(false))); + std::unique_ptr<PasswordFormManager> form_manager_to_save; + EXPECT_CALL(client_, PromptUserToSaveOrUpdatePasswordPtr(_)) + .WillOnce(WithArg<0>(SaveToScopedPtr(&form_manager_to_save))); observed.clear(); manager()->OnPasswordFormsParsed(&driver_, observed); @@ -436,9 +446,9 @@ .WillRepeatedly(Return(true)); OnPasswordFormSubmitted(second_form); - scoped_refptr<PasswordFormManager> form_manager_to_save; - EXPECT_CALL(client_, PromptUserToSaveOrUpdatePassword(_, _)) - .WillOnce(DoAll(SaveArg<0>(&form_manager_to_save), Return(false))); + std::unique_ptr<PasswordFormManager> form_manager_to_save; + EXPECT_CALL(client_, PromptUserToSaveOrUpdatePasswordPtr(_)) + .WillOnce(WithArg<0>(SaveToScopedPtr(&form_manager_to_save))); // Navigation after form submit, no forms appear. observed.clear(); manager()->OnPasswordFormsParsed(&driver_, observed); @@ -467,9 +477,9 @@ OnPasswordFormSubmitted(form); // Expect info bar to appear: - scoped_refptr<PasswordFormManager> form_manager_to_save; - EXPECT_CALL(client_, PromptUserToSaveOrUpdatePassword(_, _)) - .WillOnce(DoAll(SaveArg<0>(&form_manager_to_save), Return(false))); + std::unique_ptr<PasswordFormManager> form_manager_to_save; + EXPECT_CALL(client_, PromptUserToSaveOrUpdatePasswordPtr(_)) + .WillOnce(WithArg<0>(SaveToScopedPtr(&form_manager_to_save))); // The form reappears, but is not visible in the layout: manager()->OnPasswordFormsParsed(&driver_, observed); @@ -541,7 +551,7 @@ observed.push_back(MakeTwitterFailedLoginForm()); // A PasswordForm appears, and is visible in the layout: // No expected calls to the PasswordStore... - EXPECT_CALL(client_, PromptUserToSaveOrUpdatePassword(_, _)).Times(0); + EXPECT_CALL(client_, PromptUserToSaveOrUpdatePasswordPtr(_)).Times(0); EXPECT_CALL(client_, AutomaticPasswordSaveIndicator()).Times(0); EXPECT_CALL(*store_, AddLogin(_)).Times(0); EXPECT_CALL(*store_, UpdateLogin(_)).Times(0); @@ -561,7 +571,7 @@ manager()->OnPasswordFormsRendered(&driver_, observed, true); // User should not be prompted and password should not be saved. - EXPECT_CALL(client_, PromptUserToSaveOrUpdatePassword(_, _)).Times(0); + EXPECT_CALL(client_, PromptUserToSaveOrUpdatePasswordPtr(_)).Times(0); EXPECT_CALL(*store_, AddLogin(_)).Times(0); // Prefs are needed for failure logging about sync credentials. EXPECT_CALL(client_, GetPrefs()).WillRepeatedly(Return(nullptr)); @@ -588,7 +598,7 @@ // |observed_form| and not the |stored_form| what is passed to ShouldSave. observed_form.username_element += ASCIIToUTF16("1"); observed.push_back(observed_form); - EXPECT_CALL(driver_, FillPasswordForm(_)).Times(3); + EXPECT_CALL(driver_, FillPasswordForm(_)).Times(2); // Simulate that |form| is already in the store, making this an update. EXPECT_CALL(*store_, GetLogins(_, _)) .WillRepeatedly(WithArg<1>(InvokeConsumer(stored_form))); @@ -674,7 +684,7 @@ // Because the user successfully uses an updated sync password, Chrome should // remove the obsolete copy of it. EXPECT_CALL(*store_, RemoveLogin(form)); - EXPECT_CALL(client_, PromptUserToSaveOrUpdatePassword(_, _)).Times(0); + EXPECT_CALL(client_, PromptUserToSaveOrUpdatePasswordPtr(_)).Times(0); observed.clear(); manager()->OnPasswordFormsParsed(&driver_, observed); manager()->OnPasswordFormsRendered(&driver_, observed, true); @@ -711,7 +721,7 @@ first_form.origin = GURL("http://www.xda-developers.com/"); first_form.action = GURL("http://forum.xda-developers.com/login.php"); - // |second_form|'s action differs only with it's scheme i.e. "https://". + // |second_form|'s action differs only with it's scheme i.e. *https://*. PasswordForm second_form(first_form); second_form.action = GURL("https://forum.xda-developers.com/login.php"); @@ -732,7 +742,7 @@ observed.push_back(second_form); // Verify that no prompt to save the password is shown. - EXPECT_CALL(client_, PromptUserToSaveOrUpdatePassword(_, _)).Times(0); + EXPECT_CALL(client_, PromptUserToSaveOrUpdatePasswordPtr(_)).Times(0); manager()->OnPasswordFormsParsed(&driver_, observed); manager()->OnPasswordFormsRendered(&driver_, observed, true); } @@ -804,9 +814,9 @@ // Make sure |PromptUserToSaveOrUpdatePassword| gets called, and the resulting // form manager is saved. - scoped_refptr<PasswordFormManager> form_manager_to_save; - EXPECT_CALL(client_, PromptUserToSaveOrUpdatePassword(_, _)) - .WillOnce(DoAll(SaveArg<0>(&form_manager_to_save), Return(false))); + std::unique_ptr<PasswordFormManager> form_manager_to_save; + EXPECT_CALL(client_, PromptUserToSaveOrUpdatePasswordPtr(_)) + .WillOnce(WithArg<0>(SaveToScopedPtr(&form_manager_to_save))); EXPECT_CALL(client_, GetMainFrameURL()) .WillRepeatedly(ReturnRef(insecure_form.origin)); @@ -819,7 +829,7 @@ // Expect no further calls to |ProptUserToSaveOrUpdatePassword| due to // insecure origin. - EXPECT_CALL(client_, PromptUserToSaveOrUpdatePassword(_, _)).Times(0); + EXPECT_CALL(client_, PromptUserToSaveOrUpdatePasswordPtr(_)).Times(0); // Trigger call to |ProvisionalSavePassword| by rendering a page without // forms. @@ -855,9 +865,9 @@ .WillRepeatedly(Return(true)); OnPasswordFormSubmitted(form); - scoped_refptr<PasswordFormManager> form_manager_to_save; - EXPECT_CALL(client_, PromptUserToSaveOrUpdatePassword(_, _)) - .WillOnce(DoAll(SaveArg<0>(&form_manager_to_save), Return(false))); + std::unique_ptr<PasswordFormManager> form_manager_to_save; + EXPECT_CALL(client_, PromptUserToSaveOrUpdatePasswordPtr(_)) + .WillOnce(WithArg<0>(SaveToScopedPtr(&form_manager_to_save))); // Now the password manager waits for the login to complete successfully. observed.clear(); @@ -888,9 +898,9 @@ .WillRepeatedly(Return(true)); OnPasswordFormSubmitted(form); - scoped_refptr<PasswordFormManager> form_manager_to_save; - EXPECT_CALL(client_, PromptUserToSaveOrUpdatePassword(_, _)) - .WillOnce(DoAll(SaveArg<0>(&form_manager_to_save), Return(false))); + std::unique_ptr<PasswordFormManager> form_manager_to_save; + EXPECT_CALL(client_, PromptUserToSaveOrUpdatePasswordPtr(_)) + .WillOnce(WithArg<0>(SaveToScopedPtr(&form_manager_to_save))); // Now the password manager waits for the navigation to complete. observed.clear(); @@ -931,23 +941,19 @@ PasswordForm form(MakeSimpleForm()); observed.push_back(form); EXPECT_CALL(*store_, GetLogins(_, _)) - .Times(2) - .WillRepeatedly(WithArg<1>(InvokeEmptyConsumerWithForms())); + .WillOnce(WithArg<1>(InvokeEmptyConsumerWithForms())); manager()->OnPasswordFormsParsed(&driver_, observed); manager()->OnPasswordFormsRendered(&driver_, observed, true); EXPECT_CALL(client_, IsSavingAndFillingEnabledForCurrentPage()) .WillRepeatedly(Return(true)); - scoped_refptr<PasswordFormManager> form_manager_to_save; - EXPECT_CALL(client_, PromptUserToSaveOrUpdatePassword(_, _)) - .WillOnce(DoAll(SaveArg<0>(&form_manager_to_save), Return(false))); + std::unique_ptr<PasswordFormManager> form_manager_to_save; + EXPECT_CALL(client_, PromptUserToSaveOrUpdatePasswordPtr(_)) + .WillOnce(WithArg<0>(SaveToScopedPtr(&form_manager_to_save))); manager()->OnInPageNavigation(&driver_, form); - // Checks |form_manager_to_save| is still in |pending_login_managers_|. - EXPECT_EQ(1u, manager()->pending_login_managers().size()); - // Simulate saving the form, as if the info bar was accepted. EXPECT_CALL(*store_, AddLogin(FormMatches(form))); ASSERT_TRUE(form_manager_to_save); @@ -974,9 +980,9 @@ // Prefs are needed for failure logging about blacklisting. EXPECT_CALL(client_, GetPrefs()).WillRepeatedly(Return(nullptr)); - scoped_refptr<PasswordFormManager> form_manager_to_save; - EXPECT_CALL(client_, PromptUserToSaveOrUpdatePassword(_, _)) - .WillOnce(DoAll(SaveArg<0>(&form_manager_to_save), Return(false))); + std::unique_ptr<PasswordFormManager> form_manager_to_save; + EXPECT_CALL(client_, PromptUserToSaveOrUpdatePasswordPtr(_)) + .WillOnce(WithArg<0>(SaveToScopedPtr(&form_manager_to_save))); manager()->OnInPageNavigation(&driver_, form); EXPECT_TRUE(form_manager_to_save->IsBlacklisted()); @@ -1009,9 +1015,9 @@ .WillRepeatedly(Return(true)); OnPasswordFormSubmitted(submitted_form); - scoped_refptr<PasswordFormManager> form_manager_to_save; - EXPECT_CALL(client_, PromptUserToSaveOrUpdatePassword(_, _)) - .WillOnce(DoAll(SaveArg<0>(&form_manager_to_save), Return(false))); + std::unique_ptr<PasswordFormManager> form_manager_to_save; + EXPECT_CALL(client_, PromptUserToSaveOrUpdatePasswordPtr(_)) + .WillOnce(WithArg<0>(SaveToScopedPtr(&form_manager_to_save))); // Now the password manager waits for the navigation to complete. observed.clear(); @@ -1062,9 +1068,9 @@ .WillRepeatedly(Return(true)); OnPasswordFormSubmitted(submitted_form); - scoped_refptr<PasswordFormManager> form_manager_to_save; - EXPECT_CALL(client_, PromptUserToSaveOrUpdatePassword(_, _)) - .WillOnce(DoAll(SaveArg<0>(&form_manager_to_save), Return(false))); + std::unique_ptr<PasswordFormManager> form_manager_to_save; + EXPECT_CALL(client_, PromptUserToSaveOrUpdatePasswordPtr(_)) + .WillOnce(WithArg<0>(SaveToScopedPtr(&form_manager_to_save))); // Now the password manager waits for the navigation to complete. observed.clear(); @@ -1114,9 +1120,9 @@ .WillRepeatedly(Return(true)); OnPasswordFormSubmitted(form); - scoped_refptr<PasswordFormManager> form_manager_to_save; - EXPECT_CALL(client_, PromptUserToSaveOrUpdatePassword(_, _)) - .WillOnce(DoAll(SaveArg<0>(&form_manager_to_save), Return(false))); + std::unique_ptr<PasswordFormManager> form_manager_to_save; + EXPECT_CALL(client_, PromptUserToSaveOrUpdatePasswordPtr(_)) + .WillOnce(WithArg<0>(SaveToScopedPtr(&form_manager_to_save))); // Now the password manager waits for the navigation to complete. observed.clear(); @@ -1147,7 +1153,7 @@ autofill::PasswordForm updated_form; autofill::PasswordForm notified_form; - EXPECT_CALL(client_, PromptUserToSaveOrUpdatePassword(_, _)).Times(0); + EXPECT_CALL(client_, PromptUserToSaveOrUpdatePasswordPtr(_)).Times(0); EXPECT_CALL(*store_, UpdateLogin(_)).WillOnce(SaveArg<0>(&updated_form)); EXPECT_CALL(client_, NotifySuccessfulLoginWithExistingPassword(_)) .WillOnce(SaveArg<0>(¬ified_form)); @@ -1187,9 +1193,9 @@ static_cast<FormFetcherImpl*>(form_manager->form_fetcher()) ->OnGetPasswordStoreResults(std::vector<std::unique_ptr<PasswordForm>>()); - scoped_refptr<PasswordFormManager> form_manager_to_save; - EXPECT_CALL(client_, PromptUserToSaveOrUpdatePassword(_, _)) - .WillOnce(DoAll(SaveArg<0>(&form_manager_to_save), Return(false))); + std::unique_ptr<PasswordFormManager> form_manager_to_save; + EXPECT_CALL(client_, PromptUserToSaveOrUpdatePasswordPtr(_)) + .WillOnce(WithArg<0>(SaveToScopedPtr(&form_manager_to_save))); // Now the password manager waits for the navigation to complete. observed.clear(); @@ -1216,7 +1222,7 @@ manager()->SetHasGeneratedPasswordForForm(&driver_, form, true); // Do not save generated password when the password form reappears. - EXPECT_CALL(client_, PromptUserToSaveOrUpdatePassword(_, _)).Times(0); + EXPECT_CALL(client_, PromptUserToSaveOrUpdatePasswordPtr(_)).Times(0); EXPECT_CALL(*store_, AddLogin(_)).Times(0); EXPECT_CALL(client_, AutomaticPasswordSaveIndicator()).Times(0); @@ -1248,7 +1254,7 @@ OnPasswordFormSubmitted(form); // Do not save generated password when the password form reappears. - EXPECT_CALL(client_, PromptUserToSaveOrUpdatePassword(_, _)).Times(0); + EXPECT_CALL(client_, PromptUserToSaveOrUpdatePasswordPtr(_)).Times(0); EXPECT_CALL(*store_, AddLogin(_)).Times(0); EXPECT_CALL(client_, AutomaticPasswordSaveIndicator()).Times(0); @@ -1282,7 +1288,7 @@ OnPasswordFormSubmitted(form); // No infobar or prompt is shown if submission fails. - EXPECT_CALL(client_, PromptUserToSaveOrUpdatePassword(_, _)).Times(0); + EXPECT_CALL(client_, PromptUserToSaveOrUpdatePasswordPtr(_)).Times(0); EXPECT_CALL(client_, AutomaticPasswordSaveIndicator()).Times(0); // Simulate submission failing, with the same form being visible after @@ -1314,9 +1320,9 @@ OnPasswordFormSubmitted(form); // Verify that a normal prompt is shown instead of the force saving UI. - scoped_refptr<PasswordFormManager> form_to_save; - EXPECT_CALL(client_, PromptUserToSaveOrUpdatePassword(_, _)) - .WillOnce(DoAll(SaveArg<0>(&form_to_save), Return(false))); + std::unique_ptr<PasswordFormManager> form_to_save; + EXPECT_CALL(client_, PromptUserToSaveOrUpdatePasswordPtr(_)) + .WillOnce(WithArg<0>(SaveToScopedPtr(&form_to_save))); EXPECT_CALL(client_, AutomaticPasswordSaveIndicator()).Times(0); // Simulate a successful submission. @@ -1344,7 +1350,7 @@ form.username_value = ASCIIToUTF16("new_username"); OnPasswordFormSubmitted(form); - EXPECT_CALL(client_, PromptUserToSaveOrUpdatePassword(_, _)).Times(0); + EXPECT_CALL(client_, PromptUserToSaveOrUpdatePasswordPtr(_)).Times(0); PasswordForm form_to_save; EXPECT_CALL(*store_, AddLogin(_)).WillOnce(SaveArg<0>(&form_to_save)); EXPECT_CALL(client_, AutomaticPasswordSaveIndicator()); @@ -1407,12 +1413,12 @@ .WillRepeatedly(WithArg<1>(InvokeEmptyConsumerWithForms())); EXPECT_CALL(*store_, GetLoginsForSameOrganizationName(_, _)); } - scoped_refptr<PasswordFormManager> form_manager; + std::unique_ptr<PasswordFormManager> form_manager; if (found_matched_logins_in_store) { - EXPECT_CALL(client_, PromptUserToSaveOrUpdatePassword(_, _)) - .WillOnce(DoAll(SaveArg<0>(&form_manager), Return(false))); + EXPECT_CALL(client_, PromptUserToSaveOrUpdatePasswordPtr(_)) + .WillOnce(WithArg<0>(SaveToScopedPtr(&form_manager))); } else { - EXPECT_CALL(client_, PromptUserToSaveOrUpdatePassword(_, _)).Times(0); + EXPECT_CALL(client_, PromptUserToSaveOrUpdatePasswordPtr(_)).Times(0); } EXPECT_CALL(client_, AutomaticPasswordSaveIndicator()) .Times(found_matched_logins_in_store ? 0 : 1); @@ -1479,11 +1485,11 @@ manager()->OnPasswordFormsParsed(&driver_, observed); manager()->OnPasswordFormsRendered(&driver_, observed, true); - scoped_refptr<PasswordFormManager> form_manager_to_save; + std::unique_ptr<PasswordFormManager> form_manager_to_save; EXPECT_CALL(client_, IsSavingAndFillingEnabledForCurrentPage()) .WillRepeatedly(Return(true)); - EXPECT_CALL(client_, PromptUserToSaveOrUpdatePassword(_, _)) - .WillOnce(DoAll(SaveArg<0>(&form_manager_to_save), Return(false))); + EXPECT_CALL(client_, PromptUserToSaveOrUpdatePasswordPtr(_)) + .WillOnce(WithArg<0>(SaveToScopedPtr(&form_manager_to_save))); manager()->OnPasswordFormForceSaveRequested(&driver_, form); ASSERT_TRUE(form_manager_to_save); EXPECT_EQ(form.password_value, @@ -1508,7 +1514,7 @@ EXPECT_CALL(client_, IsSavingAndFillingEnabledForCurrentPage()) .WillRepeatedly(Return(true)); - EXPECT_CALL(client_, PromptUserToSaveOrUpdatePassword(_, _)).Times(0); + EXPECT_CALL(client_, PromptUserToSaveOrUpdatePasswordPtr(_)).Times(0); manager()->OnPasswordFormForceSaveRequested(&driver_, empty_password_form); } @@ -1549,7 +1555,7 @@ .WillRepeatedly(Return(true)); OnPasswordFormSubmitted(form); - EXPECT_CALL(client_, PromptUserToSaveOrUpdatePassword(_, _)).Times(0); + EXPECT_CALL(client_, PromptUserToSaveOrUpdatePasswordPtr(_)).Times(0); observed.clear(); manager()->OnPasswordFormsParsed(&driver_, observed); manager()->OnPasswordFormsRendered(&driver_, observed, true); @@ -1585,7 +1591,7 @@ PasswordForm saved_form; PasswordForm saved_notified_form; EXPECT_CALL(*store_, UpdateLogin(_)).WillOnce(SaveArg<0>(&saved_form)); - EXPECT_CALL(client_, PromptUserToSaveOrUpdatePassword(_, _)).Times(0); + EXPECT_CALL(client_, PromptUserToSaveOrUpdatePasswordPtr(_)).Times(0); EXPECT_CALL(client_, NotifySuccessfulLoginWithExistingPassword(_)) .WillOnce(SaveArg<0>(&saved_notified_form)); EXPECT_CALL(*store_, AddLogin(_)).Times(0); @@ -1623,9 +1629,9 @@ filled_form.password_value = ASCIIToUTF16("new_password"); OnPasswordFormSubmitted(filled_form); - scoped_refptr<PasswordFormManager> form_manager_to_save; - EXPECT_CALL(client_, PromptUserToSaveOrUpdatePassword(_, _)) - .WillOnce(DoAll(SaveArg<0>(&form_manager_to_save), Return(false))); + std::unique_ptr<PasswordFormManager> form_manager_to_save; + EXPECT_CALL(client_, PromptUserToSaveOrUpdatePasswordPtr(_)) + .WillOnce(WithArg<0>(SaveToScopedPtr(&form_manager_to_save))); observed_forms.clear(); manager()->OnPasswordFormsParsed(&driver_, observed_forms); @@ -1674,9 +1680,9 @@ observed[0].new_password_value.clear(); // Check success of the submission. - scoped_refptr<PasswordFormManager> form_manager_to_save; - EXPECT_CALL(client_, PromptUserToSaveOrUpdatePassword(_, _)) - .WillOnce(DoAll(SaveArg<0>(&form_manager_to_save), Return(false))); + std::unique_ptr<PasswordFormManager> form_manager_to_save; + EXPECT_CALL(client_, PromptUserToSaveOrUpdatePasswordPtr(_)) + .WillOnce(WithArg<0>(SaveToScopedPtr(&form_manager_to_save))); manager()->OnPasswordFormsParsed(&driver_, observed); manager()->OnPasswordFormsRendered(&driver_, observed, true);
diff --git a/components/password_manager/core/browser/stub_password_manager_client.cc b/components/password_manager/core/browser/stub_password_manager_client.cc index 432d115..309c877e 100644 --- a/components/password_manager/core/browser/stub_password_manager_client.cc +++ b/components/password_manager/core/browser/stub_password_manager_client.cc
@@ -16,7 +16,7 @@ StubPasswordManagerClient::~StubPasswordManagerClient() {} bool StubPasswordManagerClient::PromptUserToSaveOrUpdatePassword( - scoped_refptr<PasswordFormManager> form_to_save, + std::unique_ptr<PasswordFormManager> form_to_save, bool update_password) { return false; } @@ -41,7 +41,7 @@ void StubPasswordManagerClient::NotifyStorePasswordCalled() {} void StubPasswordManagerClient::AutomaticPasswordSave( - scoped_refptr<PasswordFormManager> saved_manager) {} + std::unique_ptr<PasswordFormManager> saved_manager) {} PrefService* StubPasswordManagerClient::GetPrefs() { return nullptr;
diff --git a/components/password_manager/core/browser/stub_password_manager_client.h b/components/password_manager/core/browser/stub_password_manager_client.h index 4cfb70e..77c740b 100644 --- a/components/password_manager/core/browser/stub_password_manager_client.h +++ b/components/password_manager/core/browser/stub_password_manager_client.h
@@ -22,7 +22,7 @@ // PasswordManagerClient: bool PromptUserToSaveOrUpdatePassword( - scoped_refptr<PasswordFormManager> form_to_save, + std::unique_ptr<PasswordFormManager> form_to_save, bool update_password) override; bool PromptUserToChooseCredentials( std::vector<std::unique_ptr<autofill::PasswordForm>> local_forms, @@ -37,7 +37,7 @@ const autofill::PasswordForm& form) override; void NotifyStorePasswordCalled() override; void AutomaticPasswordSave( - scoped_refptr<PasswordFormManager> saved_manager) override; + std::unique_ptr<PasswordFormManager> saved_manager) override; PrefService* GetPrefs() override; PasswordStore* GetPasswordStore() const override; const GURL& GetLastCommittedEntryURL() const override;
diff --git a/components/password_manager/sync/browser/sync_credentials_filter_unittest.cc b/components/password_manager/sync/browser/sync_credentials_filter_unittest.cc index 1ae27e47..2830c55 100644 --- a/components/password_manager/sync/browser/sync_credentials_filter_unittest.cc +++ b/components/password_manager/sync/browser/sync_credentials_filter_unittest.cc
@@ -96,13 +96,12 @@ CredentialsFilterTest() : password_manager_(&client_), pending_(SimpleGaiaForm("user@gmail.com")), - form_manager_(base::MakeRefCounted<PasswordFormManager>( - &password_manager_, - &client_, - driver_.AsWeakPtr(), - pending_, - base::MakeUnique<StubFormSaver>(), - &fetcher_)), + form_manager_(&password_manager_, + &client_, + driver_.AsWeakPtr(), + pending_, + base::MakeUnique<StubFormSaver>(), + &fetcher_), filter_(&client_, base::Bind(&SyncUsernameTestBase::sync_service, base::Unretained(this)), @@ -139,7 +138,7 @@ } fetcher_.SetNonFederated(matches, 0u); - form_manager_->ProvisionallySave( + form_manager_.ProvisionallySave( pending_, PasswordFormManager::IGNORE_OTHER_POSSIBLE_USERNAMES); } @@ -149,7 +148,7 @@ StubPasswordManagerDriver driver_; PasswordForm pending_; FakeFormFetcher fetcher_; - scoped_refptr<PasswordFormManager> form_manager_; + PasswordFormManager form_manager_; SyncCredentialsFilter filter_; }; @@ -287,7 +286,7 @@ base::UserActionTester tester; SavePending(LoginState::EXISTING); - filter_.ReportFormLoginSuccess(*form_manager_); + filter_.ReportFormLoginSuccess(form_manager_); EXPECT_EQ(1, tester.GetActionCount(kFilledAndLoginActionName)); } @@ -297,7 +296,7 @@ base::UserActionTester tester; SavePending(LoginState::NEW); - filter_.ReportFormLoginSuccess(*form_manager_); + filter_.ReportFormLoginSuccess(form_manager_); EXPECT_EQ(0, tester.GetActionCount(kFilledAndLoginActionName)); } @@ -309,7 +308,7 @@ base::UserActionTester tester; SavePending(LoginState::EXISTING); - filter_.ReportFormLoginSuccess(*form_manager_); + filter_.ReportFormLoginSuccess(form_manager_); EXPECT_EQ(0, tester.GetActionCount(kFilledAndLoginActionName)); } @@ -320,7 +319,7 @@ base::UserActionTester tester; SavePending(LoginState::EXISTING); - filter_.ReportFormLoginSuccess(*form_manager_); + filter_.ReportFormLoginSuccess(form_manager_); EXPECT_EQ(0, tester.GetActionCount(kFilledAndLoginActionName)); } @@ -330,7 +329,7 @@ base::UserActionTester tester; SavePending(LoginState::EXISTING); - filter_.ReportFormLoginSuccess(*form_manager_); + filter_.ReportFormLoginSuccess(form_manager_); EXPECT_EQ(0, tester.GetActionCount(kFilledAndLoginActionName)); }
diff --git a/content/browser/accessibility/accessibility_tree_formatter.cc b/content/browser/accessibility/accessibility_tree_formatter.cc index 1b67e306..6a37b87 100644 --- a/content/browser/accessibility/accessibility_tree_formatter.cc +++ b/content/browser/accessibility/accessibility_tree_formatter.cc
@@ -58,8 +58,7 @@ const BrowserAccessibility& node, base::DictionaryValue* dict) { AddProperties(node, dict); - base::ListValue* children = new base::ListValue; - dict->Set(kChildrenDictAttr, children); + auto children = base::MakeUnique<base::ListValue>(); for (size_t i = 0; i < ChildCount(node); ++i) { BrowserAccessibility* child_node = GetChild(node, i); @@ -68,6 +67,7 @@ RecursiveBuildAccessibilityTree(*child_node, child_dict.get()); children->Append(std::move(child_dict)); } + dict->Set(kChildrenDictAttr, std::move(children)); } void AccessibilityTreeFormatter::RecursiveFormatAccessibilityTree(
diff --git a/content/browser/accessibility/accessibility_tree_formatter_auralinux.cc b/content/browser/accessibility/accessibility_tree_formatter_auralinux.cc index f151255..65b9f696 100644 --- a/content/browser/accessibility/accessibility_tree_formatter_auralinux.cc +++ b/content/browser/accessibility/accessibility_tree_formatter_auralinux.cc
@@ -6,11 +6,15 @@ #include <atk/atk.h> +#include <utility> + #include "base/logging.h" +#include "base/memory/ptr_util.h" #include "base/strings/string_number_conversions.h" #include "base/strings/string_util.h" #include "base/strings/stringprintf.h" #include "base/strings/utf_string_conversions.h" +#include "base/values.h" #include "content/browser/accessibility/browser_accessibility_auralinux.h" namespace content { @@ -60,13 +64,13 @@ dict->SetString("description", std::string(description)); AtkStateSet* state_set = atk_object_ref_state_set(atk_object); - base::ListValue* states = new base::ListValue; + auto states = base::MakeUnique<base::ListValue>(); for (int i = ATK_STATE_INVALID; i < ATK_STATE_LAST_DEFINED; i++) { AtkStateType state_type = static_cast<AtkStateType>(i); if (atk_state_set_contains_state(state_set, state_type)) states->AppendString(atk_state_type_get_name(state_type)); } - dict->Set("states", states); + dict->Set("states", std::move(states)); } base::string16 AccessibilityTreeFormatterAuraLinux::ToString(
diff --git a/content/browser/accessibility/accessibility_tree_formatter_blink.cc b/content/browser/accessibility/accessibility_tree_formatter_blink.cc index ad862ccf..5c845ffe 100644 --- a/content/browser/accessibility/accessibility_tree_formatter_blink.cc +++ b/content/browser/accessibility/accessibility_tree_formatter_blink.cc
@@ -4,9 +4,13 @@ #include <stddef.h> +#include <utility> + +#include "base/memory/ptr_util.h" #include "base/strings/string_number_conversions.h" #include "base/strings/string_util.h" #include "base/strings/stringprintf.h" +#include "base/values.h" #include "content/browser/accessibility/accessibility_tree_formatter_blink.h" #include "content/browser/accessibility/browser_accessibility_manager.h" #include "ui/gfx/geometry/rect_conversions.h" @@ -120,7 +124,7 @@ if (node.HasIntListAttribute(attr)) { std::vector<int32_t> values; node.GetIntListAttribute(attr, &values); - base::ListValue* value_list = new base::ListValue; + auto value_list = base::MakeUnique<base::ListValue>(); for (size_t i = 0; i < values.size(); ++i) { if (ui::IsNodeIdIntListAttribute(attr)) { BrowserAccessibility* target = node.manager()->GetFromID(values[i]); @@ -132,7 +136,7 @@ value_list->AppendInteger(values[i]); } } - dict->Set(ui::ToString(attr), value_list); + dict->Set(ui::ToString(attr), std::move(value_list)); } }
diff --git a/content/browser/accessibility/accessibility_ui.cc b/content/browser/accessibility/accessibility_ui.cc index 266d5e2..4600f84 100644 --- a/content/browser/accessibility/accessibility_ui.cc +++ b/content/browser/accessibility/accessibility_ui.cc
@@ -5,6 +5,7 @@ #include "content/browser/accessibility/accessibility_ui.h" #include <memory> +#include <utility> #include "base/bind.h" #include "base/bind_helpers.h" @@ -142,7 +143,7 @@ } base::DictionaryValue data; - data.Set("list", rvh_list.release()); + data.Set("list", std::move(rvh_list)); AccessibilityMode mode = BrowserAccessibilityStateImpl::GetInstance()->accessibility_mode(); bool disabled = base::CommandLine::ForCurrentProcess()->HasSwitch( @@ -322,7 +323,7 @@ std::unique_ptr<base::DictionaryValue> result(new base::DictionaryValue()); result->SetInteger(kProcessIdField, process_id); result->SetInteger(kRouteIdField, route_id); - result->Set("error", new base::Value("Renderer no longer exists.")); + result->SetString("error", "Renderer no longer exists."); web_ui()->CallJavascriptFunctionUnsafe("accessibility.showTree", *(result.get())); return; @@ -351,8 +352,7 @@ DCHECK(ax_mgr); formatter->FormatAccessibilityTree(ax_mgr->GetRoot(), &accessibility_contents_utf16); - result->Set("tree", - new base::Value(base::UTF16ToUTF8(accessibility_contents_utf16))); + result->SetString("tree", base::UTF16ToUTF8(accessibility_contents_utf16)); web_ui()->CallJavascriptFunctionUnsafe("accessibility.showTree", *(result.get())); }
diff --git a/content/browser/devtools/protocol/devtools_protocol_browsertest.cc b/content/browser/devtools/protocol/devtools_protocol_browsertest.cc index b308661..2845733e 100644 --- a/content/browser/devtools/protocol/devtools_protocol_browsertest.cc +++ b/content/browser/devtools/protocol/devtools_protocol_browsertest.cc
@@ -3,6 +3,7 @@ // found in the LICENSE file. #include <stddef.h> + #include <utility> #include "base/base64.h" @@ -180,7 +181,7 @@ command.SetInteger(kIdParam, ++last_sent_id_); command.SetString(kMethodParam, method); if (params) - command.Set(kParamsParam, params.release()); + command.Set(kParamsParam, std::move(params)); std::string json_command; base::JSONWriter::Write(command, &json_command);
diff --git a/content/browser/devtools/protocol/system_info_handler.cc b/content/browser/devtools/protocol/system_info_handler.cc index a5e1b73..ac0c8be59 100644 --- a/content/browser/devtools/protocol/system_info_handler.cc +++ b/content/browser/devtools/protocol/system_info_handler.cc
@@ -110,7 +110,7 @@ gpu_info.EnumerateFields(&enumerator); std::unique_ptr<base::DictionaryValue> base_feature_status = - base::WrapUnique(GetFeatureStatus()); + GetFeatureStatus(); std::unique_ptr<protocol::DictionaryValue> feature_status = protocol::DictionaryValue::cast( protocol::toProtocolValue(base_feature_status.get(), 1000));
diff --git a/content/browser/gpu/compositor_util.cc b/content/browser/gpu/compositor_util.cc index 0921c99..1298d75 100644 --- a/content/browser/gpu/compositor_util.cc +++ b/content/browser/gpu/compositor_util.cc
@@ -6,7 +6,6 @@ #include <stddef.h> -#include <memory> #include <utility> #include "base/command_line.h" @@ -295,13 +294,13 @@ return false; } -base::DictionaryValue* GetFeatureStatus() { +std::unique_ptr<base::DictionaryValue> GetFeatureStatus() { GpuDataManagerImpl* manager = GpuDataManagerImpl::GetInstance(); std::string gpu_access_blocked_reason; bool gpu_access_blocked = !manager->GpuAccessAllowed(&gpu_access_blocked_reason); - base::DictionaryValue* feature_status_dict = new base::DictionaryValue(); + auto feature_status_dict = base::MakeUnique<base::DictionaryValue>(); bool eof = false; for (size_t i = 0; !eof; ++i) { @@ -356,23 +355,23 @@ return feature_status_dict; } -base::Value* GetProblems() { +std::unique_ptr<base::ListValue> GetProblems() { GpuDataManagerImpl* manager = GpuDataManagerImpl::GetInstance(); std::string gpu_access_blocked_reason; bool gpu_access_blocked = !manager->GpuAccessAllowed(&gpu_access_blocked_reason); - base::ListValue* problem_list = new base::ListValue(); - manager->GetBlacklistReasons(problem_list); + auto problem_list = base::MakeUnique<base::ListValue>(); + manager->GetBlacklistReasons(problem_list.get()); if (gpu_access_blocked) { auto problem = base::MakeUnique<base::DictionaryValue>(); problem->SetString("description", "GPU process was unable to boot: " + gpu_access_blocked_reason); - problem->Set("crBugs", new base::ListValue()); - base::ListValue* disabled_features = new base::ListValue(); + problem->Set("crBugs", base::MakeUnique<base::ListValue>()); + auto disabled_features = base::MakeUnique<base::ListValue>(); disabled_features->AppendString("all"); - problem->Set("affectedGpuSettings", disabled_features); + problem->Set("affectedGpuSettings", std::move(disabled_features)); problem->SetString("tag", "disabledFeatures"); problem_list->Insert(0, std::move(problem)); } @@ -381,14 +380,13 @@ for (size_t i = 0; !eof; ++i) { const GpuFeatureInfo gpu_feature_info = GetGpuFeatureInfo(i, &eof); if (gpu_feature_info.disabled) { - std::unique_ptr<base::DictionaryValue> problem( - new base::DictionaryValue()); + auto problem = base::MakeUnique<base::DictionaryValue>(); problem->SetString( "description", gpu_feature_info.disabled_description); - problem->Set("crBugs", new base::ListValue()); - base::ListValue* disabled_features = new base::ListValue(); + problem->Set("crBugs", base::MakeUnique<base::ListValue>()); + auto disabled_features = base::MakeUnique<base::ListValue>(); disabled_features->AppendString(gpu_feature_info.name); - problem->Set("affectedGpuSettings", disabled_features); + problem->Set("affectedGpuSettings", std::move(disabled_features)); problem->SetString("tag", "disabledFeatures"); problem_list->Append(std::move(problem)); }
diff --git a/content/browser/gpu/compositor_util.h b/content/browser/gpu/compositor_util.h index 140eaf8..5bf3749 100644 --- a/content/browser/gpu/compositor_util.h +++ b/content/browser/gpu/compositor_util.h
@@ -5,6 +5,8 @@ #ifndef CONTENT_BROWSER_GPU_COMPOSITOR_UTIL_H_ #define CONTENT_BROWSER_GPU_COMPOSITOR_UTIL_H_ +#include <memory> + #include "base/values.h" #include "content/common/content_export.h" @@ -42,8 +44,8 @@ // Returns true if images can be decode asynchronously from rasterization. CONTENT_EXPORT bool IsCheckerImagingEnabled(); -CONTENT_EXPORT base::DictionaryValue* GetFeatureStatus(); -CONTENT_EXPORT base::Value* GetProblems(); +CONTENT_EXPORT std::unique_ptr<base::DictionaryValue> GetFeatureStatus(); +CONTENT_EXPORT std::unique_ptr<base::ListValue> GetProblems(); CONTENT_EXPORT std::vector<std::string> GetDriverBugWorkarounds(); } // namespace content
diff --git a/content/browser/gpu/gpu_data_manager_impl.cc b/content/browser/gpu/gpu_data_manager_impl.cc index 0c9940b..98eb567 100644 --- a/content/browser/gpu/gpu_data_manager_impl.cc +++ b/content/browser/gpu/gpu_data_manager_impl.cc
@@ -249,7 +249,7 @@ private_->ProcessCrashed(exit_code); } -base::ListValue* GpuDataManagerImpl::GetLogMessages() const { +std::unique_ptr<base::ListValue> GpuDataManagerImpl::GetLogMessages() const { base::AutoLock auto_lock(lock_); return private_->GetLogMessages(); }
diff --git a/content/browser/gpu/gpu_data_manager_impl.h b/content/browser/gpu/gpu_data_manager_impl.h index 6c616cf..8c45dff4 100644 --- a/content/browser/gpu/gpu_data_manager_impl.h +++ b/content/browser/gpu/gpu_data_manager_impl.h
@@ -147,9 +147,8 @@ void ProcessCrashed(base::TerminationStatus exit_code); - // Returns a new copy of the ListValue. Caller is responsible to release - // the returned value. - base::ListValue* GetLogMessages() const; + // Returns a new copy of the ListValue. + std::unique_ptr<base::ListValue> GetLogMessages() const; // Called when switching gpu. void HandleGpuSwitch();
diff --git a/content/browser/gpu/gpu_data_manager_impl_private.cc b/content/browser/gpu/gpu_data_manager_impl_private.cc index 0677ceb..3c7c214 100644 --- a/content/browser/gpu/gpu_data_manager_impl_private.cc +++ b/content/browser/gpu/gpu_data_manager_impl_private.cc
@@ -12,6 +12,7 @@ #include "base/bind.h" #include "base/bind_helpers.h" #include "base/command_line.h" +#include "base/memory/ptr_util.h" #include "base/metrics/field_trial.h" #include "base/metrics/histogram_macros.h" #include "base/metrics/sparse_histogram.h" @@ -1017,8 +1018,9 @@ } } -base::ListValue* GpuDataManagerImplPrivate::GetLogMessages() const { - base::ListValue* value = new base::ListValue; +std::unique_ptr<base::ListValue> GpuDataManagerImplPrivate::GetLogMessages() + const { + auto value = base::MakeUnique<base::ListValue>(); for (size_t ii = 0; ii < log_messages_.size(); ++ii) { std::unique_ptr<base::DictionaryValue> dict(new base::DictionaryValue()); dict->SetInteger("level", log_messages_[ii].level);
diff --git a/content/browser/gpu/gpu_data_manager_impl_private.h b/content/browser/gpu/gpu_data_manager_impl_private.h index d78a7ebd..254c27b3 100644 --- a/content/browser/gpu/gpu_data_manager_impl_private.h +++ b/content/browser/gpu/gpu_data_manager_impl_private.h
@@ -10,6 +10,7 @@ #include <list> #include <map> +#include <memory> #include <set> #include <string> #include <vector> @@ -19,6 +20,7 @@ #include "base/memory/ref_counted.h" #include "base/memory/singleton.h" #include "base/observer_list_threadsafe.h" +#include "base/values.h" #include "build/build_config.h" #include "content/browser/gpu/gpu_data_manager_impl.h" #include "gpu/config/gpu_blacklist.h" @@ -91,7 +93,7 @@ void ProcessCrashed(base::TerminationStatus exit_code); - base::ListValue* GetLogMessages() const; + std::unique_ptr<base::ListValue> GetLogMessages() const; void HandleGpuSwitch();
diff --git a/content/browser/gpu/gpu_internals_ui.cc b/content/browser/gpu/gpu_internals_ui.cc index 45f2f6d..066f6d0 100644 --- a/content/browser/gpu/gpu_internals_ui.cc +++ b/content/browser/gpu/gpu_internals_ui.cc
@@ -80,17 +80,17 @@ std::unique_ptr<base::DictionaryValue> NewDescriptionValuePair( const std::string& desc, - base::Value* value) { + std::unique_ptr<base::Value> value) { std::unique_ptr<base::DictionaryValue> dict(new base::DictionaryValue()); dict->SetString("description", desc); - dict->Set("value", value); + dict->Set("value", std::move(value)); return dict; } #if defined(OS_WIN) // Output DxDiagNode tree as nested array of {description,value} pairs -base::ListValue* DxDiagNodeToList(const gpu::DxDiagNode& node) { - base::ListValue* list = new base::ListValue(); +std::unique_ptr<base::ListValue> DxDiagNodeToList(const gpu::DxDiagNode& node) { + auto list = base::MakeUnique<base::ListValue>(); for (std::map<std::string, std::string>::const_iterator it = node.values.begin(); it != node.values.end(); @@ -102,8 +102,8 @@ node.children.begin(); it != node.children.end(); ++it) { - base::ListValue* sublist = DxDiagNodeToList(it->second); - list->Append(NewDescriptionValuePair(it->first, sublist)); + std::unique_ptr<base::ListValue> sublist = DxDiagNodeToList(it->second); + list->Append(NewDescriptionValuePair(it->first, std::move(sublist))); } return list; } @@ -120,21 +120,23 @@ vendor.c_str(), device.c_str(), gpu.active ? " *ACTIVE*" : ""); } -base::DictionaryValue* GpuInfoAsDictionaryValue() { +std::unique_ptr<base::DictionaryValue> GpuInfoAsDictionaryValue() { gpu::GPUInfo gpu_info = GpuDataManagerImpl::GetInstance()->GetGPUInfo(); - base::ListValue* basic_info = new base::ListValue(); + auto basic_info = base::MakeUnique<base::ListValue>(); basic_info->Append(NewDescriptionValuePair( "Initialization time", base::Int64ToString(gpu_info.initialization_time.InMilliseconds()))); basic_info->Append(NewDescriptionValuePair( - "In-process GPU", new base::Value(gpu_info.in_process_gpu))); + "In-process GPU", + base::MakeUnique<base::Value>(gpu_info.in_process_gpu))); basic_info->Append(NewDescriptionValuePair( "Passthrough Command Decoder", - new base::Value(gpu_info.passthrough_cmd_decoder))); + base::MakeUnique<base::Value>(gpu_info.passthrough_cmd_decoder))); basic_info->Append(NewDescriptionValuePair( - "Supports overlays", new base::Value(gpu_info.supports_overlays))); + "Supports overlays", + base::MakeUnique<base::Value>(gpu_info.supports_overlays))); basic_info->Append(NewDescriptionValuePair( - "Sandboxed", new base::Value(gpu_info.sandboxed))); + "Sandboxed", base::MakeUnique<base::Value>(gpu_info.sandboxed))); basic_info->Append(NewDescriptionValuePair( "GPU0", GPUDeviceToString(gpu_info.gpu))); for (size_t i = 0; i < gpu_info.secondary_gpus.size(); ++i) { @@ -142,12 +144,13 @@ base::StringPrintf("GPU%d", static_cast<int>(i + 1)), GPUDeviceToString(gpu_info.secondary_gpus[i]))); } - basic_info->Append( - NewDescriptionValuePair("Optimus", new base::Value(gpu_info.optimus))); - basic_info->Append( - NewDescriptionValuePair("Optimus", new base::Value(gpu_info.optimus))); basic_info->Append(NewDescriptionValuePair( - "AMD switchable", new base::Value(gpu_info.amd_switchable))); + "Optimus", base::MakeUnique<base::Value>(gpu_info.optimus))); + basic_info->Append(NewDescriptionValuePair( + "Optimus", base::MakeUnique<base::Value>(gpu_info.optimus))); + basic_info->Append(NewDescriptionValuePair( + "AMD switchable", + base::MakeUnique<base::Value>(gpu_info.amd_switchable))); #if defined(OS_WIN) std::string compositor = ui::win::IsAeroGlassEnabled() ? "Aero Glass" : "none"; @@ -232,17 +235,16 @@ basic_info->Append(NewDescriptionValuePair( "Reset notification strategy", reset_strategy)); - basic_info->Append( - NewDescriptionValuePair("GPU process crash count", - new base::Value(gpu_info.process_crash_count))); + basic_info->Append(NewDescriptionValuePair( + "GPU process crash count", + base::MakeUnique<base::Value>(gpu_info.process_crash_count))); - base::DictionaryValue* info = new base::DictionaryValue(); - info->Set("basic_info", basic_info); + auto info = base::MakeUnique<base::DictionaryValue>(); #if defined(OS_WIN) auto dx_info = base::MakeUnique<base::Value>(); if (gpu_info.dx_diagnostics.children.size()) - dx_info.reset(DxDiagNodeToList(gpu_info.dx_diagnostics)); + dx_info = DxDiagNodeToList(gpu_info.dx_diagnostics); info->Set("diagnostics", std::move(dx_info)); #endif @@ -253,6 +255,7 @@ "RGBA visual ID", base::Uint64ToString(gpu_info.rgba_visual))); #endif + info->Set("basic_info", std::move(basic_info)); return info; } @@ -314,8 +317,8 @@ return nullptr; } -base::ListValue* CompositorInfo() { - base::ListValue* compositor_info = new base::ListValue(); +std::unique_ptr<base::ListValue> CompositorInfo() { + auto compositor_info = base::MakeUnique<base::ListValue>(); compositor_info->Append(NewDescriptionValuePair( "Tile Update Mode", @@ -326,8 +329,8 @@ return compositor_info; } -base::ListValue* GpuMemoryBufferInfo() { - base::ListValue* gpu_memory_buffer_info = new base::ListValue(); +std::unique_ptr<base::ListValue> GpuMemoryBufferInfo() { + auto gpu_memory_buffer_info = base::MakeUnique<base::ListValue>(); BrowserGpuMemoryBufferManager* gpu_memory_buffer_manager = BrowserGpuMemoryBufferManager::current(); @@ -381,8 +384,10 @@ void OnCallAsync(const base::ListValue* list); // Submessages dispatched from OnCallAsync - base::Value* OnRequestClientInfo(const base::ListValue* list); - base::Value* OnRequestLogMessages(const base::ListValue* list); + std::unique_ptr<base::DictionaryValue> OnRequestClientInfo( + const base::ListValue* list); + std::unique_ptr<base::ListValue> OnRequestLogMessages( + const base::ListValue* list); private: // True if observing the GpuDataManager (re-attaching as observer would @@ -431,7 +436,7 @@ ok = args->GetString(1, &submessage); DCHECK(ok); - base::ListValue* submessageArgs = new base::ListValue(); + auto submessageArgs = base::MakeUnique<base::ListValue>(); for (size_t i = 2; i < args->GetSize(); ++i) { const base::Value* arg; ok = args->Get(i, &arg); @@ -441,23 +446,20 @@ } // call the submessage handler - base::Value* ret = NULL; + std::unique_ptr<base::Value> ret; if (submessage == "requestClientInfo") { - ret = OnRequestClientInfo(submessageArgs); + ret = OnRequestClientInfo(submessageArgs.get()); } else if (submessage == "requestLogMessages") { - ret = OnRequestLogMessages(submessageArgs); + ret = OnRequestLogMessages(submessageArgs.get()); } else { // unrecognized submessage NOTREACHED(); - delete submessageArgs; return; } - delete submessageArgs; // call BrowserBridge.onCallAsyncReply with result if (ret) { web_ui()->CallJavascriptFunctionUnsafe("browserBridge.onCallAsyncReply", *requestId, *ret); - delete ret; } else { web_ui()->CallJavascriptFunctionUnsafe("browserBridge.onCallAsyncReply", *requestId); @@ -484,11 +486,11 @@ OnGpuInfoUpdate(); } -base::Value* GpuMessageHandler::OnRequestClientInfo( +std::unique_ptr<base::DictionaryValue> GpuMessageHandler::OnRequestClientInfo( const base::ListValue* list) { DCHECK_CURRENTLY_ON(BrowserThread::UI); - base::DictionaryValue* dict = new base::DictionaryValue(); + auto dict = base::MakeUnique<base::DictionaryValue>(); dict->SetString("version", GetContentClient()->GetProduct()); dict->SetString("command_line", @@ -508,7 +510,8 @@ return dict; } -base::Value* GpuMessageHandler::OnRequestLogMessages(const base::ListValue*) { +std::unique_ptr<base::ListValue> GpuMessageHandler::OnRequestLogMessages( + const base::ListValue*) { DCHECK_CURRENTLY_ON(BrowserThread::UI); return GpuDataManagerImpl::GetInstance()->GetLogMessages(); @@ -520,14 +523,14 @@ GpuInfoAsDictionaryValue()); // Add in blacklisting features - base::DictionaryValue* feature_status = new base::DictionaryValue; + auto feature_status = base::MakeUnique<base::DictionaryValue>(); feature_status->Set("featureStatus", GetFeatureStatus()); feature_status->Set("problems", GetProblems()); - base::ListValue* workarounds = new base::ListValue(); + auto workarounds = base::MakeUnique<base::ListValue>(); for (const std::string& workaround : GetDriverBugWorkarounds()) workarounds->AppendString(workaround); - feature_status->Set("workarounds", workarounds); - gpu_info_val->Set("featureStatus", feature_status); + feature_status->Set("workarounds", std::move(workarounds)); + gpu_info_val->Set("featureStatus", std::move(feature_status)); gpu_info_val->Set("compositorInfo", CompositorInfo()); gpu_info_val->Set("gpuMemoryBufferInfo", GpuMemoryBufferInfo());
diff --git a/content/browser/indexed_db/indexed_db_context_impl.cc b/content/browser/indexed_db/indexed_db_context_impl.cc index ec8a2c8..660a48ab 100644 --- a/content/browser/indexed_db/indexed_db_context_impl.cc +++ b/content/browser/indexed_db/indexed_db_context_impl.cc
@@ -179,7 +179,7 @@ base::MakeUnique<base::ListValue>()); for (const base::FilePath& path : GetStoragePaths(origin)) paths->AppendString(path.value()); - info->Set("paths", paths.release()); + info->Set("paths", std::move(paths)); } info->SetDouble("connection_count", GetConnectionCount(origin)); @@ -260,14 +260,14 @@ scope->AppendString(it->second.name); } - transaction_info->Set("scope", scope.release()); + transaction_info->Set("scope", std::move(scope)); transaction_list->Append(std::move(transaction_info)); } - db_info->Set("transactions", transaction_list.release()); + db_info->Set("transactions", std::move(transaction_list)); database_list->Append(std::move(db_info)); } - info->Set("databases", database_list.release()); + info->Set("databases", std::move(database_list)); } list->Append(std::move(info));
diff --git a/content/browser/media/media_internals.cc b/content/browser/media/media_internals.cc index def2b61..61d5aea 100644 --- a/content/browser/media/media_internals.cc +++ b/content/browser/media/media_internals.cc
@@ -807,7 +807,7 @@ dict.SetString("params.pipeline_error", media::MediaLog::PipelineStatusToString(error)); } else { - dict.Set("params", event.params.DeepCopy()); + dict.Set("params", base::MakeUnique<base::Value>(event.params)); } *update = SerializeUpdate("media.onMediaEvent", &dict); @@ -899,7 +899,7 @@ video_capture_capabilities_cached_data_.Clear(); for (const auto& device_format_pair : descriptors_and_formats) { - base::ListValue* format_list = new base::ListValue(); + auto format_list = base::MakeUnique<base::ListValue>(); // TODO(nisse): Representing format information as a string, to be // parsed by the javascript handler, is brittle. Consider passing // a list of mappings instead. @@ -915,7 +915,7 @@ new base::DictionaryValue()); device_dict->SetString("id", descriptor.device_id); device_dict->SetString("name", descriptor.GetNameAndModel()); - device_dict->Set("formats", format_list); + device_dict->Set("formats", std::move(format_list)); #if defined(OS_WIN) || defined(OS_MACOSX) || defined(OS_LINUX) || \ defined(OS_ANDROID) device_dict->SetString("captureApi", descriptor.GetCaptureApiTypeString()); @@ -998,7 +998,8 @@ return; } else if (!has_entry) { DCHECK_EQ(type, CREATE); - audio_streams_cached_data_.Set(cache_key, value->DeepCopy()); + audio_streams_cached_data_.Set(cache_key, + base::MakeUnique<base::Value>(*value)); } else if (type == UPDATE_AND_DELETE) { std::unique_ptr<base::Value> out_value; CHECK(audio_streams_cached_data_.Remove(cache_key, &out_value));
diff --git a/content/browser/media/media_internals_proxy.cc b/content/browser/media/media_internals_proxy.cc index da1f190..f180589a 100644 --- a/content/browser/media/media_internals_proxy.cc +++ b/content/browser/media/media_internals_proxy.cc
@@ -47,8 +47,9 @@ DCHECK_CURRENTLY_ON(BrowserThread::UI); DCHECK_EQ(type, NOTIFICATION_RENDERER_PROCESS_TERMINATED); RenderProcessHost* process = Source<RenderProcessHost>(source).ptr(); - CallJavaScriptFunctionOnUIThread("media.onRendererTerminated", - new base::Value(process->GetID())); + CallJavaScriptFunctionOnUIThread( + "media.onRendererTerminated", + base::MakeUnique<base::Value>(process->GetID())); } void MediaInternalsProxy::Attach(MediaInternalsMessageHandler* handler) { @@ -109,8 +110,8 @@ MediaInternalsProxy::~MediaInternalsProxy() {} -base::Value* MediaInternalsProxy::GetConstants() { - base::DictionaryValue* event_phases = new base::DictionaryValue(); +std::unique_ptr<base::Value> MediaInternalsProxy::GetConstants() { + auto event_phases = base::MakeUnique<base::DictionaryValue>(); event_phases->SetInteger( net::NetLog::EventPhaseToString(net::NetLogEventPhase::NONE), static_cast<int>(net::NetLogEventPhase::NONE)); @@ -121,11 +122,11 @@ net::NetLog::EventPhaseToString(net::NetLogEventPhase::END), static_cast<int>(net::NetLogEventPhase::END)); - base::DictionaryValue* constants = new base::DictionaryValue(); + auto constants = base::MakeUnique<base::DictionaryValue>(); constants->Set("eventTypes", net::NetLog::GetEventTypesAsValue()); - constants->Set("eventPhases", event_phases); + constants->Set("eventPhases", std::move(event_phases)); - return constants; + return std::move(constants); } void MediaInternalsProxy::ObserveMediaInternalsOnIOThread() { @@ -179,15 +180,15 @@ void MediaInternalsProxy::SendNetEventsOnUIThread() { DCHECK_CURRENTLY_ON(BrowserThread::UI); CallJavaScriptFunctionOnUIThread("media.onNetUpdate", - pending_net_updates_.release()); + std::move(pending_net_updates_)); } void MediaInternalsProxy::CallJavaScriptFunctionOnUIThread( - const std::string& function, base::Value* args) { + const std::string& function, + std::unique_ptr<base::Value> args) { DCHECK_CURRENTLY_ON(BrowserThread::UI); - std::unique_ptr<base::Value> args_value(args); std::vector<const base::Value*> args_vector; - args_vector.push_back(args_value.get()); + args_vector.push_back(args.get()); base::string16 update = WebUI::GetJavascriptCall(function, args_vector); UpdateUIOnUIThread(update); }
diff --git a/content/browser/media/media_internals_proxy.h b/content/browser/media/media_internals_proxy.h index f0995e33..a9dbba4 100644 --- a/content/browser/media/media_internals_proxy.h +++ b/content/browser/media/media_internals_proxy.h
@@ -60,7 +60,7 @@ ~MediaInternalsProxy() override; // Build a dictionary mapping constant names to values. - base::Value* GetConstants(); + std::unique_ptr<base::Value> GetConstants(); void ObserveMediaInternalsOnIOThread(); void StopObservingMediaInternalsOnIOThread(); @@ -75,9 +75,9 @@ // Send all pending events to the page. void SendNetEventsOnUIThread(); - // Call a JavaScript function on the page. Takes ownership of |args|. + // Call a JavaScript function on the page. void CallJavaScriptFunctionOnUIThread(const std::string& function, - base::Value* args); + std::unique_ptr<base::Value> args); MediaInternalsMessageHandler* handler_; std::unique_ptr<base::ListValue> pending_net_updates_;
diff --git a/content/browser/net/network_errors_listing_ui.cc b/content/browser/net/network_errors_listing_ui.cc index 86ed0bb0..9769701 100644 --- a/content/browser/net/network_errors_listing_ui.cc +++ b/content/browser/net/network_errors_listing_ui.cc
@@ -64,7 +64,7 @@ return false; base::DictionaryValue data; - data.Set(kErrorCodesDataName, GetNetworkErrorData().release()); + data.Set(kErrorCodesDataName, GetNetworkErrorData()); std::string json_string; base::JSONWriter::Write(data, &json_string); callback.Run(base::RefCountedString::TakeString(&json_string));
diff --git a/content/browser/service_worker/service_worker_internals_ui.cc b/content/browser/service_worker/service_worker_internals_ui.cc index 5dd7a48a0..8b061c3 100644 --- a/content/browser/service_worker/service_worker_internals_ui.cc +++ b/content/browser/service_worker/service_worker_internals_ui.cc
@@ -194,16 +194,16 @@ if (registration.active_version.version_id != kInvalidServiceWorkerVersionId) { - DictionaryValue* active_info = new DictionaryValue(); - UpdateVersionInfo(registration.active_version, active_info); - registration_info->Set("active", active_info); + auto active_info = base::MakeUnique<DictionaryValue>(); + UpdateVersionInfo(registration.active_version, active_info.get()); + registration_info->Set("active", std::move(active_info)); } if (registration.waiting_version.version_id != kInvalidServiceWorkerVersionId) { - DictionaryValue* waiting_info = new DictionaryValue(); - UpdateVersionInfo(registration.waiting_version, waiting_info); - registration_info->Set("waiting", waiting_info); + auto waiting_info = base::MakeUnique<DictionaryValue>(); + UpdateVersionInfo(registration.waiting_version, waiting_info.get()); + registration_info->Set("waiting", std::move(waiting_info)); } result->Append(std::move(registration_info));
diff --git a/content/browser/service_worker/service_worker_process_manager.cc b/content/browser/service_worker/service_worker_process_manager.cc index cedb5d9..b083840 100644 --- a/content/browser/service_worker/service_worker_process_manager.cc +++ b/content/browser/service_worker/service_worker_process_manager.cc
@@ -224,6 +224,9 @@ // SiteInstanceImpl::ProcessReusePolicy::REUSE_PENDING_OR_COMMITTED_SITE. scoped_refptr<SiteInstanceImpl> site_instance = SiteInstanceImpl::CreateForURL(browser_context_, script_url); + DCHECK_NE( + site_instance->process_reuse_policy(), + SiteInstanceImpl::ProcessReusePolicy::REUSE_PENDING_OR_COMMITTED_SITE); if (can_use_existing_process) { site_instance->set_process_reuse_policy( SiteInstanceImpl::ProcessReusePolicy::REUSE_PENDING_OR_COMMITTED_SITE);
diff --git a/content/browser/service_worker/service_worker_process_manager_unittest.cc b/content/browser/service_worker/service_worker_process_manager_unittest.cc index 8e276f62..d332eac 100644 --- a/content/browser/service_worker/service_worker_process_manager_unittest.cc +++ b/content/browser/service_worker/service_worker_process_manager_unittest.cc
@@ -245,7 +245,7 @@ const int kEmbeddedWorkerId = 100; const GURL kSiteUrl = GURL("http://example.com"); - // Create a process that is hosting a frame with URL |patter_|. + // Create a process that is hosting a frame with URL |pattern_|. std::unique_ptr<MockRenderProcessHost> host(CreateRenderProcessHost()); RenderProcessHostImpl::AddFrameWithSite(browser_context_.get(), host.get(), kSiteUrl); @@ -291,7 +291,7 @@ const int kEmbeddedWorkerId = 100; const GURL kSiteUrl = GURL("http://example.com"); - // Create a process that is hosting a frame with URL |patter_|. + // Create a process that is hosting a frame with URL |pattern_|. std::unique_ptr<MockRenderProcessHost> host(CreateRenderProcessHost()); RenderProcessHostImpl::AddFrameWithSite(browser_context_.get(), host.get(), kSiteUrl); @@ -300,7 +300,7 @@ process_manager_->instance_info_; EXPECT_TRUE(instance_info.empty()); - // Allocate a process to a worker, when process reuse is authorized. + // Allocate a process to a worker, when process reuse is disallowed. base::RunLoop run_loop; ServiceWorkerStatusCode status = SERVICE_WORKER_ERROR_MAX_VALUE; int process_id = -10; @@ -312,7 +312,7 @@ &process_id, &is_new_process)); run_loop.Run(); - // An new process should be allocated to the worker. + // A new process should be allocated to the worker. EXPECT_EQ(SERVICE_WORKER_OK, status); EXPECT_NE(host->GetID(), process_id); EXPECT_TRUE(is_new_process);
diff --git a/content/browser/tracing/tracing_controller_impl.cc b/content/browser/tracing/tracing_controller_impl.cc index ca3cffe..6bb7164 100644 --- a/content/browser/tracing/tracing_controller_impl.cc +++ b/content/browser/tracing/tracing_controller_impl.cc
@@ -14,6 +14,7 @@ #include "base/guid.h" #include "base/json/string_escape.h" #include "base/macros.h" +#include "base/memory/ptr_util.h" #include "base/memory/ref_counted_memory.h" #include "base/strings/string_number_conversions.h" #include "base/sys_info.h" @@ -21,6 +22,7 @@ #include "base/threading/thread_task_runner_handle.h" #include "base/time/time.h" #include "base/trace_event/trace_event.h" +#include "base/values.h" #include "build/build_config.h" #include "components/tracing/common/process_metrics_memory_dump_provider.h" #include "content/browser/tracing/file_tracing_provider_impl.h" @@ -819,7 +821,8 @@ for (base::DictionaryValue::Iterator it(*metadata); !it.IsAtEnd(); it.Advance()) { if (filter.Run(it.key())) - filtered_metadata->Set(it.key(), it.value().DeepCopy()); + filtered_metadata->Set(it.key(), + base::MakeUnique<base::Value>(it.value())); else filtered_metadata->SetString(it.key(), "__stripped__"); }
diff --git a/content/browser/webrtc/webrtc_internals.cc b/content/browser/webrtc/webrtc_internals.cc index 4131766..ff46576 100644 --- a/content/browser/webrtc/webrtc_internals.cc +++ b/content/browser/webrtc/webrtc_internals.cc
@@ -9,6 +9,7 @@ #include <memory> #include <utility> +#include "base/memory/ptr_util.h" #include "base/strings/string_number_conversions.h" #include "build/build_config.h" #include "content/browser/renderer_host/render_process_host_impl.h" @@ -44,10 +45,8 @@ // Makes sure that |dict| has a ListValue under path "log". base::ListValue* EnsureLogList(base::DictionaryValue* dict) { base::ListValue* log = NULL; - if (!dict->GetList("log", &log)) { - log = new base::ListValue(); - dict->Set("log", log); - } + if (!dict->GetList("log", &log)) + log = dict->SetList("log", base::MakeUnique<base::ListValue>()); return log; } @@ -191,7 +190,7 @@ if (!observers_.might_have_observers()) return; - std::unique_ptr<base::DictionaryValue> log_entry(new base::DictionaryValue()); + auto log_entry = base::MakeUnique<base::DictionaryValue>(); double epoch_time = base::Time::Now().ToJsTime(); string time = base::DoubleToString(epoch_time); @@ -199,7 +198,7 @@ log_entry->SetString("type", type); log_entry->SetString("value", value); - std::unique_ptr<base::DictionaryValue> update(new base::DictionaryValue()); + auto update = base::MakeUnique<base::DictionaryValue>(); update->SetInteger("pid", static_cast<int>(pid)); update->SetInteger("lid", lid); update->MergeDictionary(log_entry.get()); @@ -215,11 +214,11 @@ if (!observers_.might_have_observers()) return; - std::unique_ptr<base::DictionaryValue> dict(new base::DictionaryValue()); + auto dict = base::MakeUnique<base::DictionaryValue>(); dict->SetInteger("pid", static_cast<int>(pid)); dict->SetInteger("lid", lid); - dict->Set("reports", value.CreateDeepCopy()); + dict->Set("reports", base::MakeUnique<base::Value>(value)); SendUpdate("addStats", std::move(dict)); } @@ -233,7 +232,7 @@ const std::string& video_constraints) { DCHECK_CURRENTLY_ON(BrowserThread::UI); - std::unique_ptr<base::DictionaryValue> dict(new base::DictionaryValue()); + auto dict = base::MakeUnique<base::DictionaryValue>(); dict->SetInteger("rid", rid); dict->SetInteger("pid", static_cast<int>(pid)); dict->SetString("origin", origin);
diff --git a/content/renderer/devtools/devtools_agent.cc b/content/renderer/devtools/devtools_agent.cc index b995c0d..ea469e1 100644 --- a/content/renderer/devtools/devtools_agent.cc +++ b/content/renderer/devtools/devtools_agent.cc
@@ -7,6 +7,7 @@ #include <stddef.h> #include <map> +#include <utility> #include "base/json/json_writer.h" #include "base/lazy_instance.h" @@ -341,8 +342,8 @@ result->SetString("url", url.Utf16()); if (!failed) result->SetString("data", debug_info.raw_data); - result->Set("errors", errors.release()); - response->Set("result", result.release()); + result->Set("errors", std::move(errors)); + response->Set("result", std::move(result)); std::string json_message; base::JSONWriter::Write(*response, &json_message);
diff --git a/content/renderer/media/peer_connection_tracker.cc b/content/renderer/media/peer_connection_tracker.cc index b68adf40..40cb37c 100644 --- a/content/renderer/media/peer_connection_tracker.cc +++ b/content/renderer/media/peer_connection_tracker.cc
@@ -10,9 +10,11 @@ #include <memory> #include <utility> +#include "base/memory/ptr_util.h" #include "base/strings/string_number_conversions.h" #include "base/strings/utf_string_conversions.h" #include "base/threading/thread_task_runner_handle.h" +#include "base/values.h" #include "content/common/media/peer_connection_tracker_messages.h" #include "content/renderer/media/rtc_peer_connection_handler.h" #include "content/renderer/render_thread_impl.h" @@ -244,19 +246,15 @@ } // Builds a DictionaryValue from the StatsReport. -// The caller takes the ownership of the returned value. // Note: // The format must be consistent with what webrtc_internals.js expects. // If you change it here, you must change webrtc_internals.js as well. -static base::DictionaryValue* GetDictValueStats(const StatsReport& report) { +static std::unique_ptr<base::DictionaryValue> GetDictValueStats( + const StatsReport& report) { if (report.values().empty()) return NULL; - base::DictionaryValue* dict = new base::DictionaryValue(); - dict->SetDouble("timestamp", report.timestamp()); - - base::ListValue* values = new base::ListValue(); - dict->Set("values", values); + auto values = base::MakeUnique<base::ListValue>(); for (const auto& v : report.values()) { const StatsReport::ValuePtr& value = v.second; @@ -286,6 +284,10 @@ } } + auto dict = base::MakeUnique<base::DictionaryValue>(); + dict->SetDouble("timestamp", report.timestamp()); + dict->Set("values", std::move(values)); + return dict; } @@ -293,17 +295,15 @@ // The caller takes the ownership of the returned value. static std::unique_ptr<base::DictionaryValue> GetDictValue( const StatsReport& report) { - std::unique_ptr<base::DictionaryValue> stats, result; - - stats.reset(GetDictValueStats(report)); + std::unique_ptr<base::DictionaryValue> stats = GetDictValueStats(report); if (!stats) return NULL; - result.reset(new base::DictionaryValue()); // Note: // The format must be consistent with what webrtc_internals.js expects. // If you change it here, you must change webrtc_internals.js as well. - result->Set("stats", stats.release()); + auto result = base::MakeUnique<base::DictionaryValue>(); + result->Set("stats", std::move(stats)); result->SetString("id", report.id()->ToString()); result->SetString("type", report.TypeToString());
diff --git a/content/shell/browser/shell_devtools_bindings.cc b/content/shell/browser/shell_devtools_bindings.cc index 77bfc75..e13e73db 100644 --- a/content/shell/browser/shell_devtools_bindings.cc +++ b/content/shell/browser/shell_devtools_bindings.cc
@@ -6,10 +6,13 @@ #include <stddef.h> +#include <utility> + #include "base/json/json_reader.h" #include "base/json/json_writer.h" #include "base/json/string_escape.h" #include "base/macros.h" +#include "base/memory/ptr_util.h" #include "base/strings/string_number_conversions.h" #include "base/strings/stringprintf.h" #include "base/strings/utf_string_conversions.h" @@ -323,16 +326,16 @@ DCHECK(it != pending_requests_.end()); base::DictionaryValue response; - base::DictionaryValue* headers = new base::DictionaryValue(); + auto headers = base::MakeUnique<base::DictionaryValue>(); net::HttpResponseHeaders* rh = source->GetResponseHeaders(); response.SetInteger("statusCode", rh ? rh->response_code() : 200); - response.Set("headers", headers); size_t iterator = 0; std::string name; std::string value; while (rh && rh->EnumerateHeaderLines(&iterator, &name, &value)) headers->SetString(name, value); + response.Set("headers", std::move(headers)); SendMessageAck(it->second, &response); pending_requests_.erase(it);
diff --git a/content/shell/browser/shell_net_log.cc b/content/shell/browser/shell_net_log.cc index a765603..aebbc092e 100644 --- a/content/shell/browser/shell_net_log.cc +++ b/content/shell/browser/shell_net_log.cc
@@ -5,11 +5,13 @@ #include "content/shell/browser/shell_net_log.h" #include <stdio.h> + #include <utility> #include "base/command_line.h" #include "base/files/file_path.h" #include "base/files/scoped_file.h" +#include "base/memory/ptr_util.h" #include "base/values.h" #include "build/build_config.h" #include "content/public/common/content_switches.h" @@ -20,21 +22,22 @@ namespace { -base::DictionaryValue* GetShellConstants(const std::string& app_name) { +std::unique_ptr<base::DictionaryValue> GetShellConstants( + const std::string& app_name) { std::unique_ptr<base::DictionaryValue> constants_dict = net::GetNetConstants(); // Add a dictionary with client information - base::DictionaryValue* dict = new base::DictionaryValue(); + auto dict = base::MakeUnique<base::DictionaryValue>(); dict->SetString("name", app_name); dict->SetString( "command_line", base::CommandLine::ForCurrentProcess()->GetCommandLineString()); - constants_dict->Set("clientInfo", dict); + constants_dict->Set("clientInfo", std::move(dict)); - return constants_dict.release(); + return constants_dict; } } // namespace
diff --git a/content/shell/renderer/layout_test/leak_detector.cc b/content/shell/renderer/layout_test/leak_detector.cc index f95cc74..a30af9ae0 100644 --- a/content/shell/renderer/layout_test/leak_detector.cc +++ b/content/shell/renderer/layout_test/leak_detector.cc
@@ -4,8 +4,11 @@ #include "content/shell/renderer/layout_test/leak_detector.h" +#include <utility> + #include "base/json/json_writer.h" #include "base/logging.h" +#include "base/memory/ptr_util.h" #include "base/values.h" #include "content/shell/renderer/layout_test/blink_test_runner.h" #include "third_party/WebKit/public/web/WebLeakDetector.h" @@ -76,71 +79,71 @@ if (previous_result_.number_of_live_audio_nodes < result.number_of_live_audio_nodes) { - base::ListValue* list = new base::ListValue(); + auto list = base::MakeUnique<base::ListValue>(); list->AppendInteger(previous_result_.number_of_live_audio_nodes); list->AppendInteger(result.number_of_live_audio_nodes); - detail.Set("numberOfLiveAudioNodes", list); + detail.Set("numberOfLiveAudioNodes", std::move(list)); } if (previous_result_.number_of_live_documents < result.number_of_live_documents) { - base::ListValue* list = new base::ListValue(); + auto list = base::MakeUnique<base::ListValue>(); list->AppendInteger(previous_result_.number_of_live_documents); list->AppendInteger(result.number_of_live_documents); - detail.Set("numberOfLiveDocuments", list); + detail.Set("numberOfLiveDocuments", std::move(list)); } if (previous_result_.number_of_live_nodes < result.number_of_live_nodes) { - base::ListValue* list = new base::ListValue(); + auto list = base::MakeUnique<base::ListValue>(); list->AppendInteger(previous_result_.number_of_live_nodes); list->AppendInteger(result.number_of_live_nodes); - detail.Set("numberOfLiveNodes", list); + detail.Set("numberOfLiveNodes", std::move(list)); } if (previous_result_.number_of_live_layout_objects < result.number_of_live_layout_objects) { - base::ListValue* list = new base::ListValue(); + auto list = base::MakeUnique<base::ListValue>(); list->AppendInteger(previous_result_.number_of_live_layout_objects); list->AppendInteger(result.number_of_live_layout_objects); - detail.Set("numberOfLiveLayoutObjects", list); + detail.Set("numberOfLiveLayoutObjects", std::move(list)); } if (previous_result_.number_of_live_resources < result.number_of_live_resources) { - base::ListValue* list = new base::ListValue(); + auto list = base::MakeUnique<base::ListValue>(); list->AppendInteger(previous_result_.number_of_live_resources); list->AppendInteger(result.number_of_live_resources); - detail.Set("numberOfLiveResources", list); + detail.Set("numberOfLiveResources", std::move(list)); } if (previous_result_.number_of_live_suspendable_objects < result.number_of_live_suspendable_objects) { - base::ListValue* list = new base::ListValue(); + auto list = base::MakeUnique<base::ListValue>(); list->AppendInteger(previous_result_.number_of_live_suspendable_objects); list->AppendInteger(result.number_of_live_suspendable_objects); - detail.Set("numberOfLiveSuspendableObjects", list); + detail.Set("numberOfLiveSuspendableObjects", std::move(list)); } if (previous_result_.number_of_live_script_promises < result.number_of_live_script_promises) { - base::ListValue* list = new base::ListValue(); + auto list = base::MakeUnique<base::ListValue>(); list->AppendInteger(previous_result_.number_of_live_script_promises); list->AppendInteger(result.number_of_live_script_promises); - detail.Set("numberOfLiveScriptPromises", list); + detail.Set("numberOfLiveScriptPromises", std::move(list)); } if (previous_result_.number_of_live_frames < result.number_of_live_frames) { - base::ListValue* list = new base::ListValue(); + auto list = base::MakeUnique<base::ListValue>(); list->AppendInteger(previous_result_.number_of_live_frames); list->AppendInteger(result.number_of_live_frames); - detail.Set("numberOfLiveFrames", list); + detail.Set("numberOfLiveFrames", std::move(list)); } if (previous_result_.number_of_live_v8_per_context_data < result.number_of_live_v8_per_context_data) { - base::ListValue* list = new base::ListValue(); + auto list = base::MakeUnique<base::ListValue>(); list->AppendInteger(previous_result_.number_of_live_v8_per_context_data); list->AppendInteger(result.number_of_live_v8_per_context_data); - detail.Set("numberOfLiveV8PerContextData", list); + detail.Set("numberOfLiveV8PerContextData", std::move(list)); } if (previous_result_.number_of_worker_global_scopes < result.number_of_worker_global_scopes) { - base::ListValue* list = new base::ListValue(); + auto list = base::MakeUnique<base::ListValue>(); list->AppendInteger(previous_result_.number_of_worker_global_scopes); list->AppendInteger(result.number_of_worker_global_scopes); - detail.Set("numberOfWorkerGlobalScopes", list); + detail.Set("numberOfWorkerGlobalScopes", std::move(list)); } if (!detail.empty()) {
diff --git a/device/bluetooth/public/interfaces/test/fake_bluetooth.mojom b/device/bluetooth/public/interfaces/test/fake_bluetooth.mojom index 98da605..1e7b4bf 100644 --- a/device/bluetooth/public/interfaces/test/fake_bluetooth.mojom +++ b/device/bluetooth/public/interfaces/test/fake_bluetooth.mojom
@@ -68,4 +68,24 @@ // Calls callback with false if there was any error when simulating the next // response. SetNextGATTConnectionResponse(string address, uint16 code) => (bool success); + + // Sets the next GATT Discovery request response for peripheral with + // |address| to |code|. |code| could be an HCI Error Code from + // BT 4.2 Vol 2 Part D 1.3 List Of Error Codes or a number outside that range + // returned by specific platforms e.g. Android returns 0x101 to signal a GATT + // failure + // https://developer.android.com/reference/android/bluetooth/BluetoothGatt.html#GATT_FAILURE + // Calls callback with false if there was any error when simulating the next + // response. + // + // The following procedures defined at BT 4.2 Vol 3 Part G Section 4. + // "GATT Feature Requirements" are used to discover attributes of the + // GATT Server: + // - Primary Service Discovery + // - Relationship Discovery + // - Characteristic Discovery + // - Characteristic Descriptor Discovery + // This method aims to simulate the response once all of these procedures + // have completed or if there was an error during any of them. + SetNextGATTDiscoveryResponse(string address, uint16 code) => (bool success); };
diff --git a/device/bluetooth/test/fake_central.cc b/device/bluetooth/test/fake_central.cc index 2b11378..74adb7b95 100644 --- a/device/bluetooth/test/fake_central.cc +++ b/device/bluetooth/test/fake_central.cc
@@ -60,6 +60,21 @@ std::move(callback).Run(true); } +void FakeCentral::SetNextGATTDiscoveryResponse( + const std::string& address, + uint16_t code, + SetNextGATTDiscoveryResponseCallback callback) { + auto device_iter = devices_.find(address); + if (device_iter == devices_.end()) { + std::move(callback).Run(false); + } + + FakePeripheral* fake_peripheral = + static_cast<FakePeripheral*>(device_iter->second.get()); + fake_peripheral->SetNextGATTDiscoveryResponse(code); + std::move(callback).Run(true); +} + std::string FakeCentral::GetAddress() const { NOTREACHED(); return std::string();
diff --git a/device/bluetooth/test/fake_central.h b/device/bluetooth/test/fake_central.h index 4b096eca..828cdb3 100644 --- a/device/bluetooth/test/fake_central.h +++ b/device/bluetooth/test/fake_central.h
@@ -33,6 +33,10 @@ const std::string& address, uint16_t code, SetNextGATTConnectionResponseCallback) override; + void SetNextGATTDiscoveryResponse( + const std::string& address, + uint16_t code, + SetNextGATTDiscoveryResponseCallback callback) override; // BluetoothAdapter overrides: std::string GetAddress() const override;
diff --git a/device/bluetooth/test/fake_peripheral.cc b/device/bluetooth/test/fake_peripheral.cc index a8524e2..3a0e0e7 100644 --- a/device/bluetooth/test/fake_peripheral.cc +++ b/device/bluetooth/test/fake_peripheral.cc
@@ -14,6 +14,7 @@ address_(address), system_connected_(false), gatt_connected_(false), + pending_gatt_discovery_(false), weak_ptr_factory_(this) {} FakePeripheral::~FakePeripheral() {} @@ -36,6 +37,11 @@ next_connection_response_ = code; } +void FakePeripheral::SetNextGATTDiscoveryResponse(uint16_t code) { + DCHECK(!next_discovery_response_); + next_discovery_response_ = code; +} + uint32_t FakePeripheral::GetBluetoothClass() const { NOTREACHED(); return 0; @@ -211,6 +217,31 @@ CreateGattConnectionImpl(); } +bool FakePeripheral::IsGattServicesDiscoveryComplete() const { + const bool discovery_complete = + BluetoothDevice::IsGattServicesDiscoveryComplete(); + DCHECK(!(pending_gatt_discovery_ && discovery_complete)); + + // There is currently no method to intiate a Service Discovery procedure. + // Web Bluetooth keeps a queue of pending getPrimaryServices() requests until + // BluetoothAdapter::Observer::GattServicesDiscovered is called. + // We use a call to IsGattServicesDiscoveryComplete as a signal that Web + // Bluetooth needs to initiate a Service Discovery procedure and post + // a task to call GattServicesDiscovered to simulate that the procedure has + // completed. + // TODO(crbug.com/729456): Remove this override and run + // DiscoverGattServices() callback with next_discovery_response_ once + // DiscoverGattServices() is implemented. + if (!pending_gatt_discovery_ && !discovery_complete) { + pending_gatt_discovery_ = true; + base::ThreadTaskRunnerHandle::Get()->PostTask( + FROM_HERE, base::Bind(&FakePeripheral::DispatchDiscoveryResponse, + weak_ptr_factory_.GetWeakPtr())); + } + + return discovery_complete; +} + void FakePeripheral::CreateGattConnectionImpl() { base::ThreadTaskRunnerHandle::Get()->PostTask( FROM_HERE, base::Bind(&FakePeripheral::DispatchConnectionResponse, @@ -233,6 +264,21 @@ } } +void FakePeripheral::DispatchDiscoveryResponse() { + DCHECK(next_discovery_response_); + + uint16_t code = next_discovery_response_.value(); + next_discovery_response_.reset(); + + pending_gatt_discovery_ = false; + if (code == mojom::kHCISuccess) { + SetGattServicesDiscoveryComplete(true); + GetAdapter()->NotifyGattServicesDiscovered(this); + } else { + SetGattServicesDiscoveryComplete(false); + } +} + void FakePeripheral::DisconnectGatt() { }
diff --git a/device/bluetooth/test/fake_peripheral.h b/device/bluetooth/test/fake_peripheral.h index b105c4f1..b42a4b2 100644 --- a/device/bluetooth/test/fake_peripheral.h +++ b/device/bluetooth/test/fake_peripheral.h
@@ -39,6 +39,12 @@ // with the ConnectErrorCode corresponding to |code|. void SetNextGATTConnectionResponse(uint16_t code); + // If |code| is kHCISuccess, calls + // BluetoothAdapter::Observer::GattServicesDiscovered otherwise + // sets IsGattDiscoveryComplete to false. Both of these happen + // after IsGattDiscoveryComplete is called. + void SetNextGATTDiscoveryResponse(uint16_t code); + // BluetoothDevice overrides: uint32_t GetBluetoothClass() const override; #if defined(OS_CHROMEOS) || defined(OS_LINUX) @@ -89,6 +95,7 @@ void CreateGattConnection( const GattConnectionCallback& callback, const ConnectErrorCallback& error_callback) override; + bool IsGattServicesDiscoveryComplete() const override; protected: void CreateGattConnectionImpl() override; @@ -96,6 +103,7 @@ private: void DispatchConnectionResponse(); + void DispatchDiscoveryResponse(); const std::string address_; base::Optional<std::string> name_; @@ -106,11 +114,21 @@ // True when this Bluetooth interface is connected to the device. bool gatt_connected_; + // Used to simulate a GATT Discovery procedure. + // Mutable because IsGattServicesDiscoveryComplete needs to set this but + // is const. + mutable bool pending_gatt_discovery_; + // Used to decide which callback should be called when // CreateGattConnection is called. base::Optional<uint16_t> next_connection_response_; - base::WeakPtrFactory<FakePeripheral> weak_ptr_factory_; + // Used to decide if the GattServicesDiscovered method is called. + base::Optional<uint16_t> next_discovery_response_; + + // Mutable because IsGattServicesDiscoveryComplete needs to post a task but + // is const. + mutable base::WeakPtrFactory<FakePeripheral> weak_ptr_factory_; DISALLOW_COPY_AND_ASSIGN(FakePeripheral); };
diff --git a/extensions/browser/BUILD.gn b/extensions/browser/BUILD.gn index a4483ca..2ca03e12 100644 --- a/extensions/browser/BUILD.gn +++ b/extensions/browser/BUILD.gn
@@ -47,6 +47,8 @@ "blacklist_state.h", "blob_holder.cc", "blob_holder.h", + "blob_reader.cc", + "blob_reader.h", "blocked_action_type.h", "browser_context_keyed_api_factory.h", "component_extension_resource_manager.h",
diff --git a/chrome/browser/extensions/blob_reader.cc b/extensions/browser/blob_reader.cc similarity index 87% rename from chrome/browser/extensions/blob_reader.cc rename to extensions/browser/blob_reader.cc index da5846da..45c2c122 100644 --- a/chrome/browser/extensions/blob_reader.cc +++ b/extensions/browser/blob_reader.cc
@@ -2,7 +2,7 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "chrome/browser/extensions/blob_reader.h" +#include "extensions/browser/blob_reader.h" #include <limits> #include <utility> @@ -10,8 +10,9 @@ #include "base/format_macros.h" #include "base/strings/string_util.h" #include "base/strings/stringprintf.h" -#include "chrome/browser/profiles/profile.h" +#include "content/public/browser/browser_context.h" #include "content/public/browser/browser_thread.h" +#include "content/public/browser/storage_partition.h" #include "net/http/http_request_headers.h" #include "net/http/http_response_headers.h" #include "net/traffic_annotation/network_traffic_annotation.h" @@ -19,7 +20,7 @@ #include "net/url_request/url_request_context.h" #include "net/url_request/url_request_context_getter.h" -BlobReader::BlobReader(Profile* profile, +BlobReader::BlobReader(content::BrowserContext* browser_context, const std::string& blob_uuid, BlobReadCallback callback) : callback_(callback) { @@ -38,7 +39,9 @@ // it is scheduled to be removed in (crbug.com/701851). fetcher_ = net::URLFetcher::Create(blob_url, net::URLFetcher::GET, this, NO_TRAFFIC_ANNOTATION_YET); - fetcher_->SetRequestContext(profile->GetRequestContext()); + fetcher_->SetRequestContext( + content::BrowserContext::GetDefaultStoragePartition(browser_context) + ->GetURLRequestContext()); } BlobReader::~BlobReader() { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); }
diff --git a/chrome/browser/extensions/blob_reader.h b/extensions/browser/blob_reader.h similarity index 85% rename from chrome/browser/extensions/blob_reader.h rename to extensions/browser/blob_reader.h index 4c0076a9c..23083ec 100644 --- a/chrome/browser/extensions/blob_reader.h +++ b/extensions/browser/blob_reader.h
@@ -2,8 +2,8 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#ifndef CHROME_BROWSER_EXTENSIONS_BLOB_READER_H_ -#define CHROME_BROWSER_EXTENSIONS_BLOB_READER_H_ +#ifndef EXTENSIONS_BROWSER_BLOB_READER_H_ +#define EXTENSIONS_BROWSER_BLOB_READER_H_ #include <stdint.h> @@ -17,7 +17,10 @@ #include "net/url_request/url_request.h" #include "url/gurl.h" -class Profile; +namespace content { +class BrowserContext; +} + namespace net { class URLFetcher; } @@ -32,7 +35,7 @@ int64_t blob_total_size)> BlobReadCallback; - BlobReader(Profile* profile, + BlobReader(content::BrowserContext* browser_context, const std::string& blob_uuid, BlobReadCallback callback); ~BlobReader() override; @@ -51,4 +54,4 @@ DISALLOW_COPY_AND_ASSIGN(BlobReader); }; -#endif // CHROME_BROWSER_EXTENSIONS_BLOB_READER_H_ +#endif // EXTENSIONS_BROWSER_BLOB_READER_H_
diff --git a/extensions/browser/extension_util.cc b/extensions/browser/extension_util.cc index 0961f42..5ed98fc 100644 --- a/extensions/browser/extension_util.cc +++ b/extensions/browser/extension_util.cc
@@ -78,6 +78,12 @@ return ExtensionPrefs::Get(context)->IsIncognitoEnabled(extension_id); } +GURL GetSiteForExtensionId(const std::string& extension_id, + content::BrowserContext* context) { + return content::SiteInstance::GetSiteForURL( + context, Extension::GetBaseURLFromExtensionId(extension_id)); +} + content::StoragePartition* GetStoragePartitionForExtensionId( const std::string& extension_id, content::BrowserContext* browser_context) {
diff --git a/extensions/browser/extension_util.h b/extensions/browser/extension_util.h index dd0c0e25..274c1a7 100644 --- a/extensions/browser/extension_util.h +++ b/extensions/browser/extension_util.h
@@ -7,7 +7,7 @@ #include <string> -class GURL; +#include "url/gurl.h" namespace content { class BrowserContext; @@ -39,6 +39,11 @@ bool IsIncognitoEnabled(const std::string& extension_id, content::BrowserContext* context); +// Returns the site of the |extension_id|, given the associated |context|. +// Suitable for use with BrowserContext::GetStoragePartitionForSite(). +GURL GetSiteForExtensionId(const std::string& extension_id, + content::BrowserContext* context); + content::StoragePartition* GetStoragePartitionForExtensionId( const std::string& extension_id, content::BrowserContext* browser_context);
diff --git a/ios/BUILD.gn b/ios/BUILD.gn index 874b62d..ec0e0b1 100644 --- a/ios/BUILD.gn +++ b/ios/BUILD.gn
@@ -15,6 +15,7 @@ v8_experimental_extra_library_files = [] v8_enable_gdbjit = false v8_imminent_deprecation_warnings = false + v8_check_microtasks_scopes_consistency = false } # Prevent warnings for unused build args above. @@ -22,6 +23,7 @@ assert(v8_experimental_extra_library_files != 0) assert(!v8_enable_gdbjit) assert(!v8_imminent_deprecation_warnings) +assert(!v8_check_microtasks_scopes_consistency) # This list all targets that needs to be build as part of "gn_all" on iOS. # This list should generally only include executables, but since some code
diff --git a/ios/chrome/browser/content_suggestions/content_suggestions_coordinator.mm b/ios/chrome/browser/content_suggestions/content_suggestions_coordinator.mm index 44315761..a803c220 100644 --- a/ios/chrome/browser/content_suggestions/content_suggestions_coordinator.mm +++ b/ios/chrome/browser/content_suggestions/content_suggestions_coordinator.mm
@@ -228,7 +228,7 @@ [weakSelf dismissArticle:weakArticle atIndexPath:indexPath]; } - style:UIAlertActionStyleDefault]; + style:UIAlertActionStyleDestructive]; [self.alertCoordinator addItemWithTitle:l10n_util::GetNSString(IDS_APP_CANCEL) action:^{ @@ -299,7 +299,7 @@ blacklistMostVisitedURL:strongItem.URL]; [strongSelf showMostVisitedUndoForURL:strongItem.URL]; } - style:UIAlertActionStyleDefault]; + style:UIAlertActionStyleDestructive]; [self.alertCoordinator addItemWithTitle:l10n_util::GetNSString(IDS_APP_CANCEL) action:nil
diff --git a/ios/chrome/browser/passwords/ios_chrome_password_manager_client.h b/ios/chrome/browser/passwords/ios_chrome_password_manager_client.h index 2e5aa6c4..b0cbd424 100644 --- a/ios/chrome/browser/passwords/ios_chrome_password_manager_client.h +++ b/ios/chrome/browser/passwords/ios_chrome_password_manager_client.h
@@ -22,11 +22,11 @@ // Shows UI to prompt the user to save the password. - (void)showSavePasswordInfoBar: - (scoped_refptr<password_manager::PasswordFormManager>)formToSave; + (std::unique_ptr<password_manager::PasswordFormManager>)formToSave; // Shows UI to prompt the user to update the password. - (void)showUpdatePasswordInfoBar: - (scoped_refptr<password_manager::PasswordFormManager>)formToUpdate; + (std::unique_ptr<password_manager::PasswordFormManager>)formToUpdate; @property(readonly, nonatomic) ios::ChromeBrowserState* browserState; @@ -46,14 +46,14 @@ // password_manager::PasswordManagerClient implementation. password_manager::PasswordSyncState GetPasswordSyncState() const override; bool PromptUserToSaveOrUpdatePassword( - scoped_refptr<password_manager::PasswordFormManager> form_to_save, + std::unique_ptr<password_manager::PasswordFormManager> form_to_save, bool update_password) override; bool PromptUserToChooseCredentials( std::vector<std::unique_ptr<autofill::PasswordForm>> local_forms, const GURL& origin, const CredentialsCallback& callback) override; void AutomaticPasswordSave( - scoped_refptr<password_manager::PasswordFormManager> saved_form_manager) + std::unique_ptr<password_manager::PasswordFormManager> saved_form_manager) override; bool IsIncognito() const override; PrefService* GetPrefs() override;
diff --git a/ios/chrome/browser/passwords/ios_chrome_password_manager_client.mm b/ios/chrome/browser/passwords/ios_chrome_password_manager_client.mm index 19f20bc..6c7c82a 100644 --- a/ios/chrome/browser/passwords/ios_chrome_password_manager_client.mm +++ b/ios/chrome/browser/passwords/ios_chrome_password_manager_client.mm
@@ -69,7 +69,7 @@ } bool IOSChromePasswordManagerClient::PromptUserToSaveOrUpdatePassword( - scoped_refptr<PasswordFormManager> form_to_save, + std::unique_ptr<PasswordFormManager> form_to_save, bool update_password) { if (form_to_save->IsBlacklisted()) return false; @@ -84,7 +84,7 @@ } void IOSChromePasswordManagerClient::AutomaticPasswordSave( - scoped_refptr<PasswordFormManager> saved_form_manager) { + std::unique_ptr<PasswordFormManager> saved_form_manager) { NOTIMPLEMENTED(); }
diff --git a/ios/chrome/browser/passwords/ios_chrome_password_manager_infobar_delegate.h b/ios/chrome/browser/passwords/ios_chrome_password_manager_infobar_delegate.h index d85fd60..afc444a 100644 --- a/ios/chrome/browser/passwords/ios_chrome_password_manager_infobar_delegate.h +++ b/ios/chrome/browser/passwords/ios_chrome_password_manager_infobar_delegate.h
@@ -8,7 +8,6 @@ #include <memory> #include "base/macros.h" -#include "base/memory/ref_counted.h" #include "components/infobars/core/confirm_infobar_delegate.h" #include "components/password_manager/core/browser/password_manager_metrics_util.h" @@ -27,7 +26,7 @@ protected: IOSChromePasswordManagerInfoBarDelegate( bool is_smart_lock_branding_enabled, - scoped_refptr<password_manager::PasswordFormManager> form_manager); + std::unique_ptr<password_manager::PasswordFormManager> form_manager); password_manager::PasswordFormManager* form_to_save() const { return form_to_save_.get(); @@ -51,7 +50,7 @@ // The password_manager::PasswordFormManager managing the form we're asking // the user about, and should save as per their decision. - scoped_refptr<password_manager::PasswordFormManager> form_to_save_; + std::unique_ptr<password_manager::PasswordFormManager> form_to_save_; // Used to track the results we get from the info bar. password_manager::metrics_util::UIDismissalReason infobar_response_;
diff --git a/ios/chrome/browser/passwords/ios_chrome_password_manager_infobar_delegate.mm b/ios/chrome/browser/passwords/ios_chrome_password_manager_infobar_delegate.mm index b82afeb..db7cea2 100644 --- a/ios/chrome/browser/passwords/ios_chrome_password_manager_infobar_delegate.mm +++ b/ios/chrome/browser/passwords/ios_chrome_password_manager_infobar_delegate.mm
@@ -27,7 +27,7 @@ IOSChromePasswordManagerInfoBarDelegate:: IOSChromePasswordManagerInfoBarDelegate( bool is_smart_lock_branding_enabled, - scoped_refptr<password_manager::PasswordFormManager> form_to_save) + std::unique_ptr<password_manager::PasswordFormManager> form_to_save) : form_to_save_(std::move(form_to_save)), infobar_response_(password_manager::metrics_util::NO_DIRECT_INTERACTION), is_smart_lock_branding_enabled_(is_smart_lock_branding_enabled) {}
diff --git a/ios/chrome/browser/passwords/ios_chrome_save_password_infobar_delegate.h b/ios/chrome/browser/passwords/ios_chrome_save_password_infobar_delegate.h index 0b187f7..821581c 100644 --- a/ios/chrome/browser/passwords/ios_chrome_save_password_infobar_delegate.h +++ b/ios/chrome/browser/passwords/ios_chrome_save_password_infobar_delegate.h
@@ -30,7 +30,7 @@ static void Create( bool is_smart_lock_branding_enabled, infobars::InfoBarManager* infobar_manager, - scoped_refptr<password_manager::PasswordFormManager> form_to_save); + std::unique_ptr<password_manager::PasswordFormManager> form_to_save); ~IOSChromeSavePasswordInfoBarDelegate() override; @@ -39,7 +39,7 @@ private: IOSChromeSavePasswordInfoBarDelegate( bool is_smart_lock_branding_enabled, - scoped_refptr<password_manager::PasswordFormManager> form_to_save); + std::unique_ptr<password_manager::PasswordFormManager> form_to_save); // ConfirmInfoBarDelegate implementation. infobars::InfoBarDelegate::InfoBarIdentifier GetIdentifier() const override;
diff --git a/ios/chrome/browser/passwords/ios_chrome_save_password_infobar_delegate.mm b/ios/chrome/browser/passwords/ios_chrome_save_password_infobar_delegate.mm index e5a17976..a0274c3 100644 --- a/ios/chrome/browser/passwords/ios_chrome_save_password_infobar_delegate.mm +++ b/ios/chrome/browser/passwords/ios_chrome_save_password_infobar_delegate.mm
@@ -22,7 +22,7 @@ void IOSChromeSavePasswordInfoBarDelegate::Create( bool is_smart_lock_branding_enabled, infobars::InfoBarManager* infobar_manager, - scoped_refptr<PasswordFormManager> form_to_save) { + std::unique_ptr<PasswordFormManager> form_to_save) { DCHECK(infobar_manager); auto delegate = base::WrapUnique(new IOSChromeSavePasswordInfoBarDelegate( is_smart_lock_branding_enabled, std::move(form_to_save))); @@ -34,7 +34,7 @@ IOSChromeSavePasswordInfoBarDelegate::IOSChromeSavePasswordInfoBarDelegate( bool is_smart_lock_branding_enabled, - scoped_refptr<PasswordFormManager> form_to_save) + std::unique_ptr<PasswordFormManager> form_to_save) : IOSChromePasswordManagerInfoBarDelegate(is_smart_lock_branding_enabled, std::move(form_to_save)) {}
diff --git a/ios/chrome/browser/passwords/ios_chrome_update_password_infobar_delegate.h b/ios/chrome/browser/passwords/ios_chrome_update_password_infobar_delegate.h index cdd99bf5..d720ba2 100644 --- a/ios/chrome/browser/passwords/ios_chrome_update_password_infobar_delegate.h +++ b/ios/chrome/browser/passwords/ios_chrome_update_password_infobar_delegate.h
@@ -27,7 +27,7 @@ static void Create( bool is_smart_lock_branding_enabled, infobars::InfoBarManager* infobar_manager, - scoped_refptr<password_manager::PasswordFormManager> form_to_save); + std::unique_ptr<password_manager::PasswordFormManager> form_to_save); ~IOSChromeUpdatePasswordInfoBarDelegate() override; @@ -49,7 +49,7 @@ private: IOSChromeUpdatePasswordInfoBarDelegate( bool is_smart_lock_branding_enabled, - scoped_refptr<password_manager::PasswordFormManager> form_to_save); + std::unique_ptr<password_manager::PasswordFormManager> form_to_save); // Returns the string with the branded title of the password manager (e.g. // "Google Smart Lock for Passwords").
diff --git a/ios/chrome/browser/passwords/ios_chrome_update_password_infobar_delegate.mm b/ios/chrome/browser/passwords/ios_chrome_update_password_infobar_delegate.mm index 0929fcf..19afa48 100644 --- a/ios/chrome/browser/passwords/ios_chrome_update_password_infobar_delegate.mm +++ b/ios/chrome/browser/passwords/ios_chrome_update_password_infobar_delegate.mm
@@ -27,7 +27,7 @@ void IOSChromeUpdatePasswordInfoBarDelegate::Create( bool is_smart_lock_branding_enabled, infobars::InfoBarManager* infobar_manager, - scoped_refptr<PasswordFormManager> form_manager) { + std::unique_ptr<PasswordFormManager> form_manager) { DCHECK(infobar_manager); auto delegate = base::WrapUnique(new IOSChromeUpdatePasswordInfoBarDelegate( is_smart_lock_branding_enabled, std::move(form_manager))); @@ -43,7 +43,7 @@ IOSChromeUpdatePasswordInfoBarDelegate::IOSChromeUpdatePasswordInfoBarDelegate( bool is_smart_lock_branding_enabled, - scoped_refptr<PasswordFormManager> form_manager) + std::unique_ptr<PasswordFormManager> form_manager) : IOSChromePasswordManagerInfoBarDelegate(is_smart_lock_branding_enabled, std::move(form_manager)) { selected_account_ = form_to_save()->preferred_match()->username_value;
diff --git a/ios/chrome/browser/passwords/password_controller.mm b/ios/chrome/browser/passwords/password_controller.mm index 608285e5..2545cb3 100644 --- a/ios/chrome/browser/passwords/password_controller.mm +++ b/ios/chrome/browser/passwords/password_controller.mm
@@ -18,7 +18,6 @@ #include "base/mac/foundation_util.h" #include "base/mac/scoped_nsobject.h" #include "base/memory/ptr_util.h" -#include "base/memory/ref_counted.h" #include "base/strings/string16.h" #include "base/strings/sys_string_conversions.h" #include "base/strings/utf_string_conversions.h" @@ -119,7 +118,7 @@ // Displays infobar for |form| with |type|. If |type| is UPDATE, the user // is prompted to update the password. If |type| is SAVE, the user is prompted // to save the password. -- (void)showInfoBarForForm:(scoped_refptr<PasswordFormManager>)form +- (void)showInfoBarForForm:(std::unique_ptr<PasswordFormManager>)form infoBarType:(PasswordInfoBarType)type; @end @@ -643,13 +642,14 @@ #pragma mark - PasswordManagerClientDelegate -- (void)showSavePasswordInfoBar:(scoped_refptr<PasswordFormManager>)formToSave { +- (void)showSavePasswordInfoBar: + (std::unique_ptr<PasswordFormManager>)formToSave { [self showInfoBarForForm:std::move(formToSave) infoBarType:PasswordInfoBarType::SAVE]; } - (void)showUpdatePasswordInfoBar: - (scoped_refptr<PasswordFormManager>)formToUpdate { + (std::unique_ptr<PasswordFormManager>)formToUpdate { [self showInfoBarForForm:std::move(formToUpdate) infoBarType:PasswordInfoBarType::UPDATE]; } @@ -852,7 +852,7 @@ #pragma mark - Private methods -- (void)showInfoBarForForm:(scoped_refptr<PasswordFormManager>)form +- (void)showInfoBarForForm:(std::unique_ptr<PasswordFormManager>)form infoBarType:(PasswordInfoBarType)type { if (!webStateObserverBridge_ || !webStateObserverBridge_->web_state()) return;
diff --git a/ios/chrome/browser/payments/payment_request.h b/ios/chrome/browser/payments/payment_request.h index 8bc25f60..65ea580 100644 --- a/ios/chrome/browser/payments/payment_request.h +++ b/ios/chrome/browser/payments/payment_request.h
@@ -163,7 +163,7 @@ // Returns whether the current PaymentRequest can be used to make a payment. bool CanMakePayment() const; - protected: + private: // Fetches the autofill profiles for this user from the PersonalDataManager, // and stores copies of them, owned by this PaymentRequest, in profile_cache_. void PopulateProfileCache();
diff --git a/ios/chrome/browser/payments/test_payment_request.h b/ios/chrome/browser/payments/test_payment_request.h index 1d6eda9..025d38eb 100644 --- a/ios/chrome/browser/payments/test_payment_request.h +++ b/ios/chrome/browser/payments/test_payment_request.h
@@ -15,7 +15,6 @@ namespace web { class PaymentRequest; -class PaymentShippingOption; } // namespace web // PaymentRequest for use in tests. @@ -32,24 +31,6 @@ region_data_loader_ = region_data_loader; } - // Returns the web::PaymentRequest instance that was used to build this - // object. - web::PaymentRequest& web_payment_request() { return web_payment_request_; } - - // Removes all the shipping profiles. - void ClearShippingProfiles(); - - // Removes all the contact profiles. - void ClearContactProfiles(); - - // Removes all the credit cards. - void ClearCreditCards(); - - // Sets the currently selected shipping option for this PaymentRequest flow. - void set_selected_shipping_option(web::PaymentShippingOption* option) { - selected_shipping_option_ = option; - } - // PaymentRequest autofill::RegionDataLoader* GetRegionDataLoader() override;
diff --git a/ios/chrome/browser/payments/test_payment_request.mm b/ios/chrome/browser/payments/test_payment_request.mm index a2e1e49..37f20d9 100644 --- a/ios/chrome/browser/payments/test_payment_request.mm +++ b/ios/chrome/browser/payments/test_payment_request.mm
@@ -12,18 +12,6 @@ #error "This file requires ARC support." #endif -void TestPaymentRequest::ClearShippingProfiles() { - shipping_profiles_.clear(); -} - -void TestPaymentRequest::ClearContactProfiles() { - contact_profiles_.clear(); -} - -void TestPaymentRequest::ClearCreditCards() { - credit_cards_.clear(); -} - autofill::RegionDataLoader* TestPaymentRequest::GetRegionDataLoader() { return region_data_loader_; }
diff --git a/ios/chrome/browser/ui/payments/BUILD.gn b/ios/chrome/browser/ui/payments/BUILD.gn index a827903..feeadd8 100644 --- a/ios/chrome/browser/ui/payments/BUILD.gn +++ b/ios/chrome/browser/ui/payments/BUILD.gn
@@ -45,6 +45,9 @@ "payment_request_manager.mm", "payment_request_mediator.h", "payment_request_mediator.mm", + "payment_request_view_controller.h", + "payment_request_view_controller.mm", + "payment_request_view_controller_actions.h", "region_data_loader.h", "region_data_loader.mm", "shipping_address_selection_coordinator.h", @@ -116,10 +119,6 @@ "payment_request_selector_view_controller.mm", "payment_request_selector_view_controller_actions.h", "payment_request_selector_view_controller_data_source.h", - "payment_request_view_controller.h", - "payment_request_view_controller.mm", - "payment_request_view_controller_actions.h", - "payment_request_view_controller_data_source.h", ] deps = [ "//base", @@ -157,7 +156,6 @@ "payment_request_edit_view_controller_unittest.mm", "payment_request_error_coordinator_unittest.mm", "payment_request_error_view_controller_unittest.mm", - "payment_request_mediator_unittest.mm", "payment_request_selector_view_controller_unittest.mm", "payment_request_view_controller_unittest.mm", "region_data_loader_unittest.mm",
diff --git a/ios/chrome/browser/ui/payments/payment_request_coordinator.mm b/ios/chrome/browser/ui/payments/payment_request_coordinator.mm index 1ada066..08653996 100644 --- a/ios/chrome/browser/ui/payments/payment_request_coordinator.mm +++ b/ios/chrome/browser/ui/payments/payment_request_coordinator.mm
@@ -55,10 +55,10 @@ - (void)start { _mediator = - [[PaymentRequestMediator alloc] initWithBrowserState:_browserState - paymentRequest:_paymentRequest]; + [[PaymentRequestMediator alloc] initWithBrowserState:_browserState]; - _viewController = [[PaymentRequestViewController alloc] init]; + _viewController = [[PaymentRequestViewController alloc] + initWithPaymentRequest:_paymentRequest]; [_viewController setPageFavicon:_pageFavicon]; [_viewController setPageTitle:_pageTitle]; [_viewController setPageHost:_pageHost]; @@ -124,7 +124,6 @@ - (void)updatePaymentDetails:(web::PaymentDetails)paymentDetails { BOOL totalValueChanged = (_paymentRequest->payment_details().total != paymentDetails.total); - [_mediator setTotalValueChanged:totalValueChanged]; _paymentRequest->UpdatePaymentDetails(paymentDetails); if (_paymentRequest->shipping_options().empty()) { @@ -139,25 +138,29 @@ [_viewController loadModel]; [[_viewController collectionView] reloadData]; } else { - // Update the payment summary item. - [_viewController updatePaymentSummaryItem]; + // Update the payment summary section. + [_viewController + updatePaymentSummaryWithTotalValueChanged:totalValueChanged]; if (_shippingAddressSelectionCoordinator) { - // Set the selected shipping address. + // Set the selected shipping address and update the selected shipping + // address in the payment request summary view. _paymentRequest->set_selected_shipping_profile(_pendingShippingAddress); _pendingShippingAddress = nil; + [_viewController updateSelectedShippingAddressUI]; // Dismiss the shipping address selection view. [_shippingAddressSelectionCoordinator stop]; _shippingAddressSelectionCoordinator = nil; } else if (_shippingOptionSelectionCoordinator) { + // Update the selected shipping option in the payment request summary + // view. The updated selection is already reflected in |_paymentRequest|. + [_viewController updateSelectedShippingOptionUI]; + // Dismiss the shipping option selection view. [_shippingOptionSelectionCoordinator stop]; _shippingOptionSelectionCoordinator = nil; } - - // Update the Shipping section in the payment request summary view. - [_viewController updateShippingSection]; } } @@ -257,7 +260,7 @@ - (void)paymentItemsDisplayCoordinatorDidReturn: (PaymentItemsDisplayCoordinator*)coordinator { // Clear the 'Updated' label on the payment summary item, if there is one. - [_viewController updatePaymentSummaryItem]; + [_viewController updatePaymentSummaryWithTotalValueChanged:NO]; [_itemsDisplayCoordinator stop]; _itemsDisplayCoordinator = nil; @@ -275,7 +278,7 @@ didSelectContactProfile:(autofill::AutofillProfile*)contactProfile { _paymentRequest->set_selected_contact_profile(contactProfile); - [_viewController updateContactInfoSection]; + [_viewController updateSelectedContactInfoUI]; [_contactInfoSelectionCoordinator stop]; _contactInfoSelectionCoordinator = nil; @@ -303,7 +306,7 @@ - (void)shippingAddressSelectionCoordinatorDidReturn: (ShippingAddressSelectionCoordinator*)coordinator { // Clear the 'Updated' label on the payment summary item, if there is one. - [_viewController updatePaymentSummaryItem]; + [_viewController updatePaymentSummaryWithTotalValueChanged:NO]; [_shippingAddressSelectionCoordinator stop]; _shippingAddressSelectionCoordinator = nil; @@ -322,7 +325,7 @@ - (void)shippingOptionSelectionCoordinatorDidReturn: (ShippingAddressSelectionCoordinator*)coordinator { // Clear the 'Updated' label on the payment summary item, if there is one. - [_viewController updatePaymentSummaryItem]; + [_viewController updatePaymentSummaryWithTotalValueChanged:NO]; [_shippingOptionSelectionCoordinator stop]; _shippingOptionSelectionCoordinator = nil; @@ -335,10 +338,10 @@ didSelectPaymentMethod:(autofill::CreditCard*)creditCard { _paymentRequest->set_selected_credit_card(creditCard); - [_viewController updatePaymentMethodSection]; + [_viewController updateSelectedPaymentMethodUI]; // Clear the 'Updated' label on the payment summary item, if there is one. - [_viewController updatePaymentSummaryItem]; + [_viewController updatePaymentSummaryWithTotalValueChanged:NO]; [_methodSelectionCoordinator stop]; _methodSelectionCoordinator = nil; @@ -347,7 +350,7 @@ - (void)paymentMethodSelectionCoordinatorDidReturn: (PaymentMethodSelectionCoordinator*)coordinator { // Clear the 'Updated' label on the payment summary item, if there is one. - [_viewController updatePaymentSummaryItem]; + [_viewController updatePaymentSummaryWithTotalValueChanged:NO]; [_methodSelectionCoordinator stop]; _methodSelectionCoordinator = nil;
diff --git a/ios/chrome/browser/ui/payments/payment_request_mediator.h b/ios/chrome/browser/ui/payments/payment_request_mediator.h index e24f2b5..7835b29 100644 --- a/ios/chrome/browser/ui/payments/payment_request_mediator.h +++ b/ios/chrome/browser/ui/payments/payment_request_mediator.h
@@ -5,27 +5,17 @@ #ifndef IOS_CHROME_BROWSER_UI_PAYMENTS_PAYMENT_REQUEST_MEDIATOR_H_ #define IOS_CHROME_BROWSER_UI_PAYMENTS_PAYMENT_REQUEST_MEDIATOR_H_ -#import "ios/chrome/browser/ui/payments/payment_request_view_controller_data_source.h" +#include "ios/chrome/browser/ui/payments/payment_request_view_controller.h" namespace ios { class ChromeBrowserState; } // namespace ios -class PaymentRequest; - // A mediator object that provides data for a PaymentRequestViewController. @interface PaymentRequestMediator : NSObject<PaymentRequestViewControllerDataSource> -// Whether or not the total price value was changed by the merchant. -@property(nonatomic, assign) BOOL totalValueChanged; - -// Initializes this object with an instance of ios::ChromeBrowserState and an -// instance of PaymentRequest which has a copy of web::PaymentRequest as -// provided by the page invoking the Payment Request API. This object will not -// take ownership of |browserState| or |paymentRequest|. - (instancetype)initWithBrowserState:(ios::ChromeBrowserState*)browserState - paymentRequest:(PaymentRequest*)paymentRequest NS_DESIGNATED_INITIALIZER; - (instancetype)init NS_UNAVAILABLE;
diff --git a/ios/chrome/browser/ui/payments/payment_request_mediator.mm b/ios/chrome/browser/ui/payments/payment_request_mediator.mm index 494729a0..ce5c2d6f 100644 --- a/ios/chrome/browser/ui/payments/payment_request_mediator.mm +++ b/ios/chrome/browser/ui/payments/payment_request_mediator.mm
@@ -2,279 +2,28 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#import <Foundation/Foundation.h> - #include "ios/chrome/browser/ui/payments/payment_request_mediator.h" #include "base/strings/sys_string_conversions.h" -#include "base/strings/utf_string_conversions.h" -#include "components/autofill/core/browser/autofill_data_util.h" -#include "components/autofill/core/browser/autofill_profile.h" -#include "components/autofill/core/browser/credit_card.h" -#include "components/autofill/core/browser/field_types.h" -#include "components/payments/core/currency_formatter.h" -#include "components/payments/core/strings_util.h" #include "components/signin/core/browser/signin_manager.h" -#include "components/strings/grit/components_strings.h" -#include "ios/chrome/browser/payments/payment_request.h" -#include "ios/chrome/browser/payments/payment_request_util.h" #include "ios/chrome/browser/signin/signin_manager_factory.h" -#import "ios/chrome/browser/ui/collection_view/cells/collection_view_detail_item.h" -#import "ios/chrome/browser/ui/collection_view/cells/collection_view_footer_item.h" -#import "ios/chrome/browser/ui/collection_view/cells/collection_view_item.h" -#import "ios/chrome/browser/ui/payments/cells/autofill_profile_item.h" -#import "ios/chrome/browser/ui/payments/cells/payment_method_item.h" -#import "ios/chrome/browser/ui/payments/cells/payments_text_item.h" -#import "ios/chrome/browser/ui/payments/cells/price_item.h" -#include "ios/chrome/browser/ui/uikit_ui_util.h" -#include "ui/base/l10n/l10n_util.h" -#include "ui/base/resource/resource_bundle.h" -#if !defined(__has_feature) || !__has_feature(objc_arc) -#error "This file requires ARC support." -#endif +@implementation PaymentRequestMediator { + ios::ChromeBrowserState* _browserState; +} -namespace { -// String used as the "URL" to take the user to the settings page for card and -// address options. Needs to be URL-like; otherwise, the link will not appear -// as a link in the UI (see setLabelLinkURL: in CollectionViewFooterCell). -const char kSettingsURL[] = "settings://card-and-address"; - -using ::payments::GetShippingOptionSectionString; -using ::payment_request_util::GetEmailLabelFromAutofillProfile; -using ::payment_request_util::GetNameLabelFromAutofillProfile; -using ::payment_request_util::GetPhoneNumberLabelFromAutofillProfile; -using ::payment_request_util::GetShippingAddressLabelFromAutofillProfile; -using ::payment_request_util::GetShippingSectionTitle; -} // namespace - -@interface PaymentRequestMediator () - -@property(nonatomic, assign) ios::ChromeBrowserState* browserState; - -// The PaymentRequest object owning an instance of web::PaymentRequest as -// provided by the page invoking the Payment Request API. This is a weak -// pointer and should outlive this class. -@property(nonatomic, assign) PaymentRequest* paymentRequest; - -@end - -@implementation PaymentRequestMediator - -@synthesize totalValueChanged = _totalValueChanged; -@synthesize browserState = _browserState; -@synthesize paymentRequest = _paymentRequest; - -- (instancetype)initWithBrowserState:(ios::ChromeBrowserState*)browserState - paymentRequest:(PaymentRequest*)paymentRequest { +- (instancetype)initWithBrowserState:(ios::ChromeBrowserState*)browserState { DCHECK(browserState); self = [super init]; if (self) { _browserState = browserState; - _paymentRequest = paymentRequest; } return self; } -#pragma mark - PaymentRequestViewControllerDataSource - -- (BOOL)canPay { - return self.paymentRequest->selected_credit_card() != nullptr && - (self.paymentRequest->selected_shipping_option() != nullptr || - ![self requestShipping]) && - (self.paymentRequest->selected_shipping_profile() != nullptr || - ![self requestShipping]) && - (self.paymentRequest->selected_contact_profile() != nullptr || - ![self requestContactInfo]); -} - -- (BOOL)canShip { - return !self.paymentRequest->shipping_options().empty() && - self.paymentRequest->selected_shipping_profile() != nullptr; -} - -- (BOOL)hasPaymentItems { - return !self.paymentRequest->payment_details().display_items.empty(); -} - -- (BOOL)requestShipping { - return self.paymentRequest->request_shipping(); -} - -- (BOOL)requestContactInfo { - return self.paymentRequest->request_payer_name() || - self.paymentRequest->request_payer_email() || - self.paymentRequest->request_payer_phone(); -} - -- (CollectionViewItem*)paymentSummaryItem { - PriceItem* item = [[PriceItem alloc] init]; - item.item = base::SysUTF16ToNSString( - self.paymentRequest->payment_details().total.label); - payments::CurrencyFormatter* currencyFormatter = - self.paymentRequest->GetOrCreateCurrencyFormatter(); - item.price = SysUTF16ToNSString(l10n_util::GetStringFUTF16( - IDS_PAYMENT_REQUEST_ORDER_SUMMARY_SHEET_TOTAL_FORMAT, - base::UTF8ToUTF16(currencyFormatter->formatted_currency_code()), - currencyFormatter->Format(base::UTF16ToASCII( - self.paymentRequest->payment_details().total.amount.value)))); - item.notification = self.totalValueChanged - ? l10n_util::GetNSString(IDS_PAYMENTS_UPDATED_LABEL) - : nil; - self.totalValueChanged = NO; - if ([self hasPaymentItems]) { - item.accessoryType = MDCCollectionViewCellAccessoryDisclosureIndicator; - } - return item; -} - -- (CollectionViewItem*)shippingSectionHeaderItem { - PaymentsTextItem* item = [[PaymentsTextItem alloc] init]; - item.text = GetShippingSectionTitle(self.paymentRequest->shipping_type()); - return item; -} - -- (CollectionViewItem*)shippingAddressItem { - const autofill::AutofillProfile* profile = - self.paymentRequest->selected_shipping_profile(); - if (profile) { - AutofillProfileItem* item = [[AutofillProfileItem alloc] init]; - item.name = GetNameLabelFromAutofillProfile(*profile); - item.address = GetShippingAddressLabelFromAutofillProfile(*profile); - item.phoneNumber = GetPhoneNumberLabelFromAutofillProfile(*profile); - item.accessoryType = MDCCollectionViewCellAccessoryDisclosureIndicator; - return item; - } - - CollectionViewDetailItem* item = [[CollectionViewDetailItem alloc] init]; - item.text = SysUTF16ToNSString( - GetShippingAddressSectionString(self.paymentRequest->shipping_type())); - if (self.paymentRequest->shipping_profiles().empty()) { - item.detailText = [l10n_util::GetNSString(IDS_ADD) - uppercaseStringWithLocale:[NSLocale currentLocale]]; - } else { - item.accessoryType = MDCCollectionViewCellAccessoryDisclosureIndicator; - } - return item; -} - -- (CollectionViewItem*)shippingOptionItem { - const web::PaymentShippingOption* option = - self.paymentRequest->selected_shipping_option(); - if (option) { - PaymentsTextItem* item = [[PaymentsTextItem alloc] init]; - item.text = base::SysUTF16ToNSString(option->label); - payments::CurrencyFormatter* currencyFormatter = - self.paymentRequest->GetOrCreateCurrencyFormatter(); - item.detailText = SysUTF16ToNSString( - currencyFormatter->Format(base::UTF16ToASCII(option->amount.value))); - item.accessoryType = MDCCollectionViewCellAccessoryDisclosureIndicator; - return item; - } - - CollectionViewDetailItem* item = [[CollectionViewDetailItem alloc] init]; - item.text = base::SysUTF16ToNSString( - GetShippingOptionSectionString(self.paymentRequest->shipping_type())); - item.accessoryType = MDCCollectionViewCellAccessoryDisclosureIndicator; - return item; -} - -- (CollectionViewItem*)paymentMethodSectionHeaderItem { - if (!self.paymentRequest->selected_credit_card()) - return nil; - PaymentsTextItem* item = [[PaymentsTextItem alloc] init]; - item.text = - l10n_util::GetNSString(IDS_PAYMENT_REQUEST_PAYMENT_METHOD_SECTION_NAME); - return item; -} - -- (CollectionViewItem*)paymentMethodItem { - const autofill::CreditCard* creditCard = - self.paymentRequest->selected_credit_card(); - if (creditCard) { - PaymentMethodItem* item = [[PaymentMethodItem alloc] init]; - item.methodID = - base::SysUTF16ToNSString(creditCard->NetworkAndLastFourDigits()); - item.methodDetail = base::SysUTF16ToNSString( - creditCard->GetRawInfo(autofill::CREDIT_CARD_NAME_FULL)); - int issuerNetworkIconID = - autofill::data_util::GetPaymentRequestData(creditCard->network()) - .icon_resource_id; - item.methodTypeIcon = NativeImage(issuerNetworkIconID); - item.accessoryType = MDCCollectionViewCellAccessoryDisclosureIndicator; - return item; - } - - CollectionViewDetailItem* item = [[CollectionViewDetailItem alloc] init]; - item.text = - l10n_util::GetNSString(IDS_PAYMENT_REQUEST_PAYMENT_METHOD_SECTION_NAME); - if (self.paymentRequest->credit_cards().empty()) { - item.detailText = [l10n_util::GetNSString(IDS_ADD) - uppercaseStringWithLocale:[NSLocale currentLocale]]; - } else { - item.accessoryType = MDCCollectionViewCellAccessoryDisclosureIndicator; - } - return item; -} - -- (CollectionViewItem*)contactInfoSectionHeaderItem { - if (!self.paymentRequest->selected_contact_profile()) - return nil; - PaymentsTextItem* item = [[PaymentsTextItem alloc] init]; - item.text = l10n_util::GetNSString(IDS_PAYMENTS_CONTACT_DETAILS_LABEL); - return item; -} - -- (CollectionViewItem*)contactInfoItem { - const autofill::AutofillProfile* profile = - self.paymentRequest->selected_contact_profile(); - if (profile) { - AutofillProfileItem* item = [[AutofillProfileItem alloc] init]; - item.name = GetNameLabelFromAutofillProfile(*profile); - item.phoneNumber = GetPhoneNumberLabelFromAutofillProfile(*profile); - item.email = GetEmailLabelFromAutofillProfile(*profile); - item.accessoryType = MDCCollectionViewCellAccessoryDisclosureIndicator; - return item; - } - - CollectionViewDetailItem* item = [[CollectionViewDetailItem alloc] init]; - item.text = l10n_util::GetNSString(IDS_PAYMENTS_CONTACT_DETAILS_LABEL); - if (self.paymentRequest->contact_profiles().empty()) { - item.detailText = [l10n_util::GetNSString(IDS_ADD) - uppercaseStringWithLocale:[NSLocale currentLocale]]; - } else { - item.accessoryType = MDCCollectionViewCellAccessoryDisclosureIndicator; - } - return item; -} - -- (CollectionViewFooterItem*)footerItem { - CollectionViewFooterItem* item = [[CollectionViewFooterItem alloc] init]; - - // TODO(crbug.com/602666): Find out if the first payment has completed. - BOOL firstPaymentCompleted = YES; - if (!firstPaymentCompleted) { - item.text = l10n_util::GetNSString(IDS_PAYMENTS_CARD_AND_ADDRESS_SETTINGS); - } else if ([[self authenticatedAccountName] length]) { - const base::string16 accountName = - base::SysNSStringToUTF16([self authenticatedAccountName]); - const std::string formattedString = l10n_util::GetStringFUTF8( - IDS_PAYMENTS_CARD_AND_ADDRESS_SETTINGS_SIGNED_IN, accountName); - item.text = base::SysUTF8ToNSString(formattedString); - } else { - item.text = l10n_util::GetNSString( - IDS_PAYMENTS_CARD_AND_ADDRESS_SETTINGS_SIGNED_OUT); - } - item.linkURL = GURL(kSettingsURL); - return item; -} - -#pragma mark - Helper methods - -// Returns the authenticated account name, or nil if user is not authenticated. - (NSString*)authenticatedAccountName { const SigninManager* signinManager = - ios::SigninManagerFactory::GetForBrowserStateIfExists(self.browserState); + ios::SigninManagerFactory::GetForBrowserStateIfExists(_browserState); if (signinManager && signinManager->IsAuthenticated()) { return base::SysUTF8ToNSString( signinManager->GetAuthenticatedAccountInfo().email);
diff --git a/ios/chrome/browser/ui/payments/payment_request_mediator_unittest.mm b/ios/chrome/browser/ui/payments/payment_request_mediator_unittest.mm deleted file mode 100644 index 3bbd1d6..0000000 --- a/ios/chrome/browser/ui/payments/payment_request_mediator_unittest.mm +++ /dev/null
@@ -1,419 +0,0 @@ -// Copyright 2017 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#import "ios/chrome/browser/ui/payments/payment_request_mediator.h" - -#import <Foundation/Foundation.h> - -#include "base/mac/foundation_util.h" -#include "base/memory/ptr_util.h" -#include "base/strings/utf_string_conversions.h" -#include "components/autofill/core/browser/autofill_profile.h" -#include "components/autofill/core/browser/autofill_test_utils.h" -#include "components/autofill/core/browser/credit_card.h" -#include "components/autofill/core/browser/test_personal_data_manager.h" -#include "components/payments/core/strings_util.h" -#include "components/signin/core/browser/signin_manager.h" -#include "components/strings/grit/components_strings.h" -#include "ios/chrome/browser/browser_state/test_chrome_browser_state.h" -#include "ios/chrome/browser/payments/payment_request_test_util.h" -#include "ios/chrome/browser/payments/payment_request_util.h" -#include "ios/chrome/browser/payments/test_payment_request.h" -#include "ios/chrome/browser/signin/fake_signin_manager_builder.h" -#include "ios/chrome/browser/signin/signin_manager_factory.h" -#import "ios/chrome/browser/ui/collection_view/cells/collection_view_detail_item.h" -#import "ios/chrome/browser/ui/collection_view/cells/collection_view_footer_item.h" -#import "ios/chrome/browser/ui/payments/cells/autofill_profile_item.h" -#import "ios/chrome/browser/ui/payments/cells/payment_method_item.h" -#import "ios/chrome/browser/ui/payments/cells/payments_text_item.h" -#import "ios/chrome/browser/ui/payments/cells/price_item.h" -#include "ios/web/public/payments/payment_request.h" -#include "ios/web/public/test/test_web_thread_bundle.h" -#include "testing/gtest/include/gtest/gtest.h" -#include "testing/platform_test.h" -#include "ui/base/l10n/l10n_util.h" - -#if !defined(__has_feature) || !__has_feature(objc_arc) -#error "This file requires ARC support." -#endif - -namespace { -using ::payments::GetShippingOptionSectionString; -using ::payment_request_util::GetEmailLabelFromAutofillProfile; -using ::payment_request_util::GetNameLabelFromAutofillProfile; -using ::payment_request_util::GetPhoneNumberLabelFromAutofillProfile; -using ::payment_request_util::GetShippingAddressLabelFromAutofillProfile; -} // namespace - -class PaymentRequestMediatorTest : public PlatformTest { - protected: - PaymentRequestMediatorTest() - : autofill_profile_(autofill::test::GetFullProfile()), - credit_card_(autofill::test::GetCreditCard()) { - // Add testing profile and credit card to autofill::TestPersonalDataManager. - personal_data_manager_.AddTestingProfile(&autofill_profile_); - personal_data_manager_.AddTestingCreditCard(&credit_card_); - - payment_request_ = base::MakeUnique<TestPaymentRequest>( - payment_request_test_util::CreateTestWebPaymentRequest(), - &personal_data_manager_); - - TestChromeBrowserState::Builder test_cbs_builder; - test_cbs_builder.AddTestingFactory(ios::SigninManagerFactory::GetInstance(), - &ios::BuildFakeSigninManager); - chrome_browser_state_ = test_cbs_builder.Build(); - mediator_ = [[PaymentRequestMediator alloc] - initWithBrowserState:chrome_browser_state_.get() - paymentRequest:payment_request_.get()]; - } - - PaymentRequestMediator* GetPaymentRequestMediator() { return mediator_; } - - web::TestWebThreadBundle thread_bundle_; - - autofill::AutofillProfile autofill_profile_; - autofill::CreditCard credit_card_; - autofill::TestPersonalDataManager personal_data_manager_; - std::unique_ptr<TestPaymentRequest> payment_request_; - std::unique_ptr<TestChromeBrowserState> chrome_browser_state_; - PaymentRequestMediator* mediator_; -}; - -// Tests whether payment can be completed when expected. -TEST_F(PaymentRequestMediatorTest, TestCanPay) { - // Payment cannot be completed if there is no selected credit card. - EXPECT_TRUE([GetPaymentRequestMediator() canPay]); - autofill::CreditCard* selected_credit_card = - payment_request_->selected_credit_card(); - payment_request_->set_selected_credit_card(nullptr); - EXPECT_FALSE([GetPaymentRequestMediator() canPay]); - - // Restore the selected credit card. - payment_request_->set_selected_credit_card(selected_credit_card); - EXPECT_TRUE([GetPaymentRequestMediator() canPay]); - - // Payment cannot be completed if there is no selected shipping profile, - // unless no shipping information is requested. - autofill::AutofillProfile* selected_shipping_profile = - payment_request_->selected_shipping_profile(); - payment_request_->set_selected_shipping_profile(nullptr); - EXPECT_FALSE([GetPaymentRequestMediator() canPay]); - payment_request_->web_payment_request().options.request_shipping = false; - EXPECT_FALSE([GetPaymentRequestMediator() requestShipping]); - EXPECT_TRUE([GetPaymentRequestMediator() canPay]); - - // Restore the selected shipping profile and request for shipping information. - payment_request_->set_selected_shipping_profile(selected_shipping_profile); - payment_request_->web_payment_request().options.request_shipping = true; - EXPECT_TRUE([GetPaymentRequestMediator() requestShipping]); - EXPECT_TRUE([GetPaymentRequestMediator() canPay]); - - // Payment cannot be completed if there is no selected shipping option, - // unless no shipping information is requested. - web::PaymentShippingOption* selected_shipping_option = - payment_request_->selected_shipping_option(); - payment_request_->set_selected_shipping_option(nullptr); - EXPECT_FALSE([GetPaymentRequestMediator() canPay]); - payment_request_->web_payment_request().options.request_shipping = false; - EXPECT_TRUE([GetPaymentRequestMediator() canPay]); - - // Restore the selected shipping option and request for shipping information. - payment_request_->set_selected_shipping_option(selected_shipping_option); - payment_request_->web_payment_request().options.request_shipping = true; - EXPECT_TRUE([GetPaymentRequestMediator() canPay]); - - // Payment cannot be completed if there is no selected contact profile, unless - // no contact information is requested. - payment_request_->set_selected_contact_profile(nullptr); - EXPECT_FALSE([GetPaymentRequestMediator() canPay]); - payment_request_->web_payment_request().options.request_payer_name = false; - EXPECT_TRUE([GetPaymentRequestMediator() requestContactInfo]); - EXPECT_FALSE([GetPaymentRequestMediator() canPay]); - payment_request_->web_payment_request().options.request_payer_phone = false; - EXPECT_TRUE([GetPaymentRequestMediator() requestContactInfo]); - EXPECT_FALSE([GetPaymentRequestMediator() canPay]); - payment_request_->web_payment_request().options.request_payer_email = false; - EXPECT_FALSE([GetPaymentRequestMediator() requestContactInfo]); - EXPECT_TRUE([GetPaymentRequestMediator() canPay]); -} - -// Tests that the Payment Summary item is created as expected. -TEST_F(PaymentRequestMediatorTest, TestPaymentSummaryItem) { - EXPECT_TRUE([GetPaymentRequestMediator() hasPaymentItems]); - - // Payment Summary item should be of type PriceItem. - id item = [GetPaymentRequestMediator() paymentSummaryItem]; - ASSERT_TRUE([item isMemberOfClass:[PriceItem class]]); - PriceItem* payment_summary_item = base::mac::ObjCCastStrict<PriceItem>(item); - EXPECT_TRUE([payment_summary_item.item isEqualToString:@"Total"]); - EXPECT_TRUE([payment_summary_item.price isEqualToString:@"USD $1.00"]); - EXPECT_EQ(nil, payment_summary_item.notification); - EXPECT_EQ(MDCCollectionViewCellAccessoryDisclosureIndicator, - payment_summary_item.accessoryType); - - // A label should indicate if the total value was changed. - GetPaymentRequestMediator().totalValueChanged = YES; - item = [GetPaymentRequestMediator() paymentSummaryItem]; - payment_summary_item = base::mac::ObjCCastStrict<PriceItem>(item); - EXPECT_TRUE([payment_summary_item.notification - isEqualToString:l10n_util::GetNSString(IDS_PAYMENTS_UPDATED_LABEL)]); - - // The next time the data source is queried for the Payment Summary item, the - // label should disappear. - item = [GetPaymentRequestMediator() paymentSummaryItem]; - payment_summary_item = base::mac::ObjCCastStrict<PriceItem>(item); - EXPECT_EQ(nil, payment_summary_item.notification); - - // Remove the display items. - web::PaymentRequest web_payment_request = - payment_request_->web_payment_request(); - web_payment_request.details.display_items.clear(); - payment_request_->UpdatePaymentDetails(web_payment_request.details); - EXPECT_FALSE([GetPaymentRequestMediator() hasPaymentItems]); - - // No accessory view indicates there are no display items. - item = [GetPaymentRequestMediator() paymentSummaryItem]; - payment_summary_item = base::mac::ObjCCastStrict<PriceItem>(item); - EXPECT_EQ(MDCCollectionViewCellAccessoryNone, - payment_summary_item.accessoryType); -} - -// Tests that the Shipping section header item is created as expected. -TEST_F(PaymentRequestMediatorTest, TestShippingHeaderItem) { - // Shipping section header item should be of type PaymentsTextItem. - id item = [GetPaymentRequestMediator() shippingSectionHeaderItem]; - ASSERT_TRUE([item isMemberOfClass:[PaymentsTextItem class]]); - PaymentsTextItem* shipping_section_header_item = - base::mac::ObjCCastStrict<PaymentsTextItem>(item); - EXPECT_TRUE([shipping_section_header_item.text - isEqualToString:l10n_util::GetNSString( - IDS_PAYMENTS_SHIPPING_SUMMARY_LABEL)]); - EXPECT_EQ(nil, shipping_section_header_item.detailText); -} - -// Tests that the Shipping Address item is created as expected. -TEST_F(PaymentRequestMediatorTest, TestShippingAddressItem) { - // Shipping Address item should be of type AutofillProfileItem. - id item = [GetPaymentRequestMediator() shippingAddressItem]; - ASSERT_TRUE([item isMemberOfClass:[AutofillProfileItem class]]); - AutofillProfileItem* shipping_address_item = - base::mac::ObjCCastStrict<AutofillProfileItem>(item); - EXPECT_TRUE([shipping_address_item.name - isEqualToString:GetNameLabelFromAutofillProfile( - *payment_request_->selected_shipping_profile())]); - EXPECT_TRUE([shipping_address_item.address - isEqualToString:GetShippingAddressLabelFromAutofillProfile( - *payment_request_->selected_shipping_profile())]); - EXPECT_TRUE([shipping_address_item.phoneNumber - isEqualToString:GetPhoneNumberLabelFromAutofillProfile( - *payment_request_->selected_shipping_profile())]); - EXPECT_EQ(MDCCollectionViewCellAccessoryDisclosureIndicator, - shipping_address_item.accessoryType); - - // Reset the selected shipping profile. - payment_request_->set_selected_shipping_profile(nullptr); - - // When there is no selected shipping address, the Shipping Address item - // should be of type CollectionViewDetailItem. - item = [GetPaymentRequestMediator() shippingAddressItem]; - ASSERT_TRUE([item isMemberOfClass:[CollectionViewDetailItem class]]); - CollectionViewDetailItem* add_shipping_address_item = - base::mac::ObjCCastStrict<CollectionViewDetailItem>(item); - EXPECT_TRUE([add_shipping_address_item.text - isEqualToString:l10n_util::GetNSString( - IDS_PAYMENTS_SHIPPING_ADDRESS_LABEL)]); - EXPECT_EQ(nil, add_shipping_address_item.detailText); - EXPECT_EQ(MDCCollectionViewCellAccessoryDisclosureIndicator, - add_shipping_address_item.accessoryType); - - // Remove the shipping profiles. - payment_request_->ClearShippingProfiles(); - - // No accessory view indicates there are no shipping profiles to choose from. - item = [GetPaymentRequestMediator() shippingAddressItem]; - add_shipping_address_item = - base::mac::ObjCCastStrict<CollectionViewDetailItem>(item); - EXPECT_TRUE([add_shipping_address_item.detailText - isEqualToString:[l10n_util::GetNSString(IDS_ADD) - uppercaseStringWithLocale:[NSLocale currentLocale]]]); - EXPECT_EQ(MDCCollectionViewCellAccessoryNone, - add_shipping_address_item.accessoryType); -} - -// Tests that the Shipping Option item is created as expected. -TEST_F(PaymentRequestMediatorTest, TestShippingOptionItem) { - // Shipping Option item should be of type PaymentsTextItem. - id item = [GetPaymentRequestMediator() shippingOptionItem]; - ASSERT_TRUE([item isMemberOfClass:[PaymentsTextItem class]]); - PaymentsTextItem* shipping_option_item = - base::mac::ObjCCastStrict<PaymentsTextItem>(item); - EXPECT_TRUE([shipping_option_item.text isEqualToString:@"1-Day"]); - EXPECT_TRUE([shipping_option_item.detailText isEqualToString:@"$0.99"]); - EXPECT_EQ(MDCCollectionViewCellAccessoryDisclosureIndicator, - shipping_option_item.accessoryType); - - // Reset the selected shipping option. - payment_request_->set_selected_shipping_option(nullptr); - - // When there is no selected shipping option, the Shipping Option item should - // be of type CollectionViewDetailItem. - item = [GetPaymentRequestMediator() shippingOptionItem]; - ASSERT_TRUE([item isMemberOfClass:[CollectionViewDetailItem class]]); - CollectionViewDetailItem* add_shipping_option_item = - base::mac::ObjCCastStrict<CollectionViewDetailItem>(item); - EXPECT_TRUE([add_shipping_option_item.text - isEqualToString:l10n_util::GetNSString( - IDS_PAYMENTS_SHIPPING_OPTION_LABEL)]); - EXPECT_EQ(nil, add_shipping_option_item.detailText); - EXPECT_EQ(MDCCollectionViewCellAccessoryDisclosureIndicator, - add_shipping_option_item.accessoryType); -} - -// Tests that the Payment Method section header item is created as expected. -TEST_F(PaymentRequestMediatorTest, TestPaymentMethodHeaderItem) { - // Payment Method section header item should be of type PaymentsTextItem. - id item = [GetPaymentRequestMediator() paymentMethodSectionHeaderItem]; - ASSERT_TRUE([item isMemberOfClass:[PaymentsTextItem class]]); - PaymentsTextItem* payment_method_section_header_item = - base::mac::ObjCCastStrict<PaymentsTextItem>(item); - EXPECT_TRUE([payment_method_section_header_item.text - isEqualToString:l10n_util::GetNSString( - IDS_PAYMENT_REQUEST_PAYMENT_METHOD_SECTION_NAME)]); - EXPECT_EQ(nil, payment_method_section_header_item.detailText); -} - -// Tests that the Payment Method item is created as expected. -TEST_F(PaymentRequestMediatorTest, TestPaymentMethodItem) { - // Payment Method item should be of type PaymentsTextItem. - id item = [GetPaymentRequestMediator() paymentMethodItem]; - ASSERT_TRUE([item isMemberOfClass:[PaymentMethodItem class]]); - PaymentMethodItem* payment_method_item = - base::mac::ObjCCastStrict<PaymentMethodItem>(item); - EXPECT_TRUE([payment_method_item.methodID hasPrefix:@"Visa"]); - EXPECT_TRUE([payment_method_item.methodID hasSuffix:@"1111"]); - EXPECT_TRUE([payment_method_item.methodDetail isEqualToString:@"Test User"]); - EXPECT_EQ(MDCCollectionViewCellAccessoryDisclosureIndicator, - payment_method_item.accessoryType); - - // Reset the selected credit card. - payment_request_->set_selected_credit_card(nullptr); - - // When there is no selected credit card, the Payment Method item should be of - // type CollectionViewDetailItem. - item = [GetPaymentRequestMediator() paymentMethodItem]; - ASSERT_TRUE([item isMemberOfClass:[CollectionViewDetailItem class]]); - CollectionViewDetailItem* add_payment_method_item = - base::mac::ObjCCastStrict<CollectionViewDetailItem>(item); - EXPECT_TRUE([add_payment_method_item.text - isEqualToString:l10n_util::GetNSString( - IDS_PAYMENT_REQUEST_PAYMENT_METHOD_SECTION_NAME)]); - EXPECT_EQ(nil, add_payment_method_item.detailText); - EXPECT_EQ(MDCCollectionViewCellAccessoryDisclosureIndicator, - add_payment_method_item.accessoryType); - - // Remove the credit cards. - payment_request_->ClearCreditCards(); - - // No accessory view indicates there are no payment methods to choose from. - item = [GetPaymentRequestMediator() paymentMethodItem]; - add_payment_method_item = - base::mac::ObjCCastStrict<CollectionViewDetailItem>(item); - EXPECT_TRUE([add_payment_method_item.detailText - isEqualToString:[l10n_util::GetNSString(IDS_ADD) - uppercaseStringWithLocale:[NSLocale currentLocale]]]); - EXPECT_EQ(MDCCollectionViewCellAccessoryNone, - add_payment_method_item.accessoryType); -} - -// Tests that the Contact Info section header item is created as expected. -TEST_F(PaymentRequestMediatorTest, TestContactInfoHeaderItem) { - // Contact Info section header item should be of type PaymentsTextItem. - id item = [GetPaymentRequestMediator() contactInfoSectionHeaderItem]; - ASSERT_TRUE([item isMemberOfClass:[PaymentsTextItem class]]); - PaymentsTextItem* contact_info_section_header_item = - base::mac::ObjCCastStrict<PaymentsTextItem>(item); - EXPECT_TRUE([contact_info_section_header_item.text - isEqualToString:l10n_util::GetNSString( - IDS_PAYMENTS_CONTACT_DETAILS_LABEL)]); - EXPECT_EQ(nil, contact_info_section_header_item.detailText); -} - -// Tests that the Contact Info item is created as expected. -TEST_F(PaymentRequestMediatorTest, TestContactInfoItem) { - // Contact Info item should be of type AutofillProfileItem. - id item = [GetPaymentRequestMediator() contactInfoItem]; - ASSERT_TRUE([item isMemberOfClass:[AutofillProfileItem class]]); - AutofillProfileItem* contact_info_item = - base::mac::ObjCCastStrict<AutofillProfileItem>(item); - EXPECT_TRUE([contact_info_item.name - isEqualToString:GetNameLabelFromAutofillProfile( - *payment_request_->selected_contact_profile())]); - EXPECT_TRUE([contact_info_item.phoneNumber - isEqualToString:GetPhoneNumberLabelFromAutofillProfile( - *payment_request_->selected_contact_profile())]); - EXPECT_TRUE([contact_info_item.email - isEqualToString:GetEmailLabelFromAutofillProfile( - *payment_request_->selected_contact_profile())]); - EXPECT_EQ(MDCCollectionViewCellAccessoryDisclosureIndicator, - contact_info_item.accessoryType); - - // Reset the selected contact profile. - payment_request_->set_selected_contact_profile(nullptr); - - // When there is no selected contact profile, the Payment Method item should - // be of type CollectionViewDetailItem. - item = [GetPaymentRequestMediator() contactInfoItem]; - ASSERT_TRUE([item isMemberOfClass:[CollectionViewDetailItem class]]); - CollectionViewDetailItem* add_contact_info_item = - base::mac::ObjCCastStrict<CollectionViewDetailItem>(item); - EXPECT_TRUE([add_contact_info_item.text - isEqualToString:l10n_util::GetNSString( - IDS_PAYMENTS_CONTACT_DETAILS_LABEL)]); - EXPECT_EQ(nil, add_contact_info_item.detailText); - EXPECT_EQ(MDCCollectionViewCellAccessoryDisclosureIndicator, - add_contact_info_item.accessoryType); - - // Remove the contact profiles. - payment_request_->ClearContactProfiles(); - - // No accessory view indicates there are no contact profiles to choose from. - item = [GetPaymentRequestMediator() contactInfoItem]; - add_contact_info_item = - base::mac::ObjCCastStrict<CollectionViewDetailItem>(item); - EXPECT_TRUE([add_contact_info_item.detailText - isEqualToString:[l10n_util::GetNSString(IDS_ADD) - uppercaseStringWithLocale:[NSLocale currentLocale]]]); - EXPECT_EQ(MDCCollectionViewCellAccessoryNone, - add_contact_info_item.accessoryType); -} - -// Tests that the Footer item is created as expected. -TEST_F(PaymentRequestMediatorTest, TestFooterItem) { - // Make sure the user is signed out. - SigninManager* signin_manager = ios::SigninManagerFactory::GetForBrowserState( - chrome_browser_state_.get()); - if (signin_manager->IsAuthenticated()) { - signin_manager->SignOut(signin_metrics::SIGNOUT_TEST, - signin_metrics::SignoutDelete::IGNORE_METRIC); - } - - // Footer item should be of type CollectionViewFooterItem. - id item = [GetPaymentRequestMediator() footerItem]; - ASSERT_TRUE([item isMemberOfClass:[CollectionViewFooterItem class]]); - CollectionViewFooterItem* footer_item = - base::mac::ObjCCastStrict<CollectionViewFooterItem>(item); - EXPECT_TRUE([footer_item.text - isEqualToString:l10n_util::GetNSString( - IDS_PAYMENTS_CARD_AND_ADDRESS_SETTINGS_SIGNED_OUT)]); - - // Fake a signed in user. - signin_manager->SetAuthenticatedAccountInfo("12345", "username@example.com"); - - item = [GetPaymentRequestMediator() footerItem]; - footer_item = base::mac::ObjCCastStrict<CollectionViewFooterItem>(item); - EXPECT_TRUE([footer_item.text - isEqualToString:l10n_util::GetNSStringF( - IDS_PAYMENTS_CARD_AND_ADDRESS_SETTINGS_SIGNED_IN, - base::ASCIIToUTF16("username@example.com"))]); -}
diff --git a/ios/chrome/browser/ui/payments/payment_request_view_controller.h b/ios/chrome/browser/ui/payments/payment_request_view_controller.h index 9aae684..a7cf175 100644 --- a/ios/chrome/browser/ui/payments/payment_request_view_controller.h +++ b/ios/chrome/browser/ui/payments/payment_request_view_controller.h
@@ -7,13 +7,25 @@ #import <UIKit/UIKit.h> +#include "ios/chrome/browser/payments/payment_request.h" +#import "ios/chrome/browser/ui/collection_view/cells/collection_view_footer_item.h" #import "ios/chrome/browser/ui/collection_view/collection_view_controller.h" -#import "ios/chrome/browser/ui/payments/payment_request_view_controller_data_source.h" extern NSString* const kPaymentRequestCollectionViewID; +class PaymentRequest; + @class PaymentRequestViewController; +// Data source protocol for PaymentRequestViewController. +@protocol PaymentRequestViewControllerDataSource<NSObject> + +// Returns the authenticated account name, if a user is authenticated. +// Otherwise, returns nil. +- (NSString*)authenticatedAccountName; + +@end + // Delegate protocol for PaymentRequestViewController. @protocol PaymentRequestViewControllerDelegate<NSObject> @@ -54,7 +66,8 @@ // View controller responsible for presenting the details of a PaymentRequest to // the user and communicating their choices to the supplied delegate. -@interface PaymentRequestViewController : CollectionViewController +@interface PaymentRequestViewController + : CollectionViewController<CollectionViewFooterLinkDelegate> // The favicon of the page invoking the Payment Request API. @property(nonatomic, strong) UIImage* pageFavicon; @@ -74,23 +87,37 @@ // The delegate to be notified when the user confirms or cancels the request. @property(nonatomic, weak) id<PaymentRequestViewControllerDelegate> delegate; -// The data source for this view controller. +// Whether the data source should be shown (usually until the first payment +// has been completed) or not. +@property(nonatomic, assign) BOOL showPaymentDataSource; + @property(nonatomic, weak) id<PaymentRequestViewControllerDataSource> dataSource; -// Updates the payment summary item in the summary section. -- (void)updatePaymentSummaryItem; +// Updates the payment summary section UI. If |totalValueChanged| is YES, +// adds a label to the total amount item indicating that the total amount was +// updated. +- (void)updatePaymentSummaryWithTotalValueChanged:(BOOL)totalValueChanged; -// Updates the shipping section. -- (void)updateShippingSection; +// Updates the selected shipping address. +- (void)updateSelectedShippingAddressUI; -// Updates the payment method section. -- (void)updatePaymentMethodSection; +// Updates the selected shipping option. +- (void)updateSelectedShippingOptionUI; -// Updates the contact info section. -- (void)updateContactInfoSection; +// Updates the selected payment method. +- (void)updateSelectedPaymentMethodUI; -- (instancetype)init NS_DESIGNATED_INITIALIZER; +// Updates the selected contact info. +- (void)updateSelectedContactInfoUI; + +// Initializes this object with an instance of PaymentRequest which has a copy +// of web::PaymentRequest as provided by the page invoking the Payment Request +// API. This object will not take ownership of |paymentRequest|. +- (instancetype)initWithPaymentRequest:(PaymentRequest*)paymentRequest + NS_DESIGNATED_INITIALIZER; + +- (instancetype)init NS_UNAVAILABLE; - (instancetype)initWithStyle:(CollectionViewControllerStyle)style NS_UNAVAILABLE;
diff --git a/ios/chrome/browser/ui/payments/payment_request_view_controller.mm b/ios/chrome/browser/ui/payments/payment_request_view_controller.mm index 3bccff4..83d3a09 100644 --- a/ios/chrome/browser/ui/payments/payment_request_view_controller.mm +++ b/ios/chrome/browser/ui/payments/payment_request_view_controller.mm
@@ -6,34 +6,67 @@ #include "base/mac/foundation_util.h" +#include "base/strings/sys_string_conversions.h" +#include "base/strings/utf_string_conversions.h" +#include "components/autofill/core/browser/autofill_data_util.h" +#include "components/autofill/core/browser/autofill_profile.h" +#include "components/autofill/core/browser/credit_card.h" +#include "components/autofill/core/browser/field_types.h" +#include "components/autofill/core/browser/personal_data_manager.h" +#include "components/payments/core/currency_formatter.h" +#include "components/payments/core/strings_util.h" #include "components/strings/grit/components_strings.h" +#include "ios/chrome/browser/payments/payment_request.h" +#import "ios/chrome/browser/payments/payment_request_util.h" #import "ios/chrome/browser/ui/autofill/cells/status_item.h" #import "ios/chrome/browser/ui/collection_view/cells/MDCCollectionViewCell+Chrome.h" #import "ios/chrome/browser/ui/collection_view/cells/collection_view_detail_item.h" #import "ios/chrome/browser/ui/collection_view/cells/collection_view_footer_item.h" -#import "ios/chrome/browser/ui/collection_view/cells/collection_view_item+collection_view_controller.h" #import "ios/chrome/browser/ui/collection_view/cells/collection_view_item.h" #import "ios/chrome/browser/ui/collection_view/collection_view_model.h" #import "ios/chrome/browser/ui/colors/MDCPalette+CrAdditions.h" +#import "ios/chrome/browser/ui/payments/cells/autofill_profile_item.h" #import "ios/chrome/browser/ui/payments/cells/page_info_item.h" +#import "ios/chrome/browser/ui/payments/cells/payment_method_item.h" +#import "ios/chrome/browser/ui/payments/cells/payments_text_item.h" #import "ios/chrome/browser/ui/payments/cells/price_item.h" #import "ios/chrome/browser/ui/payments/payment_request_view_controller_actions.h" #include "ios/chrome/browser/ui/rtl_geometry.h" #include "ios/chrome/browser/ui/uikit_ui_util.h" #include "ios/chrome/grit/ios_strings.h" #import "ios/third_party/material_components_ios/src/components/Buttons/src/MaterialButtons.h" +#import "ios/third_party/material_components_ios/src/components/CollectionCells/src/MaterialCollectionCells.h" #import "ios/third_party/material_components_ios/src/components/Typography/src/MaterialTypography.h" +#include "ios/web/public/payments/payment_request.h" #include "ui/base/l10n/l10n_util.h" +#include "ui/base/resource/resource_bundle.h" #if !defined(__has_feature) || !__has_feature(objc_arc) #error "This file requires ARC support." #endif +namespace { +using ::payment_request_util::GetNameLabelFromAutofillProfile; +using ::payment_request_util::GetShippingAddressLabelFromAutofillProfile; +using ::payment_request_util::GetPhoneNumberLabelFromAutofillProfile; +using ::payment_request_util::GetEmailLabelFromAutofillProfile; +using ::payment_request_util::GetShippingSectionTitle; +using ::payments::GetShippingOptionSectionString; +using ::payments::GetShippingAddressSectionString; + +// String used as the "URL" to take the user to the settings page for card and +// address options. Needs to be URL-like; otherwise, the link will not appear +// as a link in the UI (see setLabelLinkURL: in CollectionViewFooterCell). +const char kSettingsURL[] = "settings://card-and-address"; + +const CGFloat kFooterCellHorizontalPadding = 16; + +} // namespace + NSString* const kPaymentRequestCollectionViewID = @"kPaymentRequestCollectionViewID"; namespace { -const CGFloat kFooterCellHorizontalPadding = 16; const CGFloat kButtonEdgeInset = 9; const CGFloat kSeparatorEdgeInset = 14; @@ -52,21 +85,35 @@ ItemTypeSummaryTotal, ItemTypeShippingTitle, ItemTypeShippingAddress, + ItemTypeAddShippingAddress, ItemTypeShippingOption, - ItemTypePaymentHeader, + ItemTypeSelectShippingOption, + ItemTypePaymentTitle, ItemTypePaymentMethod, - ItemTypeContactInfoHeader, + ItemTypeAddPaymentMethod, + ItemTypeContactInfoTitle, ItemTypeContactInfo, + ItemTypeAddContactInfo, ItemTypeFooterText, }; } // namespace @interface PaymentRequestViewController ()< - CollectionViewFooterLinkDelegate, PaymentRequestViewControllerActions> { UIBarButtonItem* _cancelButton; MDCButton* _payButton; + + // The PaymentRequest object having a copy of web::PaymentRequest as provided + // by the page invoking the Payment Request API. This is a weak pointer and + // should outlive this class. + PaymentRequest* _paymentRequest; + + __weak PriceItem* _paymentSummaryItem; + __weak AutofillProfileItem* _selectedShippingAddressItem; + __weak PaymentsTextItem* _selectedShippingOptionItem; + __weak PaymentMethodItem* _selectedPaymentMethodItem; + __weak AutofillProfileItem* _selectedContactInfoItem; } @end @@ -79,9 +126,11 @@ @synthesize connectionSecure = _connectionSecure; @synthesize pending = _pending; @synthesize delegate = _delegate; +@synthesize showPaymentDataSource = _showPaymentDataSource; @synthesize dataSource = _dataSource; -- (instancetype)init { +- (instancetype)initWithPaymentRequest:(PaymentRequest*)paymentRequest { + DCHECK(paymentRequest); if ((self = [super initWithStyle:CollectionViewControllerStyleAppBar])) { [self setTitle:l10n_util::GetNSString(IDS_PAYMENTS_TITLE)]; @@ -109,6 +158,7 @@ action:@selector(onConfirm) forControlEvents:UIControlEventTouchUpInside]; [_payButton sizeToFit]; + [_payButton setEnabled:(paymentRequest->selected_credit_card() != nil)]; [_payButton setAutoresizingMask:UIViewAutoresizingFlexibleTrailingMargin() | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin]; @@ -131,6 +181,11 @@ UIBarButtonItem* payButtonItem = [[UIBarButtonItem alloc] initWithCustomView:buttonView]; [self navigationItem].rightBarButtonItem = payButtonItem; + + _paymentRequest = paymentRequest; + + // By default, data source is shown. + _showPaymentDataSource = TRUE; } return self; } @@ -143,13 +198,6 @@ [_delegate paymentRequestViewControllerDidConfirm:self]; } -#pragma mark - Setters - -- (void)setDataSource:(id<PaymentRequestViewControllerDataSource>)dataSource { - _dataSource = dataSource; - [_payButton setEnabled:[_dataSource canPay]]; -} - #pragma mark - CollectionViewController methods - (void)loadModel { @@ -177,38 +225,170 @@ return; } - [self addPaymentSummaryItem]; + PriceItem* paymentSummaryItem = + [[PriceItem alloc] initWithType:ItemTypeSummaryTotal]; + _paymentSummaryItem = paymentSummaryItem; + [self fillPaymentSummaryItem:paymentSummaryItem + withPaymentItem:_paymentRequest->payment_details().total + withTotalValueChanged:NO]; + if (!_paymentRequest->payment_details().display_items.empty()) { + paymentSummaryItem.accessoryType = + MDCCollectionViewCellAccessoryDisclosureIndicator; + paymentSummaryItem.accessibilityTraits |= UIAccessibilityTraitButton; + } + [model addItem:paymentSummaryItem + toSectionWithIdentifier:SectionIdentifierSummary]; // Shipping section. - if ([_dataSource requestShipping]) { - [model addSectionWithIdentifier:SectionIdentifierShipping]; + [model addSectionWithIdentifier:SectionIdentifierShipping]; - CollectionViewItem* shippingSectionHeaderItem = - [_dataSource shippingSectionHeaderItem]; - [shippingSectionHeaderItem setType:ItemTypeShippingTitle]; - [model setHeader:shippingSectionHeaderItem - forSectionWithIdentifier:SectionIdentifierShipping]; + PaymentsTextItem* shippingTitle = + [[PaymentsTextItem alloc] initWithType:ItemTypeShippingTitle]; + shippingTitle.text = + GetShippingSectionTitle(_paymentRequest->shipping_type()); + [model setHeader:shippingTitle + forSectionWithIdentifier:SectionIdentifierShipping]; - [self populateShippingSection]; + CollectionViewItem* shippingAddressItem = nil; + if (_paymentRequest->selected_shipping_profile()) { + AutofillProfileItem* selectedShippingAddressItem = + [[AutofillProfileItem alloc] initWithType:ItemTypeShippingAddress]; + shippingAddressItem = selectedShippingAddressItem; + _selectedShippingAddressItem = selectedShippingAddressItem; + [self fillShippingAddressItem:selectedShippingAddressItem + withAutofillProfile:_paymentRequest->selected_shipping_profile()]; + selectedShippingAddressItem.accessoryType = + MDCCollectionViewCellAccessoryDisclosureIndicator; + selectedShippingAddressItem.accessibilityTraits |= + UIAccessibilityTraitButton; + } else { + CollectionViewDetailItem* addAddressItem = [[CollectionViewDetailItem alloc] + initWithType:ItemTypeAddShippingAddress]; + shippingAddressItem = addAddressItem; + addAddressItem.text = SysUTF16ToNSString( + GetShippingAddressSectionString(_paymentRequest->shipping_type())); + addAddressItem.detailText = [l10n_util::GetNSString(IDS_ADD) + uppercaseStringWithLocale:[NSLocale currentLocale]]; + addAddressItem.accessibilityTraits |= UIAccessibilityTraitButton; } + [model addItem:shippingAddressItem + toSectionWithIdentifier:SectionIdentifierShipping]; + + CollectionViewItem* shippingOptionItem = nil; + if (_paymentRequest->selected_shipping_option()) { + PaymentsTextItem* selectedShippingOptionItem = + [[PaymentsTextItem alloc] initWithType:ItemTypeShippingOption]; + shippingOptionItem = selectedShippingOptionItem; + + _selectedShippingOptionItem = selectedShippingOptionItem; + [self fillShippingOptionItem:selectedShippingOptionItem + withOption:_paymentRequest->selected_shipping_option()]; + selectedShippingOptionItem.accessoryType = + MDCCollectionViewCellAccessoryDisclosureIndicator; + selectedShippingOptionItem.accessibilityTraits |= + UIAccessibilityTraitButton; + } else { + CollectionViewDetailItem* selectShippingOptionItem = + [[CollectionViewDetailItem alloc] + initWithType:ItemTypeSelectShippingOption]; + shippingOptionItem = selectShippingOptionItem; + selectShippingOptionItem.text = base::SysUTF16ToNSString( + GetShippingOptionSectionString(_paymentRequest->shipping_type())); + selectShippingOptionItem.accessoryType = + MDCCollectionViewCellAccessoryDisclosureIndicator; + selectShippingOptionItem.accessibilityTraits |= UIAccessibilityTraitButton; + } + [model addItem:shippingOptionItem + toSectionWithIdentifier:SectionIdentifierShipping]; // Payment method section. [model addSectionWithIdentifier:SectionIdentifierPayment]; - [self populatePaymentMethodSection]; + + CollectionViewItem* paymentMethodItem = nil; + if (_paymentRequest->selected_credit_card()) { + PaymentsTextItem* paymentTitle = + [[PaymentsTextItem alloc] initWithType:ItemTypePaymentTitle]; + paymentTitle.text = + l10n_util::GetNSString(IDS_PAYMENT_REQUEST_PAYMENT_METHOD_SECTION_NAME); + [model setHeader:paymentTitle + forSectionWithIdentifier:SectionIdentifierPayment]; + + PaymentMethodItem* selectedPaymentMethodItem = + [[PaymentMethodItem alloc] initWithType:ItemTypePaymentMethod]; + paymentMethodItem = selectedPaymentMethodItem; + _selectedPaymentMethodItem = selectedPaymentMethodItem; + [self fillPaymentMethodItem:selectedPaymentMethodItem + withCreditCard:_paymentRequest->selected_credit_card()]; + selectedPaymentMethodItem.accessoryType = + MDCCollectionViewCellAccessoryDisclosureIndicator; + selectedPaymentMethodItem.accessibilityTraits |= UIAccessibilityTraitButton; + } else { + CollectionViewDetailItem* addPaymentMethodItem = [ + [CollectionViewDetailItem alloc] initWithType:ItemTypeAddPaymentMethod]; + paymentMethodItem = addPaymentMethodItem; + addPaymentMethodItem.text = + l10n_util::GetNSString(IDS_PAYMENT_REQUEST_PAYMENT_METHOD_SECTION_NAME); + addPaymentMethodItem.detailText = [l10n_util::GetNSString(IDS_ADD) + uppercaseStringWithLocale:[NSLocale currentLocale]]; + addPaymentMethodItem.accessibilityTraits |= UIAccessibilityTraitButton; + } + [model addItem:paymentMethodItem + toSectionWithIdentifier:SectionIdentifierPayment]; // Contact Info section. - if ([_dataSource requestContactInfo]) { - [model addSectionWithIdentifier:SectionIdentifierContactInfo]; - [self populateContactInfoSection]; + [model addSectionWithIdentifier:SectionIdentifierContactInfo]; + + CollectionViewItem* contactInfoItem = nil; + if (_paymentRequest->selected_contact_profile()) { + PaymentsTextItem* contactInfoTitle = + [[PaymentsTextItem alloc] initWithType:ItemTypeContactInfoTitle]; + contactInfoTitle.text = + l10n_util::GetNSString(IDS_PAYMENTS_CONTACT_DETAILS_LABEL); + [model setHeader:contactInfoTitle + forSectionWithIdentifier:SectionIdentifierContactInfo]; + + AutofillProfileItem* selectedContactInfoItem = + [[AutofillProfileItem alloc] initWithType:ItemTypeContactInfo]; + contactInfoItem = selectedContactInfoItem; + _selectedContactInfoItem = selectedContactInfoItem; + [self fillContactInfoItem:selectedContactInfoItem + withAutofillProfile:_paymentRequest->selected_contact_profile()]; + selectedContactInfoItem.accessoryType = + MDCCollectionViewCellAccessoryDisclosureIndicator; + + } else { + CollectionViewDetailItem* addContactInfoItem = + [[CollectionViewDetailItem alloc] initWithType:ItemTypeAddContactInfo]; + contactInfoItem = addContactInfoItem; + addContactInfoItem.text = + l10n_util::GetNSString(IDS_PAYMENTS_CONTACT_DETAILS_LABEL); + addContactInfoItem.detailText = [l10n_util::GetNSString(IDS_ADD) + uppercaseStringWithLocale:[NSLocale currentLocale]]; + addContactInfoItem.accessibilityTraits |= UIAccessibilityTraitButton; } + [model addItem:contactInfoItem + toSectionWithIdentifier:SectionIdentifierContactInfo]; // Footer Text section. [model addSectionWithIdentifier:SectionIdentifierFooter]; - - CollectionViewFooterItem* footerItem = [_dataSource footerItem]; - [footerItem setType:ItemTypeFooterText]; - footerItem.linkDelegate = self; - [model addItem:footerItem toSectionWithIdentifier:SectionIdentifierFooter]; + CollectionViewFooterItem* footer = + [[CollectionViewFooterItem alloc] initWithType:ItemTypeFooterText]; + if (!_showPaymentDataSource) { + footer.text = + l10n_util::GetNSString(IDS_PAYMENTS_CARD_AND_ADDRESS_SETTINGS); + } else if ([[_dataSource authenticatedAccountName] length]) { + const base::string16 accountName = + base::SysNSStringToUTF16([_dataSource authenticatedAccountName]); + const std::string formattedString = l10n_util::GetStringFUTF8( + IDS_PAYMENTS_CARD_AND_ADDRESS_SETTINGS_SIGNED_IN, accountName); + footer.text = base::SysUTF8ToNSString(formattedString); + } else { + footer.text = l10n_util::GetNSString( + IDS_PAYMENTS_CARD_AND_ADDRESS_SETTINGS_SIGNED_OUT); + } + footer.linkURL = GURL(kSettingsURL); + footer.linkDelegate = self; + [model addItem:footer toSectionWithIdentifier:SectionIdentifierFooter]; } - (void)viewDidLoad { @@ -221,88 +401,110 @@ UIEdgeInsetsMake(0, kSeparatorEdgeInset, 0, kSeparatorEdgeInset); } -- (void)updatePaymentSummaryItem { - CollectionViewModel* model = self.collectionViewModel; - - [model removeItemWithType:ItemTypeSummaryTotal - fromSectionWithIdentifier:SectionIdentifierSummary]; - - [self addPaymentSummaryItem]; - - // Reload the item. +- (void)updatePaymentSummaryWithTotalValueChanged:(BOOL)totalValueChanged { + [self fillPaymentSummaryItem:_paymentSummaryItem + withPaymentItem:_paymentRequest->payment_details().total + withTotalValueChanged:totalValueChanged]; NSIndexPath* indexPath = - [model indexPathForItemType:ItemTypeSummaryTotal - sectionIdentifier:SectionIdentifierSummary]; + [self.collectionViewModel indexPathForItem:_paymentSummaryItem]; [self.collectionView reloadItemsAtIndexPaths:@[ indexPath ]]; } -- (void)updateShippingSection { - CollectionViewModel* model = self.collectionViewModel; - - [model removeItemWithType:ItemTypeShippingAddress - fromSectionWithIdentifier:SectionIdentifierShipping]; - - if ([model hasItemForItemType:ItemTypeShippingOption - sectionIdentifier:SectionIdentifierShipping]) { - [model removeItemWithType:ItemTypeShippingOption - fromSectionWithIdentifier:SectionIdentifierShipping]; - } - - [self populateShippingSection]; - - // Reload the section. - NSInteger sectionIndex = - [model sectionForSectionIdentifier:SectionIdentifierShipping]; - [self.collectionView - reloadSections:[NSIndexSet indexSetWithIndex:sectionIndex]]; - - // Update the pay button. - [_payButton setEnabled:[_dataSource canPay]]; +- (void)updateSelectedShippingAddressUI { + [self fillShippingAddressItem:_selectedShippingAddressItem + withAutofillProfile:_paymentRequest->selected_shipping_profile()]; + NSIndexPath* indexPath = + [self.collectionViewModel indexPathForItem:_selectedShippingAddressItem]; + [self.collectionView reloadItemsAtIndexPaths:@[ indexPath ]]; } -- (void)updatePaymentMethodSection { - CollectionViewModel* model = self.collectionViewModel; - - [model removeItemWithType:ItemTypePaymentMethod - fromSectionWithIdentifier:SectionIdentifierPayment]; - - [self populatePaymentMethodSection]; - - // Reload the section. - NSInteger sectionIndex = - [model sectionForSectionIdentifier:SectionIdentifierPayment]; - [self.collectionView - reloadSections:[NSIndexSet indexSetWithIndex:sectionIndex]]; - - // Update the pay button. - [_payButton setEnabled:[_dataSource canPay]]; +- (void)updateSelectedShippingOptionUI { + [self fillShippingOptionItem:_selectedShippingOptionItem + withOption:_paymentRequest->selected_shipping_option()]; + NSIndexPath* indexPath = + [self.collectionViewModel indexPathForItem:_selectedShippingOptionItem]; + [self.collectionView reloadItemsAtIndexPaths:@[ indexPath ]]; } -- (void)updateContactInfoSection { - CollectionViewModel* model = self.collectionViewModel; +- (void)updateSelectedPaymentMethodUI { + [self fillPaymentMethodItem:_selectedPaymentMethodItem + withCreditCard:_paymentRequest->selected_credit_card()]; + NSIndexPath* indexPath = + [self.collectionViewModel indexPathForItem:_selectedPaymentMethodItem]; + [self.collectionView reloadItemsAtIndexPaths:@[ indexPath ]]; +} - [model removeItemWithType:ItemTypeContactInfo - fromSectionWithIdentifier:SectionIdentifierContactInfo]; +- (void)updateSelectedContactInfoUI { + [self fillContactInfoItem:_selectedContactInfoItem + withAutofillProfile:_paymentRequest->selected_contact_profile()]; + NSIndexPath* indexPath = + [self.collectionViewModel indexPathForItem:_selectedContactInfoItem]; + [self.collectionView reloadItemsAtIndexPaths:@[ indexPath ]]; +} - [self populateContactInfoSection]; +#pragma mark - Helper methods - // Reload the section. - NSInteger sectionIndex = - [model sectionForSectionIdentifier:SectionIdentifierContactInfo]; - [self.collectionView - reloadSections:[NSIndexSet indexSetWithIndex:sectionIndex]]; +- (void)fillPaymentSummaryItem:(PriceItem*)item + withPaymentItem:(web::PaymentItem)paymentItem + withTotalValueChanged:(BOOL)totalValueChanged { + item.item = + base::SysUTF16ToNSString(_paymentRequest->payment_details().total.label); + payments::CurrencyFormatter* currencyFormatter = + _paymentRequest->GetOrCreateCurrencyFormatter(); + item.price = SysUTF16ToNSString(l10n_util::GetStringFUTF16( + IDS_PAYMENT_REQUEST_ORDER_SUMMARY_SHEET_TOTAL_FORMAT, + base::UTF8ToUTF16(currencyFormatter->formatted_currency_code()), + currencyFormatter->Format(base::UTF16ToASCII(paymentItem.amount.value)))); + item.notification = totalValueChanged + ? l10n_util::GetNSString(IDS_PAYMENTS_UPDATED_LABEL) + : nil; +} - // Update the pay button. - [_payButton setEnabled:[_dataSource canPay]]; +- (void)fillShippingAddressItem:(AutofillProfileItem*)item + withAutofillProfile:(autofill::AutofillProfile*)profile { + DCHECK(profile); + item.name = GetNameLabelFromAutofillProfile(*profile); + item.address = GetShippingAddressLabelFromAutofillProfile(*profile); + item.phoneNumber = GetPhoneNumberLabelFromAutofillProfile(*profile); +} + +- (void)fillShippingOptionItem:(PaymentsTextItem*)item + withOption:(web::PaymentShippingOption*)option { + item.text = base::SysUTF16ToNSString(option->label); + payments::CurrencyFormatter* currencyFormatter = + _paymentRequest->GetOrCreateCurrencyFormatter(); + item.detailText = SysUTF16ToNSString( + currencyFormatter->Format(base::UTF16ToASCII(option->amount.value))); +} + +- (void)fillPaymentMethodItem:(PaymentMethodItem*)item + withCreditCard:(autofill::CreditCard*)creditCard { + item.methodID = + base::SysUTF16ToNSString(creditCard->NetworkAndLastFourDigits()); + item.methodDetail = base::SysUTF16ToNSString( + creditCard->GetRawInfo(autofill::CREDIT_CARD_NAME_FULL)); + int issuerNetworkIconID = + autofill::data_util::GetPaymentRequestData(creditCard->network()) + .icon_resource_id; + item.methodTypeIcon = NativeImage(issuerNetworkIconID); +} + +- (void)fillContactInfoItem:(AutofillProfileItem*)item + withAutofillProfile:(autofill::AutofillProfile*)profile { + DCHECK(profile); + item.name = GetNameLabelFromAutofillProfile(*profile); + item.phoneNumber = GetPhoneNumberLabelFromAutofillProfile(*profile); + item.email = GetEmailLabelFromAutofillProfile(*profile); } #pragma mark - CollectionViewFooterLinkDelegate - (void)cell:(CollectionViewFooterCell*)cell didTapLinkURL:(GURL)url { + DCHECK_EQ(url, GURL(kSettingsURL)) << "Unknown URL tapped"; [_delegate paymentRequestViewControllerDidSelectSettings:self]; } -#pragma mark - UICollectionViewDataSource +#pragma mark UICollectionViewDataSource - (UICollectionViewCell*)collectionView:(UICollectionView*)collectionView cellForItemAtIndexPath:(nonnull NSIndexPath*)indexPath { @@ -312,17 +514,12 @@ NSInteger itemType = [self.collectionViewModel itemTypeForIndexPath:indexPath]; switch (itemType) { - case ItemTypeShippingAddress: - case ItemTypePaymentMethod: - case ItemTypeShippingOption: - case ItemTypeContactInfo: { - if ([cell isKindOfClass:[CollectionViewDetailCell class]]) { - CollectionViewDetailCell* detailCell = - base::mac::ObjCCastStrict<CollectionViewDetailCell>(cell); - detailCell.detailTextLabel.font = [MDCTypography body2Font]; - detailCell.detailTextLabel.textColor = - [[MDCPalette cr_bluePalette] tint700]; - } + case ItemTypeAddShippingAddress: { + CollectionViewDetailCell* detailCell = + base::mac::ObjCCastStrict<CollectionViewDetailCell>(cell); + detailCell.detailTextLabel.font = [MDCTypography body2Font]; + detailCell.detailTextLabel.textColor = + [[MDCPalette cr_bluePalette] tint700]; break; } case ItemTypeFooterText: { @@ -340,7 +537,7 @@ return cell; } -#pragma mark - UICollectionViewDelegate +#pragma mark UICollectionViewDelegate - (void)collectionView:(UICollectionView*)collectionView didSelectItemAtIndexPath:(NSIndexPath*)indexPath { @@ -350,19 +547,24 @@ [self.collectionViewModel itemTypeForIndexPath:indexPath]; switch (itemType) { case ItemTypeSummaryTotal: + if (!_paymentRequest->payment_details().display_items.empty()) [_delegate paymentRequestViewControllerDidSelectPaymentSummaryItem:self]; break; case ItemTypeShippingAddress: + case ItemTypeAddShippingAddress: [_delegate paymentRequestViewControllerDidSelectShippingAddressItem:self]; break; case ItemTypeShippingOption: + case ItemTypeSelectShippingOption: [_delegate paymentRequestViewControllerDidSelectShippingOptionItem:self]; break; case ItemTypePaymentMethod: + case ItemTypeAddPaymentMethod: [_delegate paymentRequestViewControllerDidSelectPaymentMethodItem:self]; break; case ItemTypeContactInfo: + case ItemTypeAddContactInfo: [_delegate paymentRequestViewControllerDidSelectContactInfoItem:self]; break; case ItemTypeFooterText: @@ -375,7 +577,7 @@ } } -#pragma mark - MDCCollectionViewStylingDelegate +#pragma mark MDCCollectionViewStylingDelegate - (CGFloat)collectionView:(UICollectionView*)collectionView cellHeightAtIndexPath:(NSIndexPath*)indexPath { @@ -384,15 +586,23 @@ switch (item.type) { case ItemTypeSpinner: case ItemTypeShippingAddress: - case ItemTypeShippingOption: case ItemTypePaymentMethod: case ItemTypeContactInfo: case ItemTypeFooterText: return [MDCCollectionViewCell cr_preferredHeightForWidth:CGRectGetWidth(collectionView.bounds) forItem:item]; + case ItemTypeShippingOption: + return MDCCellDefaultTwoLineHeight; case ItemTypeSummaryPageInfo: case ItemTypeSummaryTotal: + case ItemTypeShippingTitle: + case ItemTypeAddShippingAddress: + case ItemTypeSelectShippingOption: + case ItemTypePaymentTitle: + case ItemTypeAddPaymentMethod: + case ItemTypeContactInfoTitle: + case ItemTypeAddContactInfo: return MDCCellDefaultOneLineHeight; default: NOTREACHED(); @@ -406,7 +616,8 @@ // If there are no payment items to display, there is no effect from touching // the total so there should not be an ink ripple. The footer should also not // have a ripple. - if ((type == ItemTypeSummaryTotal && ![_dataSource hasPaymentItems]) || + if ((type == ItemTypeSummaryTotal && + _paymentRequest->payment_details().display_items.empty()) || (type == ItemTypeFooterText)) { return YES; } else { @@ -422,69 +633,4 @@ return sectionIdentifier == SectionIdentifierFooter ? YES : NO; } -#pragma mark - Helper methods - -- (void)addPaymentSummaryItem { - CollectionViewItem* item = [_dataSource paymentSummaryItem]; - [item setType:ItemTypeSummaryTotal]; - if ([_dataSource hasPaymentItems]) - item.accessibilityTraits |= UIAccessibilityTraitButton; - [self.collectionViewModel addItem:item - toSectionWithIdentifier:SectionIdentifierSummary]; -} - -- (void)populateShippingSection { - CollectionViewModel* model = self.collectionViewModel; - - CollectionViewItem* shippingAddressItem = [_dataSource shippingAddressItem]; - [shippingAddressItem setType:ItemTypeShippingAddress]; - shippingAddressItem.accessibilityTraits |= UIAccessibilityTraitButton; - [model addItem:shippingAddressItem - toSectionWithIdentifier:SectionIdentifierShipping]; - - if ([_dataSource canShip]) { - CollectionViewItem* shippingOptionItem = [_dataSource shippingOptionItem]; - [shippingOptionItem setType:ItemTypeShippingOption]; - shippingOptionItem.accessibilityTraits |= UIAccessibilityTraitButton; - [model addItem:shippingOptionItem - toSectionWithIdentifier:SectionIdentifierShipping]; - } -} - -- (void)populatePaymentMethodSection { - CollectionViewModel* model = self.collectionViewModel; - - CollectionViewItem* paymentMethodSectionHeaderItem = - [_dataSource paymentMethodSectionHeaderItem]; - if (paymentMethodSectionHeaderItem) { - [paymentMethodSectionHeaderItem setType:ItemTypePaymentHeader]; - [model setHeader:paymentMethodSectionHeaderItem - forSectionWithIdentifier:SectionIdentifierPayment]; - } - - CollectionViewItem* paymentMethodItem = [_dataSource paymentMethodItem]; - [paymentMethodItem setType:ItemTypePaymentMethod]; - paymentMethodItem.accessibilityTraits |= UIAccessibilityTraitButton; - [model addItem:paymentMethodItem - toSectionWithIdentifier:SectionIdentifierPayment]; -} - -- (void)populateContactInfoSection { - CollectionViewModel* model = self.collectionViewModel; - - CollectionViewItem* contactInfoSectionHeaderItem = - [_dataSource contactInfoSectionHeaderItem]; - if (contactInfoSectionHeaderItem) { - [contactInfoSectionHeaderItem setType:ItemTypeContactInfoHeader]; - [model setHeader:contactInfoSectionHeaderItem - forSectionWithIdentifier:SectionIdentifierContactInfo]; - } - - CollectionViewItem* contactInfoItem = [_dataSource contactInfoItem]; - [contactInfoItem setType:ItemTypeContactInfo]; - contactInfoItem.accessibilityTraits |= UIAccessibilityTraitButton; - [model addItem:contactInfoItem - toSectionWithIdentifier:SectionIdentifierContactInfo]; -} - @end
diff --git a/ios/chrome/browser/ui/payments/payment_request_view_controller_data_source.h b/ios/chrome/browser/ui/payments/payment_request_view_controller_data_source.h deleted file mode 100644 index 1f130b3..0000000 --- a/ios/chrome/browser/ui/payments/payment_request_view_controller_data_source.h +++ /dev/null
@@ -1,64 +0,0 @@ -// Copyright 2017 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef IOS_CHROME_BROWSER_UI_PAYMENTS_PAYMENT_REQUEST_VIEW_CONTROLLER_DATA_SOURCE_H_ -#define IOS_CHROME_BROWSER_UI_PAYMENTS_PAYMENT_REQUEST_VIEW_CONTROLLER_DATA_SOURCE_H_ - -#import <Foundation/Foundation.h> - -@class CollectionViewFooterItem; -@class CollectionViewItem; - -// Data source protocol for PaymentRequestViewController. -@protocol PaymentRequestViewControllerDataSource - -// Returns whether the payment can be made and therefore the pay button should -// be enabled. -- (BOOL)canPay; - -// Returns whether shipment can be done and therefore the shipping options -// should be presented. -- (BOOL)canShip; - -// Returns whether the total price is itemized. -- (BOOL)hasPaymentItems; - -// Returns whether shipping is requested and therefore the Shipping section -// should be presented. -- (BOOL)requestShipping; - -// Returns whether contact information is requested and therefore the Contact -// Info section should be presented. -- (BOOL)requestContactInfo; - -// Returns the Payment Summary item displayed in the Summary section. -- (CollectionViewItem*)paymentSummaryItem; - -// Returns the header item for the Shipping section. -- (CollectionViewItem*)shippingSectionHeaderItem; - -// Returns the Shipping Address item displayed in the Shipping section. -- (CollectionViewItem*)shippingAddressItem; - -// Returns the Shipping Option item displayed in the Shipping section. -- (CollectionViewItem*)shippingOptionItem; - -// Returns the header item for the Payment Method section. -- (CollectionViewItem*)paymentMethodSectionHeaderItem; - -// Returns the item displayed in the Payment Method section. -- (CollectionViewItem*)paymentMethodItem; - -// Returns the header item for the Contact Info section. -- (CollectionViewItem*)contactInfoSectionHeaderItem; - -// Returns the item displayed in the Contact Info section. -- (CollectionViewItem*)contactInfoItem; - -// Returns the item displayed at the bottom of the view. -- (CollectionViewFooterItem*)footerItem; - -@end - -#endif // IOS_CHROME_BROWSER_UI_PAYMENTS_PAYMENT_REQUEST_VIEW_CONTROLLER_DATA_SOURCE_H_
diff --git a/ios/chrome/browser/ui/payments/payment_request_view_controller_unittest.mm b/ios/chrome/browser/ui/payments/payment_request_view_controller_unittest.mm index ad35d58..f42b497a 100644 --- a/ios/chrome/browser/ui/payments/payment_request_view_controller_unittest.mm +++ b/ios/chrome/browser/ui/payments/payment_request_view_controller_unittest.mm
@@ -4,8 +4,6 @@ #import "ios/chrome/browser/ui/payments/payment_request_view_controller.h" -#import <Foundation/Foundation.h> - #include "base/mac/foundation_util.h" #include "base/memory/ptr_util.h" #include "base/strings/utf_string_conversions.h" @@ -14,18 +12,16 @@ #include "components/autofill/core/browser/credit_card.h" #include "components/autofill/core/browser/test_personal_data_manager.h" #include "components/strings/grit/components_strings.h" +#include "ios/chrome/browser/payments/payment_request.h" #include "ios/chrome/browser/payments/payment_request_test_util.h" -#include "ios/chrome/browser/payments/test_payment_request.h" #import "ios/chrome/browser/ui/autofill/cells/status_item.h" #import "ios/chrome/browser/ui/collection_view/cells/collection_view_detail_item.h" -#import "ios/chrome/browser/ui/collection_view/cells/collection_view_footer_item.h" #import "ios/chrome/browser/ui/collection_view/collection_view_controller_test.h" #import "ios/chrome/browser/ui/payments/cells/autofill_profile_item.h" #import "ios/chrome/browser/ui/payments/cells/page_info_item.h" #import "ios/chrome/browser/ui/payments/cells/payment_method_item.h" #import "ios/chrome/browser/ui/payments/cells/payments_text_item.h" #import "ios/chrome/browser/ui/payments/cells/price_item.h" -#import "ios/chrome/browser/ui/payments/payment_request_view_controller_data_source.h" #include "ios/chrome/grit/ios_strings.h" #include "ios/web/public/payments/payment_request.h" #include "testing/gtest/include/gtest/gtest.h" @@ -35,107 +31,6 @@ #error "This file requires ARC support." #endif -@interface TestPaymentRequestMediator - : NSObject<PaymentRequestViewControllerDataSource> - -@end - -@implementation TestPaymentRequestMediator - -- (BOOL)canPay { - return YES; -} - -- (BOOL)canShip { - return YES; -} - -- (BOOL)hasPaymentItems { - return YES; -} - -- (BOOL)requestShipping { - return YES; -} - -- (BOOL)requestContactInfo { - return YES; -} - -- (CollectionViewItem*)paymentSummaryItem { - return [[PriceItem alloc] init]; -} - -- (CollectionViewItem*)shippingSectionHeaderItem { - return [[PaymentsTextItem alloc] init]; -} - -- (CollectionViewItem*)shippingAddressItem { - return [[AutofillProfileItem alloc] init]; -} - -- (CollectionViewItem*)shippingOptionItem { - return [[PaymentsTextItem alloc] init]; -} - -- (CollectionViewItem*)paymentMethodSectionHeaderItem { - return [[PaymentsTextItem alloc] init]; -} - -- (CollectionViewItem*)paymentMethodItem { - return [[PaymentMethodItem alloc] init]; -} - -- (CollectionViewItem*)contactInfoSectionHeaderItem { - return [[PaymentsTextItem alloc] init]; -} - -- (CollectionViewItem*)contactInfoItem { - return [[AutofillProfileItem alloc] init]; -} - -- (CollectionViewFooterItem*)footerItem { - return [[CollectionViewFooterItem alloc] init]; -} - -@end - -@interface TestPaymentRequestMediatorNoShipping : TestPaymentRequestMediator - -@end - -@implementation TestPaymentRequestMediatorNoShipping - -- (BOOL)requestShipping { - return NO; -} - -@end - -@interface TestPaymentRequestMediatorNoContactInfo : TestPaymentRequestMediator - -@end - -@implementation TestPaymentRequestMediatorNoContactInfo - -- (BOOL)requestContactInfo { - return NO; -} - -@end - -@interface TestPaymentRequestMediatorCantShip : TestPaymentRequestMediator - -@end - -@implementation TestPaymentRequestMediatorCantShip - -- (BOOL)canShip { - return NO; -} - -@end - class PaymentRequestViewControllerTest : public CollectionViewControllerTest { protected: PaymentRequestViewControllerTest() @@ -144,19 +39,15 @@ // Add testing profile and credit card to autofill::TestPersonalDataManager. personal_data_manager_.AddTestingProfile(&autofill_profile_); personal_data_manager_.AddTestingCreditCard(&credit_card_); - - payment_request_ = base::MakeUnique<TestPaymentRequest>( - payment_request_test_util::CreateTestWebPaymentRequest(), - &personal_data_manager_); - - mediator_ = [[TestPaymentRequestMediator alloc] init]; } CollectionViewController* InstantiateController() override { - PaymentRequestViewController* viewController = - [[PaymentRequestViewController alloc] init]; - [viewController setDataSource:mediator_]; - return viewController; + payment_request_ = base::MakeUnique<PaymentRequest>( + payment_request_test_util::CreateTestWebPaymentRequest(), + &personal_data_manager_); + + return [[PaymentRequestViewController alloc] + initWithPaymentRequest:payment_request_.get()]; } PaymentRequestViewController* GetPaymentRequestViewController() { @@ -167,8 +58,7 @@ autofill::AutofillProfile autofill_profile_; autofill::CreditCard credit_card_; autofill::TestPersonalDataManager personal_data_manager_; - std::unique_ptr<TestPaymentRequest> payment_request_; - TestPaymentRequestMediator* mediator_; + std::unique_ptr<PaymentRequest> payment_request_; }; // Tests that the correct items are displayed after loading the model. @@ -179,14 +69,17 @@ [GetPaymentRequestViewController() loadModel]; - // There should be five sections in total. Summary, Shipping, Payment Method, - // Contact Info and the Footer. + // There should be five sections in total. Summary, Shipping, Payment, + // Contact info and a footer. ASSERT_EQ(5, NumberOfSections()); // The only item in the Summary section should be of type PriceItem. ASSERT_EQ(1U, static_cast<unsigned int>(NumberOfItemsInSection(0))); id item = GetCollectionViewItem(0, 0); EXPECT_TRUE([item isMemberOfClass:[PriceItem class]]); + PriceItem* price_item = item; + EXPECT_EQ(MDCCollectionViewCellAccessoryDisclosureIndicator, + price_item.accessoryType); // There should be two items in the Shipping section. ASSERT_EQ(2U, static_cast<unsigned int>(NumberOfItemsInSection(1))); @@ -194,129 +87,103 @@ // The first one should be of type AutofillProfileItem. item = GetCollectionViewItem(1, 0); EXPECT_TRUE([item isMemberOfClass:[AutofillProfileItem class]]); + AutofillProfileItem* shipping_address_item = item; + EXPECT_EQ(MDCCollectionViewCellAccessoryDisclosureIndicator, + shipping_address_item.accessoryType); // The next item should be of type PaymentsTextItem. item = GetCollectionViewItem(1, 1); EXPECT_TRUE([item isMemberOfClass:[PaymentsTextItem class]]); + PaymentsTextItem* shipping_option_item = item; + EXPECT_EQ(MDCCollectionViewCellAccessoryDisclosureIndicator, + shipping_option_item.accessoryType); - // The only item in the Payment Method section should be of type - // PaymentMethodItem. + // The only item in the Payment section should be of type PaymentMethodItem. ASSERT_EQ(1U, static_cast<unsigned int>(NumberOfItemsInSection(2))); item = GetCollectionViewItem(2, 0); EXPECT_TRUE([item isMemberOfClass:[PaymentMethodItem class]]); - // The only item in the Contact Info section should be of type + // The only item in the Contact info section should be of type // AutofillProfileItem. ASSERT_EQ(1U, static_cast<unsigned int>(NumberOfItemsInSection(3))); item = GetCollectionViewItem(3, 0); EXPECT_TRUE([item isMemberOfClass:[AutofillProfileItem class]]); - - // The only item in the Footer section should be of type - // CollectionViewFooterItem. - ASSERT_EQ(1U, static_cast<unsigned int>(NumberOfItemsInSection(4))); - item = GetCollectionViewItem(4, 0); - EXPECT_TRUE([item isMemberOfClass:[CollectionViewFooterItem class]]); -} - -// Tests that the correct items are displayed after loading the model, when no -// shipping information is requested. -TEST_F(PaymentRequestViewControllerTest, TestModelNoShipping) { - mediator_ = [[TestPaymentRequestMediatorNoShipping alloc] init]; - - CreateController(); - CheckController(); - - // There should be four sections in total now. - ASSERT_EQ(4, NumberOfSections()); - - // The second section is the Payment Method section isntead of the Shipping - // section. - ASSERT_EQ(1U, static_cast<unsigned int>(NumberOfItemsInSection(1))); - CollectionViewItem* item = GetCollectionViewItem(1, 0); - EXPECT_TRUE([item isMemberOfClass:[PaymentMethodItem class]]); -} - -// Tests that the correct items are displayed after loading the model, when no -// contact information is requested. -TEST_F(PaymentRequestViewControllerTest, TestModelNoContactInfo) { - mediator_ = [[TestPaymentRequestMediatorNoContactInfo alloc] init]; - - CreateController(); - CheckController(); - - // There should be four sections in total now. - ASSERT_EQ(4, NumberOfSections()); - - // The fourth section is the Footer section instead of the Contact Info - // section. - ASSERT_EQ(1U, static_cast<unsigned int>(NumberOfItemsInSection(3))); - CollectionViewItem* item = GetCollectionViewItem(3, 0); - EXPECT_TRUE([item isMemberOfClass:[CollectionViewFooterItem class]]); } // Tests that the correct items are displayed after loading the model, when -// shipping can't be made. -TEST_F(PaymentRequestViewControllerTest, TestModelCantShip) { - mediator_ = [[TestPaymentRequestMediatorCantShip alloc] init]; - +// there are no display items. +TEST_F(PaymentRequestViewControllerTest, TestModelNoDisplayItem) { CreateController(); CheckController(); - // There should only be one item in the Shipping section and it should be of - // type AutofillProfileItem. - ASSERT_EQ(1U, static_cast<unsigned int>(NumberOfItemsInSection(1))); - id item = GetCollectionViewItem(1, 0); - EXPECT_TRUE([item isMemberOfClass:[AutofillProfileItem class]]); + payment_request_->UpdatePaymentDetails(web::PaymentDetails()); + [GetPaymentRequestViewController() loadModel]; + + // The only item in the Summary section should stil be of type PriceItem, but + // without an accessory view. + ASSERT_EQ(1U, static_cast<unsigned int>(NumberOfItemsInSection(0))); + id item = GetCollectionViewItem(0, 0); + EXPECT_TRUE([item isMemberOfClass:[PriceItem class]]); + PriceItem* price_item = item; + EXPECT_EQ(MDCCollectionViewCellAccessoryNone, price_item.accessoryType); } -// Tests that the correct items are displayed after updating the Shipping -// section. -TEST_F(PaymentRequestViewControllerTest, TestUpdateShippingSection) { +// Tests that the correct items are displayed after loading the model, when +// there is no selected shipping addresse. +TEST_F(PaymentRequestViewControllerTest, TestModelNoSelectedShippingAddress) { CreateController(); CheckController(); - [GetPaymentRequestViewController() updateShippingSection]; + payment_request_->set_selected_shipping_profile(nullptr); + [GetPaymentRequestViewController() loadModel]; - // There should be two items in the Shipping section. + // There should still be two items in the Shipping section. ASSERT_EQ(2U, static_cast<unsigned int>(NumberOfItemsInSection(1))); - // The first one should be of type AutofillProfileItem. + // The first one should be of type CollectionViewDetailItem. id item = GetCollectionViewItem(1, 0); - EXPECT_TRUE([item isMemberOfClass:[AutofillProfileItem class]]); - - // The next item should be of type PaymentsTextItem. - item = GetCollectionViewItem(1, 1); - EXPECT_TRUE([item isMemberOfClass:[PaymentsTextItem class]]); + EXPECT_TRUE([item isMemberOfClass:[CollectionViewDetailItem class]]); + CollectionViewDetailItem* detail_item = item; + EXPECT_EQ(MDCCollectionViewCellAccessoryNone, detail_item.accessoryType); } -// Tests that the correct items are displayed after updating the Payment Method -// section. -TEST_F(PaymentRequestViewControllerTest, TestUpdatePaymentMethodSection) { +// Tests that the correct items are displayed after loading the model, when +// there is no selected shipping option. +TEST_F(PaymentRequestViewControllerTest, TestModelNoSelectedShippingOption) { CreateController(); CheckController(); - [GetPaymentRequestViewController() updatePaymentMethodSection]; + // Resetting the payment details should reset the selected shipping option. + payment_request_->UpdatePaymentDetails(web::PaymentDetails()); + [GetPaymentRequestViewController() loadModel]; - // The only item in the Payment Method section should be of type - // PaymentMethodItem. + // There should still be two items in the Shipping section. + ASSERT_EQ(2U, static_cast<unsigned int>(NumberOfItemsInSection(1))); + + // The second one should be of type CollectionViewDetailItem. + id item = GetCollectionViewItem(1, 1); + EXPECT_TRUE([item isMemberOfClass:[CollectionViewDetailItem class]]); + CollectionViewDetailItem* detail_item = item; + EXPECT_EQ(MDCCollectionViewCellAccessoryDisclosureIndicator, + detail_item.accessoryType); +} + +// Tests that the correct items are displayed after loading the model, when +// there is no selected payment method. +TEST_F(PaymentRequestViewControllerTest, TestModelNoSelectedPaymentMethod) { + CreateController(); + CheckController(); + + payment_request_->set_selected_credit_card(nullptr); + [GetPaymentRequestViewController() loadModel]; + + // The only item in the Payment section should be of type + // CollectionViewDetailItem. ASSERT_EQ(1U, static_cast<unsigned int>(NumberOfItemsInSection(2))); id item = GetCollectionViewItem(2, 0); - EXPECT_TRUE([item isMemberOfClass:[PaymentMethodItem class]]); -} - -// Tests that the correct items are displayed after updating the Contact Info -// section. -TEST_F(PaymentRequestViewControllerTest, TestUpdateContactInfoSection) { - CreateController(); - CheckController(); - - [GetPaymentRequestViewController() updatePaymentMethodSection]; - - // The only item in the Contact Info section should be of type - // AutofillProfileItem. - ASSERT_EQ(1U, static_cast<unsigned int>(NumberOfItemsInSection(3))); - id item = GetCollectionViewItem(3, 0); - EXPECT_TRUE([item isMemberOfClass:[AutofillProfileItem class]]); + EXPECT_TRUE([item isMemberOfClass:[CollectionViewDetailItem class]]); + CollectionViewDetailItem* detail_item = item; + EXPECT_EQ(MDCCollectionViewCellAccessoryNone, detail_item.accessoryType); } // Tests that the correct items are displayed after loading the model, when @@ -336,3 +203,13 @@ id item = GetCollectionViewItem(0, 0); EXPECT_TRUE([item isMemberOfClass:[StatusItem class]]); } + +TEST_F(PaymentRequestViewControllerTest, TestSignedInStringFormatting) { + const std::string unformattedString = l10n_util::GetStringUTF8( + IDS_PAYMENTS_CARD_AND_ADDRESS_SETTINGS_SIGNED_IN); + const std::string formattedString = l10n_util::GetStringFUTF8( + IDS_PAYMENTS_CARD_AND_ADDRESS_SETTINGS_SIGNED_IN, + base::ASCIIToUTF16("example@gmail.com")); + + EXPECT_NE(unformattedString, formattedString); +}
diff --git a/net/log/net_log.cc b/net/log/net_log.cc index c482877..3ba872e 100644 --- a/net/log/net_log.cc +++ b/net/log/net_log.cc
@@ -9,6 +9,7 @@ #include "base/bind.h" #include "base/logging.h" +#include "base/memory/ptr_util.h" #include "base/strings/string_number_conversions.h" #include "base/strings/utf_string_conversions.h" #include "base/values.h" @@ -199,12 +200,12 @@ } // static -base::Value* NetLog::GetEventTypesAsValue() { - std::unique_ptr<base::DictionaryValue> dict(new base::DictionaryValue()); +std::unique_ptr<base::Value> NetLog::GetEventTypesAsValue() { + auto dict = base::MakeUnique<base::DictionaryValue>(); for (int i = 0; i < static_cast<int>(NetLogEventType::COUNT); ++i) { dict->SetInteger(EventTypeToString(static_cast<NetLogEventType>(i)), i); } - return dict.release(); + return std::move(dict); } // static @@ -222,12 +223,12 @@ } // static -base::Value* NetLog::GetSourceTypesAsValue() { - std::unique_ptr<base::DictionaryValue> dict(new base::DictionaryValue()); +std::unique_ptr<base::Value> NetLog::GetSourceTypesAsValue() { + auto dict = base::MakeUnique<base::DictionaryValue>(); for (int i = 0; i < static_cast<int>(NetLogSourceType::COUNT); ++i) { dict->SetInteger(SourceTypeToString(static_cast<NetLogSourceType>(i)), i); } - return dict.release(); + return std::move(dict); } // static
diff --git a/net/log/net_log.h b/net/log/net_log.h index 41e8cc64e..0a10808c 100644 --- a/net/log/net_log.h +++ b/net/log/net_log.h
@@ -154,15 +154,15 @@ static const char* EventTypeToString(NetLogEventType event_type); // Returns a dictionary that maps event type symbolic names to their enum - // values. Caller takes ownership of the returned Value. - static base::Value* GetEventTypesAsValue(); + // values. + static std::unique_ptr<base::Value> GetEventTypesAsValue(); // Returns a C-String symbolic name for |source_type|. static const char* SourceTypeToString(NetLogSourceType source_type); // Returns a dictionary that maps source type symbolic names to their enum - // values. Caller takes ownership of the returned Value. - static base::Value* GetSourceTypesAsValue(); + // values. + static std::unique_ptr<base::Value> GetSourceTypesAsValue(); // Returns a C-String symbolic name for |event_phase|. static const char* EventPhaseToString(NetLogEventPhase event_phase);
diff --git a/third_party/WebKit/LayoutTests/app_banner/app-banner-event-gc.html b/third_party/WebKit/LayoutTests/app_banner/app-banner-event-gc.html new file mode 100644 index 0000000..22de892 --- /dev/null +++ b/third_party/WebKit/LayoutTests/app_banner/app-banner-event-gc.html
@@ -0,0 +1,19 @@ +<!DOCTYPE html> +<script src="../resources/testharness.js"></script> +<script src="../resources/testharnessreport.js"></script> +<script> + +async_test(function(t) { + window.addEventListener('beforeinstallprompt', event => { + setTimeout(_ => { gc(); }, 0); + event.userChoice.then(_ => { t.done(); }); + }); + + testRunner.dispatchBeforeInstallPromptEvent(['foo'], _ => { + setTimeout(_ => { + testRunner.resolveBeforeInstallPromptPromise('foo'); + }, 100); + }); +}, 'accept'); + +</script>
diff --git a/third_party/WebKit/LayoutTests/bluetooth/requestDevice/acceptAllDevices/optional-services-missing.html b/third_party/WebKit/LayoutTests/bluetooth/requestDevice/acceptAllDevices/optional-services-missing.html index f1c028f..738e0f0 100644 --- a/third_party/WebKit/LayoutTests/bluetooth/requestDevice/acceptAllDevices/optional-services-missing.html +++ b/third_party/WebKit/LayoutTests/bluetooth/requestDevice/acceptAllDevices/optional-services-missing.html
@@ -2,14 +2,14 @@ <script src="../../../resources/testharness.js"></script> <script src="../../../resources/testharnessreport.js"></script> <script src="../../../resources/bluetooth/bluetooth-helpers.js"></script> +<script src="../../../resources/bluetooth/web-bluetooth-test.js"></script> +<script src="../../../resources/mojo-helpers.js"></script> <script> 'use strict'; promise_test(() => { - return setBluetoothFakeAdapter('TwoHeartRateServicesAdapter') - .then(() => requestDeviceWithKeyDown({acceptAllDevices: true})) - .then(device => device.gatt.connect()) - .then(gattServer => assert_promise_rejects_with_message( - gattServer.getPrimaryServices(), + return getHealthThermometerDevice({acceptAllDevices: true}) + .then(([device]) => assert_promise_rejects_with_message( + device.gatt.getPrimaryServices(), new DOMException( 'Origin is not allowed to access any service. ' + 'Tip: Add the service UUID to \'optionalServices\' in ' +
diff --git a/third_party/WebKit/LayoutTests/bluetooth/requestDevice/blocklisted-service-in-optionalServices.html b/third_party/WebKit/LayoutTests/bluetooth/requestDevice/blocklisted-service-in-optionalServices.html index 0053650..1a69b79 100644 --- a/third_party/WebKit/LayoutTests/bluetooth/requestDevice/blocklisted-service-in-optionalServices.html +++ b/third_party/WebKit/LayoutTests/bluetooth/requestDevice/blocklisted-service-in-optionalServices.html
@@ -2,6 +2,8 @@ <script src="../../resources/testharness.js"></script> <script src="../../resources/testharnessreport.js"></script> <script src="../../resources/bluetooth/bluetooth-helpers.js"></script> +<script src="../../resources/bluetooth/web-bluetooth-test.js"></script> +<script src="../../resources/mojo-helpers.js"></script> <script> 'use strict'; promise_test(() => { @@ -10,18 +12,23 @@ '\'optionalServices\' in requestDevice() ' + 'options. https://goo.gl/HxfxSQ', 'SecurityError'); - return setBluetoothFakeAdapter('BlocklistTestAdapter') - .then(() => requestDeviceWithKeyDown({ - filters: [{services: [blocklist_test_service_uuid]}], + return getDiscoveredHealthThermometerDevice({ + filters: [{services: ['health_thermometer']}], optionalServices: ['human_interface_device'] - })) - .then(device => device.gatt.connect()) - .then(gattServer => Promise.all([ - assert_promise_rejects_with_message( - gattServer.getPrimaryService('human_interface_device'), - expected, 'Blocklisted service not accessible.'), - assert_promise_rejects_with_message( - gattServer.getPrimaryServices('human_interface_device'), - expected, 'Blocklisted services not accessible.')])); + }) + .then(([device, fake_peripheral]) => { + return fake_peripheral + .setNextGATTConnectionResponse({code: HCI_SUCCESS}) + .then(() => device.gatt.connect()) + .then(() => fake_peripheral.setNextGATTDiscoveryResponse({ + code: HCI_SUCCESS})) + .then(() => Promise.all([ + assert_promise_rejects_with_message( + device.gatt.getPrimaryService('human_interface_device'), + expected, 'Blocklisted service not accessible.'), + assert_promise_rejects_with_message( + device.gatt.getPrimaryServices('human_interface_device'), + expected, 'Blocklisted services not accessible.')])); + }); }, 'Blocklisted UUID in optionalServices is removed and access not granted.'); </script>
diff --git a/third_party/WebKit/LayoutTests/presentation/presentationrequest-gc.html b/third_party/WebKit/LayoutTests/presentation/presentationrequest-gc.html new file mode 100644 index 0000000..86924b33a --- /dev/null +++ b/third_party/WebKit/LayoutTests/presentation/presentationrequest-gc.html
@@ -0,0 +1,16 @@ +<!DOCTYPE html> +<html> +<body> +<script src="../resources/testharness.js"></script> +<script src="../resources/testharnessreport.js"></script> +<script> + +async_test(function(t) { + Promise.resolve().then(_ => { gc(); }); + var request = new PresentationRequest("https://example.com"); + request.getAvailability().then(_ => { t.done(); }); + }); + +</script> +</body> +</html>
diff --git a/third_party/WebKit/LayoutTests/resources/bluetooth/bluetooth-helpers.js b/third_party/WebKit/LayoutTests/resources/bluetooth/bluetooth-helpers.js index aae8a9b..c017db2c 100644 --- a/third_party/WebKit/LayoutTests/resources/bluetooth/bluetooth-helpers.js +++ b/third_party/WebKit/LayoutTests/resources/bluetooth/bluetooth-helpers.js
@@ -461,9 +461,12 @@ function getHealthThermometerDevice(options) { return getDiscoveredHealthThermometerDevice(options) .then(([device, fake_peripheral]) => { - return fake_peripheral.setNextGATTConnectionResponse({code: HCI_SUCCESS}) + return fake_peripheral + .setNextGATTConnectionResponse({code: HCI_SUCCESS}) .then(() => device.gatt.connect()) - .then(gatt => [gatt.device, fake_peripheral]); + .then(() => fake_peripheral.setNextGATTDiscoveryResponse({ + code: HCI_SUCCESS})) + .then(() => [device, fake_peripheral]); }); }
diff --git a/third_party/WebKit/LayoutTests/resources/bluetooth/web-bluetooth-test.js b/third_party/WebKit/LayoutTests/resources/bluetooth/web-bluetooth-test.js index 1f5e29de..7b6cd79 100644 --- a/third_party/WebKit/LayoutTests/resources/bluetooth/web-bluetooth-test.js +++ b/third_party/WebKit/LayoutTests/resources/bluetooth/web-bluetooth-test.js
@@ -163,7 +163,31 @@ await this.fake_central_ptr_.setNextGATTConnectionResponse( this.address, code); - if (success !== true) throw 'Cannot set next response.'; + if (success !== true) throw 'setNextGATTConnectionResponse failed.'; + } + + // Sets the next GATT Discovery request response for peripheral with + // |address| to |code|. |code| could be an HCI Error Code from + // BT 4.2 Vol 2 Part D 1.3 List Of Error Codes or a number outside that + // range returned by specific platforms e.g. Android returns 0x101 to signal + // a GATT failure + // https://developer.android.com/reference/android/bluetooth/BluetoothGatt.html#GATT_FAILURE + // + // The following procedures defined at BT 4.2 Vol 3 Part G Section 4. + // "GATT Feature Requirements" are used to discover attributes of the + // GATT Server: + // - Primary Service Discovery + // - Relationship Discovery + // - Characteristic Discovery + // - Characteristic Descriptor Discovery + // This method aims to simulate the response once all of these procedures + // have completed or if there was an error during any of them. + async setNextGATTDiscoveryResponse({code}) { + let {success} = + await this.fake_central_ptr_.setNextGATTDiscoveryResponse( + this.address, code); + + if (success !== true) throw 'setNextGATTDiscoveryResponse failed.'; } }
diff --git a/third_party/WebKit/Source/build/scripts/make_computed_style_base.py b/third_party/WebKit/Source/build/scripts/make_computed_style_base.py index 50dc4e57..dd1dd28 100755 --- a/third_party/WebKit/Source/build/scripts/make_computed_style_base.py +++ b/third_party/WebKit/Source/build/scripts/make_computed_style_base.py
@@ -442,6 +442,7 @@ self._include_paths = _get_include_paths(all_properties) self._outputs = { 'ComputedStyleBase.h': self.generate_base_computed_style_h, + 'ComputedStyleBase.cpp': self.generate_base_computed_style_cpp, 'ComputedStyleBaseConstants.h': self.generate_base_computed_style_constants, } @@ -455,6 +456,16 @@ 'diff_functions_map': self._diff_functions_map, } + @template_expander.use_jinja('ComputedStyleBase.cpp.tmpl', tests={'in': lambda a, b: a in b}) + def generate_base_computed_style_cpp(self): + return { + 'properties': self._properties, + 'enums': self._generated_enums, + 'include_paths': self._include_paths, + 'computed_style': self._root_group, + 'diff_functions_map': self._diff_functions_map, + } + @template_expander.use_jinja('ComputedStyleBaseConstants.h.tmpl') def generate_base_computed_style_constants(self): return {
diff --git a/third_party/WebKit/Source/build/scripts/templates/ComputedStyleBase.cpp.tmpl b/third_party/WebKit/Source/build/scripts/templates/ComputedStyleBase.cpp.tmpl new file mode 100644 index 0000000..5a95aaacc --- /dev/null +++ b/third_party/WebKit/Source/build/scripts/templates/ComputedStyleBase.cpp.tmpl
@@ -0,0 +1,78 @@ +{% from 'macros.tmpl' import license, print_if %} +{% from 'fields/field.tmpl' import encode, getter_expression, setter_expression, fieldwise_copy, fieldwise_diff %} +{% from 'fields/group.tmpl' import define_field_group_class %} +{{license()}} + +#include "core/ComputedStyleBase.h" +#include "core/style/ComputedStyle.h" +#include "platform/wtf/SizeAssertions.h" + +namespace blink { + +struct SameSizeAsComputedStyleBase { + {% if computed_style.subgroups is defined %} + void* dataRefs[{{computed_style.subgroups|length}}]; + {% endif %} + {% for field in computed_style.fields|rejectattr("is_bit_field") %} + {{field.type_name}} {{field.name}}; + {% endfor %} + unsigned m_bit_fields[{{computed_style.num_32_bit_words_for_bit_fields}}]; +}; + +// If this fails, the packing algorithm in make_computed_style_base.py has +// failed to produce the optimal packed size. To fix, update the algorithm to +// ensure that the buckets are placed so that each takes up at most 1 word. +ASSERT_SIZE(ComputedStyleBase, SameSizeAsComputedStyleBase); + +// Constructor and destructor are protected so that only the parent class ComputedStyle +// can instantiate this class. +ComputedStyleBase::ComputedStyleBase() : +{% for field in computed_style.fields %} + {{field.name}}({{encode(field, field.default_value)}}){{print_if(not loop.last, ',')}} +{% endfor %} +{ + {% for subgroup in computed_style.subgroups %} + {{subgroup.member_name}}.Init(); + {% endfor %} +} + +void ComputedStyleBase::InheritFrom(const ComputedStyleBase& other, + IsAtShadowBoundary isAtShadowBoundary) { + {{fieldwise_copy(computed_style, computed_style.all_fields + |selectattr("is_property") + |selectattr("is_inherited") + |list + )|indent(2)}} +} + +void ComputedStyleBase::CopyNonInheritedFromCached( + const ComputedStyleBase& other) { + {{fieldwise_copy(computed_style, computed_style.all_fields + |rejectattr("has_custom_compare_and_copy") + |rejectattr("is_inherited") + |list + )|indent(2)}} +} + +void ComputedStyleBase::PropagateIndependentInheritedProperties( + const ComputedStyleBase& parentStyle) { + {% for field in computed_style.all_fields if field.is_property and field.is_independent %} + if ({{field.is_inherited_method_name}}()) + {{setter_expression(field)}} = parentStyle.{{getter_expression(field)}}; + {% endfor %} +} + +{% for name, groups_to_diff in diff_functions_map.items() %} +bool ComputedStyleBase::{{name}}(const ComputedStyle& a, const ComputedStyle& b) { + {{fieldwise_diff(groups_to_diff)|indent(4)}} + return false; +} + +{% endfor %} + +{% for group in computed_style.subgroups %} +{{define_field_group_class(group)}} + +{% endfor %} + +} // namespace blink
diff --git a/third_party/WebKit/Source/build/scripts/templates/ComputedStyleBase.h.tmpl b/third_party/WebKit/Source/build/scripts/templates/ComputedStyleBase.h.tmpl index ca07105..614a49c 100644 --- a/third_party/WebKit/Source/build/scripts/templates/ComputedStyleBase.h.tmpl +++ b/third_party/WebKit/Source/build/scripts/templates/ComputedStyleBase.h.tmpl
@@ -1,6 +1,6 @@ {% from 'macros.tmpl' import license, print_if %} {% from 'fields/field.tmpl' import encode, getter_expression, setter_expression, declare_storage, fieldwise_compare, fieldwise_copy, fieldwise_diff, fieldwise_pointer_compare_inherited %} -{% from 'fields/group.tmpl' import define_field_group_class %} +{% from 'fields/group.tmpl' import declare_field_group_class %} {{license()}} #ifndef ComputedStyleBase_h @@ -36,15 +36,8 @@ namespace blink { -struct SameSizeAsComputedStyleBase { - {% if computed_style.subgroups is defined %} - void* dataRefs[{{computed_style.subgroups|length}}]; - {% endif %} - {% for field in computed_style.fields|rejectattr("is_bit_field") %} - {{field.type_name}} {{field.name}}; - {% endfor %} - unsigned m_bit_fields[{{computed_style.num_32_bit_words_for_bit_fields}}]; -}; +// Forward declaration for diff functions. +class ComputedStyle; // The generated portion of ComputedStyle. For more info, see the header comment // in ComputedStyle.h. @@ -82,12 +75,6 @@ // example, a field with the 'keyword' template has only one setter, whereas an // 'external' field has an extra setter that takes an rvalue reference. A list // of the available templates can be found in CSSProperties.json5. -// -// ComputedStyleBase is a template class to allow it to use functions on -// ComputedStyle. This allows ComputedStyleBase to use hand written functions it -// would otherwise not know about. It should only be templated with the -// ComputedStyle class and no other class is allowed. -template <class ComputedStyleFinal> class CORE_EXPORT ComputedStyleBase { public: inline bool IndependentInheritedEqual(const ComputedStyleBase& o) const { @@ -142,39 +129,18 @@ }; void InheritFrom(const ComputedStyleBase& other, - IsAtShadowBoundary isAtShadowBoundary) { - {{fieldwise_copy(computed_style, computed_style.all_fields - |selectattr("is_property") - |selectattr("is_inherited") - |list - )|indent(4)}} - } + IsAtShadowBoundary isAtShadowBoundary); void CopyNonInheritedFromCached( - const ComputedStyleBase& other) { - {{fieldwise_copy(computed_style, computed_style.all_fields - |rejectattr("has_custom_compare_and_copy") - |rejectattr("is_inherited") - |list - )|indent(4)}} - } + const ComputedStyleBase& other); // Copies the values of any independent inherited properties from the parent // style that are marked as inherited by this style. void PropagateIndependentInheritedProperties( - const ComputedStyleBase& parentStyle) { - {% for field in computed_style.all_fields if field.is_property and field.is_independent %} - if ({{field.is_inherited_method_name}}()) - {{setter_expression(field)}} = parentStyle.{{getter_expression(field)}}; - {% endfor %} - } + const ComputedStyleBase& parentStyle); {% for name, groups_to_diff in diff_functions_map.items() %} - bool {{name}}(const ComputedStyleFinal& other) const { - const ComputedStyleFinal& self = static_cast<const ComputedStyleFinal&>(*this); - {{fieldwise_diff(groups_to_diff)|indent(4)}} - return false; - } + static bool {{name}}(const ComputedStyle& a, const ComputedStyle& b); {% endfor %} // Fields. @@ -188,23 +154,14 @@ {% endfor %} private: {% for subgroup in computed_style.subgroups %} - {{define_field_group_class(subgroup)|indent(2)}} + {{declare_field_group_class(subgroup)|indent(2)}} {% endfor %} protected: // Constructor and destructor are protected so that only the parent class ComputedStyle // can instantiate this class. - ALWAYS_INLINE ComputedStyleBase() : - {% for field in computed_style.fields %} - {{field.name}}({{encode(field, field.default_value)}}){{print_if(not loop.last, ',')}} - {% endfor %} - { - static_assert(std::is_same<ComputedStyle, ComputedStyleFinal>::value, "ComputedStyleBase can only be templated with ComputedStyle"); - {% for subgroup in computed_style.subgroups %} - {{subgroup.member_name}}.Init(); - {% endfor %} - } + ComputedStyleBase(); {% for field in computed_style.all_fields|sort(attribute='name') %} {% if field.field_template in ('storage_only', 'monotonic_flag', 'external') %}
diff --git a/third_party/WebKit/Source/build/scripts/templates/StylePropertyShorthand.cpp.tmpl b/third_party/WebKit/Source/build/scripts/templates/StylePropertyShorthand.cpp.tmpl index 88a25e21..875b9c0 100644 --- a/third_party/WebKit/Source/build/scripts/templates/StylePropertyShorthand.cpp.tmpl +++ b/third_party/WebKit/Source/build/scripts/templates/StylePropertyShorthand.cpp.tmpl
@@ -42,6 +42,7 @@ // Returns an empty list if the property is not a shorthand const StylePropertyShorthand& shorthandForProperty(CSSPropertyID propertyID) { DEFINE_STATIC_LOCAL(StylePropertyShorthand, emptyShorthand, ()); + // FIXME: We shouldn't switch between shorthand/not shorthand based on a runtime flag if (propertyID == CSSPropertyTextDecoration && !RuntimeEnabledFeatures::CSS3TextDecorationsEnabled()) return emptyShorthand;
diff --git a/third_party/WebKit/Source/build/scripts/templates/fields/field.tmpl b/third_party/WebKit/Source/build/scripts/templates/fields/field.tmpl index 74fcdeb..531391b 100644 --- a/third_party/WebKit/Source/build/scripts/templates/fields/field.tmpl +++ b/third_party/WebKit/Source/build/scripts/templates/fields/field.tmpl
@@ -123,16 +123,16 @@ {% macro fieldwise_diff(group_to_diff) %} {% for group in group_to_diff.subgroups %} -if ({{group.group_name}}.Get() != other.{{group.group_name}}.Get()) { +if (a.{{group.group_name}}.Get() != b.{{group.group_name}}.Get()) { {{fieldwise_diff(group)|indent(2, true)}} } {% endfor %} {% for expression in group_to_diff.expressions %} -if (self.{{expression}} != other.{{expression}}) +if (a.{{expression}} != b.{{expression}}) return true; {% endfor %} {% for predicate in group_to_diff.predicates %} -if (!self.{{predicate}}) +if (!{{predicate}}) return true; {% endfor %} {% endmacro %}
diff --git a/third_party/WebKit/Source/build/scripts/templates/fields/group.tmpl b/third_party/WebKit/Source/build/scripts/templates/fields/group.tmpl index 92d246cd..3e644f9e 100644 --- a/third_party/WebKit/Source/build/scripts/templates/fields/group.tmpl +++ b/third_party/WebKit/Source/build/scripts/templates/fields/group.tmpl
@@ -1,6 +1,6 @@ {% from 'fields/field.tmpl' import encode, declare_storage, compare %} {% from 'macros.tmpl' import print_if %} -{% macro define_field_group_class(group): -%} +{% macro declare_field_group_class(group): -%} class {{group.type_name}} : public RefCounted<{{group.type_name}}> { public: static PassRefPtr<{{group.type_name}}> Create() { @@ -24,20 +24,25 @@ {% endfor %} private: - {{group.type_name}}() : + {{group.type_name}}(); + {{group.type_name}}(const {{group.type_name}}&); +}; +{%- endmacro %} + +{% macro define_field_group_class(group): -%} +ComputedStyleBase::{{group.type_name}}::{{group.type_name}}() : {% for field in group.fields %} {{field.name}}({{encode(field, field.default_value)}}){{print_if(not loop.last, ',')}} {% endfor %} {} - {{group.type_name}}(const {{group.type_name}}& other) : +ComputedStyleBase::{{group.type_name}}::{{group.type_name}}(const {{group.type_name}}& other) : {% for field in group.fields %} - {% if field.wrapper_pointer_name %} + {% if field.wrapper_pointer_name %} {{field.name}}(MemberCopy(other.{{field.name}})){{print_if(not loop.last, ',')}} - {% else %} + {% else %} {{field.name}}(other.{{field.name}}){{print_if(not loop.last, ',')}} - {% endif %} + {% endif %} {% endfor %} {} -}; {%- endmacro %}
diff --git a/third_party/WebKit/Source/core/BUILD.gn b/third_party/WebKit/Source/core/BUILD.gn index 389b4fa..7b774bec 100644 --- a/third_party/WebKit/Source/core/BUILD.gn +++ b/third_party/WebKit/Source/core/BUILD.gn
@@ -426,10 +426,12 @@ "../build/scripts/templates/fields/storage_only.tmpl", "../build/scripts/templates/fields/external.tmpl", "../build/scripts/templates/ComputedStyleBase.h.tmpl", + "../build/scripts/templates/ComputedStyleBase.cpp.tmpl", "../build/scripts/templates/ComputedStyleBaseConstants.h.tmpl", ] outputs = [ "$blink_core_output_dir/ComputedStyleBase.h", + "$blink_core_output_dir/ComputedStyleBase.cpp", "$blink_core_output_dir/ComputedStyleBaseConstants.h", ] }
diff --git a/third_party/WebKit/Source/core/css/CSSProperties.json5 b/third_party/WebKit/Source/core/css/CSSProperties.json5 index d9b981b..1499c311 100644 --- a/third_party/WebKit/Source/core/css/CSSProperties.json5 +++ b/third_party/WebKit/Source/core/css/CSSProperties.json5
@@ -604,9 +604,9 @@ svg: true, }, { + name: "align-self", api_class: "CSSPropertyAPIAlignOrJustifySelf", api_methods: ["parseSingleValue"], - name: "align-self", converter: "ConvertSelfOrDefaultAlignmentData", initial: "InitialSelfAlignment", }, @@ -617,7 +617,9 @@ interpolable: true, runtime_flag: "CSSBackdropFilter", }, - "backface-visibility", + { + name: "backface-visibility", + }, { name: "background-attachment", custom_all: true, @@ -1159,7 +1161,9 @@ converter: "ConvertLengthOrAuto", interpolable: true, }, - "flex-direction", + { + name: "flex-direction", + }, { name: "flex-grow", api_class: "CSSPropertyAPIFlexGrowOrShrink", @@ -1172,7 +1176,9 @@ interpolable: true, type_name: "float", }, - "flex-wrap", + { + name: "flex-wrap", + }, { name: "float", default_value: "none", @@ -1310,7 +1316,9 @@ name_for_methods: "RespectImageOrientation", runtime_flag: "ImageOrientation", }, - "isolation", + { + name: "isolation", + }, { name: "justify-content", api_class: "CSSPropertyAPIAlignOrJustifyContent", @@ -2048,7 +2056,6 @@ field_size: 1, field_group: "rare-inherited", }, - // FIXME: We shouldn't switch between shorthand/not shorthand based on a runtime flag { name: "text-decoration", api_class: true, @@ -2367,8 +2374,12 @@ api_methods: ["parseSingleValue"], type_name: "unsigned int", }, - "-webkit-box-orient", - "-webkit-box-pack", + { + name: "-webkit-box-orient", + }, + { + name: "-webkit-box-pack", + }, { name: "-webkit-box-reflect", converter: "ConvertBoxReflect", @@ -2698,7 +2709,9 @@ converter: "ConvertComputedLength<float>", interpolable: true, }, - "-webkit-user-drag", + { + name: "-webkit-user-drag", + }, { name: "-webkit-user-modify", inherited: true,
diff --git a/third_party/WebKit/Source/core/css/ComputedStyleDiffFunctions.json5 b/third_party/WebKit/Source/core/css/ComputedStyleDiffFunctions.json5 index 0e1e584..5837091b 100644 --- a/third_party/WebKit/Source/core/css/ComputedStyleDiffFunctions.json5 +++ b/third_party/WebKit/Source/core/css/ComputedStyleDiffFunctions.json5
@@ -138,11 +138,11 @@ ], predicates_to_test: [ { - predicate: "TextShadowDataEquivalent(other)", + predicate: "a.TextShadowDataEquivalent(b)", field_dependencies: ["text-shadow"] }, { - predicate: "QuotesDataEquivalent(other)", + predicate: "a.QuotesDataEquivalent(b)", field_dependencies: ["quotes"] }, ]
diff --git a/third_party/WebKit/Source/core/css/parser/CSSPropertyParser.cpp b/third_party/WebKit/Source/core/css/parser/CSSPropertyParser.cpp index b1910ec..cc1c38e 100644 --- a/third_party/WebKit/Source/core/css/parser/CSSPropertyParser.cpp +++ b/third_party/WebKit/Source/core/css/parser/CSSPropertyParser.cpp
@@ -707,8 +707,9 @@ // offset: <offset-path> <offset-distance> <offset-rotate> bool CSSPropertyParser::ConsumeOffsetShorthand(bool important) { + DCHECK(context_); const CSSValue* offset_path = - CSSPropertyOffsetPathUtils::ConsumeOffsetPath(range_, context_); + CSSPropertyOffsetPathUtils::ConsumeOffsetPath(range_, *context_); const CSSValue* offset_distance = ConsumeLengthOrPercent(range_, context_->Mode(), kValueRangeAll); const CSSValue* offset_rotate = ConsumeOffsetRotate(range_, *context_);
diff --git a/third_party/WebKit/Source/core/css/properties/CSSPropertyAPIOffsetPath.cpp b/third_party/WebKit/Source/core/css/properties/CSSPropertyAPIOffsetPath.cpp index bb10b5c..6712e75 100644 --- a/third_party/WebKit/Source/core/css/properties/CSSPropertyAPIOffsetPath.cpp +++ b/third_party/WebKit/Source/core/css/properties/CSSPropertyAPIOffsetPath.cpp
@@ -13,7 +13,7 @@ CSSParserTokenRange& range, const CSSParserContext& context, const CSSParserLocalContext&) { - return CSSPropertyOffsetPathUtils::ConsumeOffsetPath(range, &context); + return CSSPropertyOffsetPathUtils::ConsumeOffsetPath(range, context); } } // namespace blink
diff --git a/third_party/WebKit/Source/core/css/properties/CSSPropertyOffsetPathUtils.cpp b/third_party/WebKit/Source/core/css/properties/CSSPropertyOffsetPathUtils.cpp index 9c091e4..373479c 100644 --- a/third_party/WebKit/Source/core/css/properties/CSSPropertyOffsetPathUtils.cpp +++ b/third_party/WebKit/Source/core/css/properties/CSSPropertyOffsetPathUtils.cpp
@@ -45,7 +45,7 @@ } CSSValue* ConsumeRay(CSSParserTokenRange& range, - const CSSParserContext* context) { + const CSSParserContext& context) { DCHECK_EQ(range.Peek().FunctionId(), CSSValueRay); CSSParserTokenRange function_range = range; CSSParserTokenRange function_args = @@ -57,7 +57,7 @@ while (!function_args.AtEnd()) { if (!angle) { angle = CSSPropertyParserHelpers::ConsumeAngle( - function_args, *context, WTF::Optional<UseCounter::Feature>()); + function_args, context, WTF::Optional<UseCounter::Feature>()); if (angle) continue; } @@ -86,7 +86,7 @@ CSSValue* CSSPropertyOffsetPathUtils::ConsumeOffsetPath( CSSParserTokenRange& range, - const CSSParserContext* context) { + const CSSParserContext& context) { CSSValue* value = nullptr; if (RuntimeEnabledFeatures::CSSOffsetPathRayEnabled() && range.Peek().FunctionId() == CSSValueRay) @@ -96,7 +96,7 @@ // Count when we receive a valid path other than 'none'. if (value && !value->IsIdentifierValue()) - context->Count(UseCounter::kCSSOffsetInEffect); + context.Count(UseCounter::kCSSOffsetInEffect); return value; }
diff --git a/third_party/WebKit/Source/core/css/properties/CSSPropertyOffsetPathUtils.h b/third_party/WebKit/Source/core/css/properties/CSSPropertyOffsetPathUtils.h index 405e500..34baacf 100644 --- a/third_party/WebKit/Source/core/css/properties/CSSPropertyOffsetPathUtils.h +++ b/third_party/WebKit/Source/core/css/properties/CSSPropertyOffsetPathUtils.h
@@ -16,7 +16,7 @@ class CSSPropertyOffsetPathUtils { STATIC_ONLY(CSSPropertyOffsetPathUtils); static CSSValue* ConsumeOffsetPath(CSSParserTokenRange&, - const CSSParserContext*); + const CSSParserContext&); static CSSValue* ConsumePathOrNone(CSSParserTokenRange&); };
diff --git a/third_party/WebKit/Source/core/dom/AXObjectCache.h b/third_party/WebKit/Source/core/dom/AXObjectCache.h index 8e2c24a..dad591df 100644 --- a/third_party/WebKit/Source/core/dom/AXObjectCache.h +++ b/third_party/WebKit/Source/core/dom/AXObjectCache.h
@@ -119,6 +119,7 @@ Node* new_focused_node) = 0; virtual void HandleInitialFocus() = 0; virtual void HandleEditableTextContentChanged(Node*) = 0; + virtual void HandleTextMarkerDataAdded(Node* start, Node* end) = 0; virtual void HandleTextFormControlChanged(Node*) = 0; virtual void HandleValueChanged(Node*) = 0; virtual void HandleUpdateActiveMenuOption(LayoutMenuList*,
diff --git a/third_party/WebKit/Source/core/dom/ContainerNode.cpp b/third_party/WebKit/Source/core/dom/ContainerNode.cpp index 071f762..ac671097 100644 --- a/third_party/WebKit/Source/core/dom/ContainerNode.cpp +++ b/third_party/WebKit/Source/core/dom/ContainerNode.cpp
@@ -628,7 +628,7 @@ } { - HTMLFrameOwnerElement::UpdateSuspendScope suspend_widget_hierarchy_updates; + HTMLFrameOwnerElement::PluginDisposeSuspendScope suspend_plugin_dispose; DocumentOrderedMap::RemoveScope tree_remove_scope; Node* prev = child->previousSibling(); @@ -684,7 +684,7 @@ ChildListMutationScope(*this).WillRemoveChild(old_child); old_child.NotifyMutationObserversNodeWillDetach(); - HTMLFrameOwnerElement::UpdateSuspendScope suspend_widget_hierarchy_updates; + HTMLFrameOwnerElement::PluginDisposeSuspendScope suspend_plugin_dispose; DocumentOrderedMap::RemoveScope tree_remove_scope; Node* prev = old_child.previousSibling(); @@ -722,7 +722,7 @@ } { - HTMLFrameOwnerElement::UpdateSuspendScope suspend_widget_hierarchy_updates; + HTMLFrameOwnerElement::PluginDisposeSuspendScope suspend_plugin_dispose; DocumentOrderedMap::RemoveScope tree_remove_scope; { EventDispatchForbiddenScope assert_no_event_dispatch;
diff --git a/third_party/WebKit/Source/core/dom/Document.cpp b/third_party/WebKit/Source/core/dom/Document.cpp index dd13c4ad..75066c0 100644 --- a/third_party/WebKit/Source/core/dom/Document.cpp +++ b/third_party/WebKit/Source/core/dom/Document.cpp
@@ -2128,8 +2128,7 @@ unsigned initial_element_count = GetStyleEngine().StyleForElementCount(); - HTMLFrameOwnerElement::UpdateSuspendScope - suspend_frame_view_base_hierarchy_updates; + HTMLFrameOwnerElement::PluginDisposeSuspendScope suspend_plugin_dispose; lifecycle_.AdvanceTo(DocumentLifecycle::kInStyleRecalc); StyleRecalcChange change = kNoChange; @@ -2548,11 +2547,10 @@ // to trigger navigation here. However, plugins (see below) can cause lots of // crazy things to happen, since plugin detach involves nested run loops. FrameNavigationDisabler navigation_disabler(*frame_); - // Defer FrameViewBase updates to avoid plugins trying to run script inside + // Defer plugin dispose to avoid plugins trying to run script inside // ScriptForbiddenScope, which will crash the renderer after // https://crrev.com/200984 - HTMLFrameOwnerElement::UpdateSuspendScope - suspend_frame_view_base_hierarchy_updates; + HTMLFrameOwnerElement::PluginDisposeSuspendScope suspend_plugin_dispose; // Don't allow script to run in the middle of detachLayoutTree() because a // detaching Document is not in a consistent state. ScriptForbiddenScope forbid_script;
diff --git a/third_party/WebKit/Source/core/dom/Element.cpp b/third_party/WebKit/Source/core/dom/Element.cpp index 7445d78a..b5b7c6ea 100644 --- a/third_party/WebKit/Source/core/dom/Element.cpp +++ b/third_party/WebKit/Source/core/dom/Element.cpp
@@ -1792,7 +1792,7 @@ } void Element::DetachLayoutTree(const AttachContext& context) { - HTMLFrameOwnerElement::UpdateSuspendScope suspend_widget_hierarchy_updates; + HTMLFrameOwnerElement::PluginDisposeSuspendScope suspend_plugin_dispose; CancelFocusAppearanceUpdate(); RemoveCallbackSelectors(); if (HasRareData()) {
diff --git a/third_party/WebKit/Source/core/editing/InputMethodController.cpp b/third_party/WebKit/Source/core/editing/InputMethodController.cpp index a647beb5..c4e039d5 100644 --- a/third_party/WebKit/Source/core/editing/InputMethodController.cpp +++ b/third_party/WebKit/Source/core/editing/InputMethodController.cpp
@@ -393,7 +393,7 @@ Clear(); - if (!MoveCaret(composition_range.end())) + if (!MoveCaret(composition_range.End())) return false; DispatchCompositionEndEvent(GetFrame(), composing); @@ -891,7 +891,7 @@ do { if (!SetSelectionOffsets(PlainTextRange( std::max(static_cast<int>(selection_offsets.Start()) - before, 0), - selection_offsets.end() + after))) + selection_offsets.End() + after))) return; if (before == 0) break; @@ -929,7 +929,7 @@ if (!root_editable_element) return; int selection_start = static_cast<int>(selection_offsets.Start()); - int selection_end = static_cast<int>(selection_offsets.end()); + int selection_end = static_cast<int>(selection_offsets.End()); // Select the text to be deleted before SelectionState::kStart. if (before > 0 && selection_start > 0) { @@ -966,7 +966,7 @@ if (valid_range.IsNull()) return; const int end = - PlainTextRange::Create(*root_editable_element, valid_range).end(); + PlainTextRange::Create(*root_editable_element, valid_range).End(); const Position& position = valid_range.EndPosition(); // Adjust the end of selection for multi-code text. TODO(yabinh): Adjustment @@ -1008,7 +1008,7 @@ return DeleteSurroundingText(before, after); const int selection_start = static_cast<int>(selection_offsets.Start()); - const int selection_end = static_cast<int>(selection_offsets.end()); + const int selection_end = static_cast<int>(selection_offsets.End()); const int before_length = CalculateBeforeDeletionLengthsInCodePoints(text, before, selection_start); @@ -1069,7 +1069,7 @@ PlainTextRange::Create(*element, first_range)); if (plain_text_range.IsNotNull()) { info.selection_start = plain_text_range.Start(); - info.selection_end = plain_text_range.end(); + info.selection_end = plain_text_range.End(); } } @@ -1078,7 +1078,7 @@ PlainTextRange plain_text_range(PlainTextRange::Create(*element, range)); if (plain_text_range.IsNotNull()) { info.composition_start = plain_text_range.Start(); - info.composition_end = plain_text_range.end(); + info.composition_end = plain_text_range.End(); } }
diff --git a/third_party/WebKit/Source/core/editing/InputMethodControllerTest.cpp b/third_party/WebKit/Source/core/editing/InputMethodControllerTest.cpp index 1deae42..7861704 100644 --- a/third_party/WebKit/Source/core/editing/InputMethodControllerTest.cpp +++ b/third_party/WebKit/Source/core/editing/InputMethodControllerTest.cpp
@@ -181,7 +181,7 @@ PlainTextRange plain_text_range(PlainTextRange::Create(*div, *range)); EXPECT_EQ(0u, plain_text_range.Start()); - EXPECT_EQ(5u, plain_text_range.end()); + EXPECT_EQ(5u, plain_text_range.End()); } TEST_F(InputMethodControllerTest, SetCompositionAfterEmoji) { @@ -225,7 +225,7 @@ String::FromUTF8("\xE0\xA4\xB9\xE0\xA5\x87\xE0\xA4\xB2\xE0\xA4\xB2"), underlines, 4, 4); EXPECT_EQ(4u, Controller().GetSelectionOffsets().Start()); - EXPECT_EQ(4u, Controller().GetSelectionOffsets().end()); + EXPECT_EQ(4u, Controller().GetSelectionOffsets().End()); // UTF16 = 0x0939 0x0947 0x0932 0x094D 0x0932 0x094B. Controller().SetComposition( @@ -233,7 +233,7 @@ "\xA4\xB2\xE0\xA5\x8B"), underlines, 6, 6); EXPECT_EQ(6u, Controller().GetSelectionOffsets().Start()); - EXPECT_EQ(6u, Controller().GetSelectionOffsets().end()); + EXPECT_EQ(6u, Controller().GetSelectionOffsets().End()); } TEST_F(InputMethodControllerTest, @@ -259,7 +259,7 @@ "\x8B\nab c", div->innerText().Utf8().data()); EXPECT_EQ(11u, Controller().GetSelectionOffsets().Start()); - EXPECT_EQ(11u, Controller().GetSelectionOffsets().end()); + EXPECT_EQ(11u, Controller().GetSelectionOffsets().End()); Controller().SetComposition(String("cd"), underlines, 2, 2); EXPECT_STREQ( @@ -267,7 +267,7 @@ "\x8B\nab cd", div->innerText().Utf8().data()); EXPECT_EQ(12u, Controller().GetSelectionOffsets().Start()); - EXPECT_EQ(12u, Controller().GetSelectionOffsets().end()); + EXPECT_EQ(12u, Controller().GetSelectionOffsets().End()); } TEST_F(InputMethodControllerTest, SetCompositionKeepingStyle) { @@ -285,14 +285,14 @@ EXPECT_STREQ("abc1<b>2</b>3457<b>8</b>9d<b>e</b>f", div->innerHTML().Utf8().data()); EXPECT_EQ(11u, Controller().GetSelectionOffsets().Start()); - EXPECT_EQ(11u, Controller().GetSelectionOffsets().end()); + EXPECT_EQ(11u, Controller().GetSelectionOffsets().End()); // Append a character. Controller().SetComposition(String("123456789"), underlines, 9, 9); EXPECT_STREQ("abc1<b>2</b>34567<b>8</b>9d<b>e</b>f", div->innerHTML().Utf8().data()); EXPECT_EQ(12u, Controller().GetSelectionOffsets().Start()); - EXPECT_EQ(12u, Controller().GetSelectionOffsets().end()); + EXPECT_EQ(12u, Controller().GetSelectionOffsets().End()); // Subtract and append characters. Controller().SetComposition(String("123hello789"), underlines, 11, 11); @@ -464,7 +464,7 @@ PlainTextRange plain_text_range(PlainTextRange::Create(*div, *range)); EXPECT_EQ(0u, plain_text_range.Start()); - EXPECT_EQ(5u, plain_text_range.end()); + EXPECT_EQ(5u, plain_text_range.End()); } TEST_F(InputMethodControllerTest, @@ -787,22 +787,22 @@ Controller().SetEditableSelectionOffsets(PlainTextRange(8, 8)); EXPECT_STREQ("aaa\nbbb\nccc\nddd\neee", div->innerText().Utf8().data()); EXPECT_EQ(8u, Controller().GetSelectionOffsets().Start()); - EXPECT_EQ(8u, Controller().GetSelectionOffsets().end()); + EXPECT_EQ(8u, Controller().GetSelectionOffsets().End()); Controller().DeleteSurroundingText(1, 0); EXPECT_STREQ("aaa\nbbbccc\nddd\neee", div->innerText().Utf8().data()); EXPECT_EQ(7u, Controller().GetSelectionOffsets().Start()); - EXPECT_EQ(7u, Controller().GetSelectionOffsets().end()); + EXPECT_EQ(7u, Controller().GetSelectionOffsets().End()); Controller().DeleteSurroundingText(0, 4); EXPECT_STREQ("aaa\nbbbddd\neee", div->innerText().Utf8().data()); EXPECT_EQ(7u, Controller().GetSelectionOffsets().Start()); - EXPECT_EQ(7u, Controller().GetSelectionOffsets().end()); + EXPECT_EQ(7u, Controller().GetSelectionOffsets().End()); Controller().DeleteSurroundingText(5, 5); EXPECT_STREQ("aaee", div->innerText().Utf8().data()); EXPECT_EQ(2u, Controller().GetSelectionOffsets().Start()); - EXPECT_EQ(2u, Controller().GetSelectionOffsets().end()); + EXPECT_EQ(2u, Controller().GetSelectionOffsets().End()); } TEST_F(InputMethodControllerTest, @@ -883,7 +883,7 @@ Controller().DeleteSurroundingTextInCodePoints(1, 1); EXPECT_STREQ("aaabb", div->innerText().Utf8().data()); EXPECT_EQ(3u, Controller().GetSelectionOffsets().Start()); - EXPECT_EQ(3u, Controller().GetSelectionOffsets().end()); + EXPECT_EQ(3u, Controller().GetSelectionOffsets().End()); } TEST_F(InputMethodControllerTest, @@ -933,7 +933,7 @@ Controller().SetEditableSelectionOffsets(PlainTextRange(2, 2)); EXPECT_STREQ("hello", input->value().Utf8().data()); EXPECT_EQ(2u, Controller().GetSelectionOffsets().Start()); - EXPECT_EQ(2u, Controller().GetSelectionOffsets().end()); + EXPECT_EQ(2u, Controller().GetSelectionOffsets().End()); Vector<CompositionUnderline> underlines; underlines.push_back(CompositionUnderline(0, 2, Color(255, 0, 0), false, 0)); @@ -943,42 +943,42 @@ Controller().SetComposition("AB", underlines, -100, -100); EXPECT_STREQ("heABllo", input->value().Utf8().data()); EXPECT_EQ(0u, Controller().GetSelectionOffsets().Start()); - EXPECT_EQ(0u, Controller().GetSelectionOffsets().end()); + EXPECT_EQ(0u, Controller().GetSelectionOffsets().End()); // The caret is on left boundary. // "*heABllo". Controller().SetComposition("AB", underlines, -2, -2); EXPECT_STREQ("heABllo", input->value().Utf8().data()); EXPECT_EQ(0u, Controller().GetSelectionOffsets().Start()); - EXPECT_EQ(0u, Controller().GetSelectionOffsets().end()); + EXPECT_EQ(0u, Controller().GetSelectionOffsets().End()); // The caret is before the composing text. // "he*ABllo". Controller().SetComposition("AB", underlines, 0, 0); EXPECT_STREQ("heABllo", input->value().Utf8().data()); EXPECT_EQ(2u, Controller().GetSelectionOffsets().Start()); - EXPECT_EQ(2u, Controller().GetSelectionOffsets().end()); + EXPECT_EQ(2u, Controller().GetSelectionOffsets().End()); // The caret is after the composing text. // "heAB*llo". Controller().SetComposition("AB", underlines, 2, 2); EXPECT_STREQ("heABllo", input->value().Utf8().data()); EXPECT_EQ(4u, Controller().GetSelectionOffsets().Start()); - EXPECT_EQ(4u, Controller().GetSelectionOffsets().end()); + EXPECT_EQ(4u, Controller().GetSelectionOffsets().End()); // The caret is on right boundary. // "heABllo*". Controller().SetComposition("AB", underlines, 5, 5); EXPECT_STREQ("heABllo", input->value().Utf8().data()); EXPECT_EQ(7u, Controller().GetSelectionOffsets().Start()); - EXPECT_EQ(7u, Controller().GetSelectionOffsets().end()); + EXPECT_EQ(7u, Controller().GetSelectionOffsets().End()); // The caret exceeds right boundary. // "heABllo*". Controller().SetComposition("AB", underlines, 100, 100); EXPECT_STREQ("heABllo", input->value().Utf8().data()); EXPECT_EQ(7u, Controller().GetSelectionOffsets().Start()); - EXPECT_EQ(7u, Controller().GetSelectionOffsets().end()); + EXPECT_EQ(7u, Controller().GetSelectionOffsets().End()); } TEST_F(InputMethodControllerTest, @@ -997,7 +997,7 @@ Controller().SetEditableSelectionOffsets(PlainTextRange(17, 17)); EXPECT_STREQ("hello\nworld\n0123456789", div->innerText().Utf8().data()); EXPECT_EQ(17u, Controller().GetSelectionOffsets().Start()); - EXPECT_EQ(17u, Controller().GetSelectionOffsets().end()); + EXPECT_EQ(17u, Controller().GetSelectionOffsets().End()); Vector<CompositionUnderline> underlines; underlines.push_back(CompositionUnderline(0, 2, Color(255, 0, 0), false, 0)); @@ -1007,77 +1007,77 @@ Controller().SetComposition("AB", underlines, -100, -100); EXPECT_STREQ("hello\nworld\n01234AB56789", div->innerText().Utf8().data()); EXPECT_EQ(0u, Controller().GetSelectionOffsets().Start()); - EXPECT_EQ(0u, Controller().GetSelectionOffsets().end()); + EXPECT_EQ(0u, Controller().GetSelectionOffsets().End()); // The caret is on left boundary. // "*hello\nworld\n01234AB56789". Controller().SetComposition("AB", underlines, -17, -17); EXPECT_STREQ("hello\nworld\n01234AB56789", div->innerText().Utf8().data()); EXPECT_EQ(0u, Controller().GetSelectionOffsets().Start()); - EXPECT_EQ(0u, Controller().GetSelectionOffsets().end()); + EXPECT_EQ(0u, Controller().GetSelectionOffsets().End()); // The caret is in the 1st node. // "he*llo\nworld\n01234AB56789". Controller().SetComposition("AB", underlines, -15, -15); EXPECT_STREQ("hello\nworld\n01234AB56789", div->innerText().Utf8().data()); EXPECT_EQ(2u, Controller().GetSelectionOffsets().Start()); - EXPECT_EQ(2u, Controller().GetSelectionOffsets().end()); + EXPECT_EQ(2u, Controller().GetSelectionOffsets().End()); // The caret is on right boundary of the 1st node. // "hello*\nworld\n01234AB56789". Controller().SetComposition("AB", underlines, -12, -12); EXPECT_STREQ("hello\nworld\n01234AB56789", div->innerText().Utf8().data()); EXPECT_EQ(5u, Controller().GetSelectionOffsets().Start()); - EXPECT_EQ(5u, Controller().GetSelectionOffsets().end()); + EXPECT_EQ(5u, Controller().GetSelectionOffsets().End()); // The caret is on right boundary of the 2nd node. // "hello\n*world\n01234AB56789". Controller().SetComposition("AB", underlines, -11, -11); EXPECT_STREQ("hello\nworld\n01234AB56789", div->innerText().Utf8().data()); EXPECT_EQ(6u, Controller().GetSelectionOffsets().Start()); - EXPECT_EQ(6u, Controller().GetSelectionOffsets().end()); + EXPECT_EQ(6u, Controller().GetSelectionOffsets().End()); // The caret is on right boundary of the 3rd node. // "hello\nworld*\n01234AB56789". Controller().SetComposition("AB", underlines, -6, -6); EXPECT_STREQ("hello\nworld\n01234AB56789", div->innerText().Utf8().data()); EXPECT_EQ(11u, Controller().GetSelectionOffsets().Start()); - EXPECT_EQ(11u, Controller().GetSelectionOffsets().end()); + EXPECT_EQ(11u, Controller().GetSelectionOffsets().End()); // The caret is on right boundary of the 4th node. // "hello\nworld\n*01234AB56789". Controller().SetComposition("AB", underlines, -5, -5); EXPECT_STREQ("hello\nworld\n01234AB56789", div->innerText().Utf8().data()); EXPECT_EQ(12u, Controller().GetSelectionOffsets().Start()); - EXPECT_EQ(12u, Controller().GetSelectionOffsets().end()); + EXPECT_EQ(12u, Controller().GetSelectionOffsets().End()); // The caret is before the composing text. // "hello\nworld\n01234*AB56789". Controller().SetComposition("AB", underlines, 0, 0); EXPECT_STREQ("hello\nworld\n01234AB56789", div->innerText().Utf8().data()); EXPECT_EQ(17u, Controller().GetSelectionOffsets().Start()); - EXPECT_EQ(17u, Controller().GetSelectionOffsets().end()); + EXPECT_EQ(17u, Controller().GetSelectionOffsets().End()); // The caret is after the composing text. // "hello\nworld\n01234AB*56789". Controller().SetComposition("AB", underlines, 2, 2); EXPECT_STREQ("hello\nworld\n01234AB56789", div->innerText().Utf8().data()); EXPECT_EQ(19u, Controller().GetSelectionOffsets().Start()); - EXPECT_EQ(19u, Controller().GetSelectionOffsets().end()); + EXPECT_EQ(19u, Controller().GetSelectionOffsets().End()); // The caret is on right boundary. // "hello\nworld\n01234AB56789*". Controller().SetComposition("AB", underlines, 7, 7); EXPECT_STREQ("hello\nworld\n01234AB56789", div->innerText().Utf8().data()); EXPECT_EQ(24u, Controller().GetSelectionOffsets().Start()); - EXPECT_EQ(24u, Controller().GetSelectionOffsets().end()); + EXPECT_EQ(24u, Controller().GetSelectionOffsets().End()); // The caret exceeds right boundary. // "hello\nworld\n01234AB56789*". Controller().SetComposition("AB", underlines, 100, 100); EXPECT_STREQ("hello\nworld\n01234AB56789", div->innerText().Utf8().data()); EXPECT_EQ(24u, Controller().GetSelectionOffsets().Start()); - EXPECT_EQ(24u, Controller().GetSelectionOffsets().end()); + EXPECT_EQ(24u, Controller().GetSelectionOffsets().End()); } TEST_F(InputMethodControllerTest, SetCompositionWithEmptyText) { @@ -1087,7 +1087,7 @@ Controller().SetEditableSelectionOffsets(PlainTextRange(2, 2)); EXPECT_STREQ("hello", div->innerText().Utf8().data()); EXPECT_EQ(2u, Controller().GetSelectionOffsets().Start()); - EXPECT_EQ(2u, Controller().GetSelectionOffsets().end()); + EXPECT_EQ(2u, Controller().GetSelectionOffsets().End()); Vector<CompositionUnderline> underlines0; underlines0.push_back(CompositionUnderline(0, 0, Color(255, 0, 0), false, 0)); @@ -1099,13 +1099,13 @@ Controller().SetComposition("", underlines0, 2, 2); EXPECT_STREQ("hello", div->innerText().Utf8().data()); EXPECT_EQ(4u, Controller().GetSelectionOffsets().Start()); - EXPECT_EQ(4u, Controller().GetSelectionOffsets().end()); + EXPECT_EQ(4u, Controller().GetSelectionOffsets().End()); // Without previous composition. Controller().SetComposition("", underlines0, -1, -1); EXPECT_STREQ("hello", div->innerText().Utf8().data()); EXPECT_EQ(3u, Controller().GetSelectionOffsets().Start()); - EXPECT_EQ(3u, Controller().GetSelectionOffsets().end()); + EXPECT_EQ(3u, Controller().GetSelectionOffsets().End()); } TEST_F(InputMethodControllerTest, InsertLineBreakWhileComposingText) { @@ -1117,12 +1117,12 @@ Controller().SetComposition("hello", underlines, 5, 5); EXPECT_STREQ("hello", div->innerText().Utf8().data()); EXPECT_EQ(5u, Controller().GetSelectionOffsets().Start()); - EXPECT_EQ(5u, Controller().GetSelectionOffsets().end()); + EXPECT_EQ(5u, Controller().GetSelectionOffsets().End()); GetFrame().GetEditor().InsertLineBreak(); EXPECT_STREQ("\n\n", div->innerText().Utf8().data()); EXPECT_EQ(1u, Controller().GetSelectionOffsets().Start()); - EXPECT_EQ(1u, Controller().GetSelectionOffsets().end()); + EXPECT_EQ(1u, Controller().GetSelectionOffsets().End()); } TEST_F(InputMethodControllerTest, InsertLineBreakAfterConfirmingText) { @@ -1136,12 +1136,12 @@ Controller().SetEditableSelectionOffsets(PlainTextRange(2, 2)); EXPECT_EQ(2u, Controller().GetSelectionOffsets().Start()); - EXPECT_EQ(2u, Controller().GetSelectionOffsets().end()); + EXPECT_EQ(2u, Controller().GetSelectionOffsets().End()); GetFrame().GetEditor().InsertLineBreak(); EXPECT_STREQ("he\nllo", div->innerText().Utf8().data()); EXPECT_EQ(3u, Controller().GetSelectionOffsets().Start()); - EXPECT_EQ(3u, Controller().GetSelectionOffsets().end()); + EXPECT_EQ(3u, Controller().GetSelectionOffsets().End()); } TEST_F(InputMethodControllerTest, CompositionInputEventIsComposing) { @@ -1297,7 +1297,7 @@ Controller().SetComposition("hello", underlines, 1, 1); GetDocument().UpdateStyleAndLayout(); EXPECT_EQ(1u, Controller().GetSelectionOffsets().Start()); - EXPECT_EQ(1u, Controller().GetSelectionOffsets().end()); + EXPECT_EQ(1u, Controller().GetSelectionOffsets().End()); // Confirm the ongoing composition. Note that it moves the caret to the end of // text [5,5] before firing 'compositonend' event.
diff --git a/third_party/WebKit/Source/core/editing/PlainTextRange.cpp b/third_party/WebKit/Source/core/editing/PlainTextRange.cpp index 2a7f62a..849d7e4 100644 --- a/third_party/WebKit/Source/core/editing/PlainTextRange.cpp +++ b/third_party/WebKit/Source/core/editing/PlainTextRange.cpp
@@ -97,7 +97,7 @@ bool found_start = Start() >= doc_text_position && Start() <= doc_text_position + len; bool found_end = - end() >= doc_text_position && end() <= doc_text_position + len; + End() >= doc_text_position && End() <= doc_text_position + len; // Fix textRunRange->endPosition(), but only if foundStart || foundEnd, // because it is only in those cases that textRunRange is used. @@ -137,12 +137,12 @@ if (found_end) { if (text_run_start_position.ComputeContainerNode()->IsTextNode()) { - int offset = end() - doc_text_position; + int offset = End() - doc_text_position; result_end = Position(text_run_start_position.ComputeContainerNode(), offset + text_run_start_position.OffsetInContainerNode()); } else { - if (end() == doc_text_position) + if (End() == doc_text_position) result_end = text_run_start_position; else result_end = text_run_end_position; @@ -156,7 +156,7 @@ if (!start_range_found) return EphemeralRange(); - if (length() && end() > doc_text_position) { // end() is out of bounds + if (length() && End() > doc_text_position) { // End() is out of bounds result_end = text_run_end_position; }
diff --git a/third_party/WebKit/Source/core/editing/PlainTextRange.h b/third_party/WebKit/Source/core/editing/PlainTextRange.h index 255d851..93505b78 100644 --- a/third_party/WebKit/Source/core/editing/PlainTextRange.h +++ b/third_party/WebKit/Source/core/editing/PlainTextRange.h
@@ -47,7 +47,7 @@ explicit PlainTextRange(int location); PlainTextRange(int start, int end); - size_t end() const { + size_t End() const { DCHECK(IsNotNull()); return end_; }
diff --git a/third_party/WebKit/Source/core/editing/SurroundingText.cpp b/third_party/WebKit/Source/core/editing/SurroundingText.cpp index 4a7d5f09..68e561e 100644 --- a/third_party/WebKit/Source/core/editing/SurroundingText.cpp +++ b/third_party/WebKit/Source/core/editing/SurroundingText.cpp
@@ -33,6 +33,7 @@ #include "core/dom/Document.h" #include "core/dom/Element.h" #include "core/dom/Range.h" +#include "core/editing/EditingUtilities.h" #include "core/editing/Position.h" #include "core/editing/iterators/BackwardsCharacterIterator.h" #include "core/editing/iterators/CharacterIterator.h" @@ -63,12 +64,17 @@ DCHECK(!document->NeedsLayoutTreeUpdate()); // The forward range starts at the selection end and ends at the document's - // end. It will then be updated to only contain the text in the text in the - // right range around the selection. + // or the input element's end. It will then be updated to only contain the + // text in the right range around the selection. + DCHECK_EQ(RootEditableElementOf(start_position), + RootEditableElementOf(end_position)); + Element* const root_editable = RootEditableElementOf(start_position); + Element* const root_element = + root_editable ? root_editable : document->documentElement(); + CharacterIterator forward_iterator( end_position, - Position::LastPositionInNode(document->documentElement()) - .ParentAnchoredEquivalent(), + Position::LastPositionInNode(root_element).ParentAnchoredEquivalent(), TextIteratorBehavior::Builder().SetStopsOnFormControls(true).Build()); // FIXME: why do we stop going trough the text if we were not able to select // something on the right? @@ -83,11 +89,10 @@ return; // Same as with the forward range but with the backward range. The range - // starts at the document's start and ends at the selection start and will - // be updated. + // starts at the document's or input element's start and ends at the selection + // start and will be updated. BackwardsCharacterIterator backwards_iterator( - Position::FirstPositionInNode(document->documentElement()) - .ParentAnchoredEquivalent(), + Position::FirstPositionInNode(root_element).ParentAnchoredEquivalent(), start_position, TextIteratorBehavior::Builder().SetStopsOnFormControls(true).Build()); if (!backwards_iterator.AtEnd())
diff --git a/third_party/WebKit/Source/core/editing/SurroundingTextTest.cpp b/third_party/WebKit/Source/core/editing/SurroundingTextTest.cpp index acb6dfc..2fe38bf 100644 --- a/third_party/WebKit/Source/core/editing/SurroundingTextTest.cpp +++ b/third_party/WebKit/Source/core/editing/SurroundingTextTest.cpp
@@ -4,15 +4,16 @@ #include "core/editing/SurroundingText.h" +#include <memory> #include "core/dom/Document.h" #include "core/dom/Range.h" #include "core/dom/Text.h" #include "core/editing/Position.h" #include "core/editing/VisibleSelection.h" #include "core/html/HTMLElement.h" +#include "core/html/TextControlElement.h" #include "core/testing/DummyPageHolder.h" #include "testing/gtest/include/gtest/gtest.h" -#include <memory> namespace blink { @@ -276,4 +277,24 @@ } } +TEST_F(SurroundingTextTest, TextAreaSelection) { + SetHTML( + String("<p>First paragraph</p>" + "<textarea id='selection'>abc def ghi</textarea>" + "<p>Second paragraph</p>")); + + TextControlElement* text_ctrl = + (TextControlElement*)GetDocument().getElementById("selection"); + + text_ctrl->SetSelectionRange(4, 7); + VisibleSelection selection = CreateVisibleSelection(text_ctrl->Selection()); + + SurroundingText surrounding_text( + *CreateRange(FirstEphemeralRangeOf(selection)), 20); + + EXPECT_EQ("abc def ghi", surrounding_text.Content().SimplifyWhiteSpace()); + EXPECT_EQ(4u, surrounding_text.StartOffsetInContent()); + EXPECT_EQ(7u, surrounding_text.EndOffsetInContent()); +} + } // namespace blink
diff --git a/third_party/WebKit/Source/core/exported/BUILD.gn b/third_party/WebKit/Source/core/exported/BUILD.gn index ddb86f1..11f0cdb 100644 --- a/third_party/WebKit/Source/core/exported/BUILD.gn +++ b/third_party/WebKit/Source/core/exported/BUILD.gn
@@ -60,6 +60,8 @@ "WebSerializedScriptValue.cpp", "WebSettingsImpl.cpp", "WebSettingsImpl.h", + "WebSharedWorkerImpl.cpp", + "WebSharedWorkerImpl.h", "WebTextCheckingCompletionImpl.cpp", "WebTextCheckingCompletionImpl.h", "WebTextCheckingResult.cpp",
diff --git a/third_party/WebKit/Source/core/exported/WebFactory.h b/third_party/WebKit/Source/core/exported/WebFactory.h index db544cc..9ec794f 100644 --- a/third_party/WebKit/Source/core/exported/WebFactory.h +++ b/third_party/WebKit/Source/core/exported/WebFactory.h
@@ -12,7 +12,13 @@ class ChromeClient; class WebViewBase; +class WebLocalFrameBase; class WebViewClient; +class WebFrameClient; +class InterfaceProvider; +class InterfaceRegistry; +class WebFrame; +enum class WebTreeScopeType; // WebFactory is a temporary class implemented in web/ that allows classes to // construct interfaces that are being moved out of web/. @@ -24,6 +30,12 @@ virtual ChromeClient* CreateChromeClient(WebViewBase*) const = 0; virtual WebViewBase* CreateWebViewBase(WebViewClient*, WebPageVisibilityState) const = 0; + virtual WebLocalFrameBase* CreateWebLocalFrameBase( + WebTreeScopeType, + WebFrameClient*, + blink::InterfaceProvider*, + blink::InterfaceRegistry*, + WebFrame* opener = nullptr) const = 0; protected: // Takes ownership of |factory|.
diff --git a/third_party/WebKit/Source/core/exported/WebRange.cpp b/third_party/WebKit/Source/core/exported/WebRange.cpp index 4b8f411..a9ead67 100644 --- a/third_party/WebKit/Source/core/exported/WebRange.cpp +++ b/third_party/WebKit/Source/core/exported/WebRange.cpp
@@ -57,7 +57,7 @@ return; start_ = range.Start(); - end_ = range.end(); + end_ = range.End(); } EphemeralRange WebRange::CreateEphemeralRange(LocalFrame* frame) const {
diff --git a/third_party/WebKit/Source/web/WebSharedWorkerImpl.cpp b/third_party/WebKit/Source/core/exported/WebSharedWorkerImpl.cpp similarity index 93% rename from third_party/WebKit/Source/web/WebSharedWorkerImpl.cpp rename to third_party/WebKit/Source/core/exported/WebSharedWorkerImpl.cpp index a826c24..4829895 100644 --- a/third_party/WebKit/Source/web/WebSharedWorkerImpl.cpp +++ b/third_party/WebKit/Source/core/exported/WebSharedWorkerImpl.cpp
@@ -28,13 +28,15 @@ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -#include "web/WebSharedWorkerImpl.h" +#include "core/exported/WebSharedWorkerImpl.h" #include <memory> #include "core/dom/Document.h" #include "core/dom/TaskRunnerHelper.h" #include "core/events/MessageEvent.h" #include "core/exported/WebDataSourceImpl.h" +#include "core/exported/WebFactory.h" +#include "core/exported/WebViewBase.h" #include "core/frame/WebLocalFrameBase.h" #include "core/inspector/ConsoleMessage.h" #include "core/loader/FrameLoadRequest.h" @@ -73,11 +75,21 @@ #include "public/web/WebSettings.h" #include "public/web/WebView.h" #include "public/web/WebWorkerContentSettingsClientProxy.h" -#include "web/IndexedDBClientImpl.h" -#include "web/LocalFileSystemClient.h" namespace blink { +namespace { + +// Vector of callbacks for the OnScriptLoaderFinished method. +using WorkerClientsCreatedCallbackVector = + WTF::Vector<WebSharedWorkerImpl::WorkerClientsCreatedCallback>; +WorkerClientsCreatedCallbackVector& GetWorkerClientsCreatedCallbackVector() { + DEFINE_STATIC_LOCAL(WorkerClientsCreatedCallbackVector, callback_vector, ()); + return callback_vector; +} + +} // namespace + // TODO(toyoshim): Share implementation with WebEmbeddedWorkerImpl as much as // possible. @@ -127,7 +139,8 @@ // loading requests from the worker context to the rest of WebKit and Chromium // infrastructure. DCHECK(!web_view_); - web_view_ = WebView::Create(nullptr, kWebPageVisibilityStateVisible); + web_view_ = WebFactory::GetInstance().CreateWebViewBase( + nullptr, kWebPageVisibilityStateVisible); // FIXME: http://crbug.com/363843. This needs to find a better way to // not create graphics layers. web_view_->GetSettings()->SetAcceleratedCompositingEnabled(false); @@ -135,9 +148,9 @@ // FIXME: Settings information should be passed to the Worker process from // Browser process when the worker is created (similar to // RenderThread::OnCreateNewView). - main_frame_ = ToWebLocalFrameBase(WebLocalFrame::Create( + main_frame_ = WebFactory::GetInstance().CreateWebLocalFrameBase( WebTreeScopeType::kDocument, this, - Platform::Current()->GetInterfaceProvider(), nullptr)); + Platform::Current()->GetInterfaceProvider(), nullptr); web_view_->SetMainFrame(main_frame_.Get()); main_frame_->SetDevToolsAgentClient(this); @@ -250,6 +263,11 @@ delete this; } +void WebSharedWorkerImpl::RegisterWorkerClientsCreatedCallback( + WorkerClientsCreatedCallback callback) { + GetWorkerClientsCreatedCallbackVector().push_back(callback); +} + void WebSharedWorkerImpl::Connect( std::unique_ptr<WebMessagePortChannel> web_channel) { DCHECK(IsMainThread()); @@ -320,15 +338,16 @@ SecurityOrigin* starter_origin = loading_document_->GetSecurityOrigin(); WorkerClients* worker_clients = WorkerClients::Create(); - ProvideLocalFileSystemToWorker(worker_clients, - LocalFileSystemClient::Create()); + DCHECK(!GetWorkerClientsCreatedCallbackVector().IsEmpty()); + for (auto& callback : GetWorkerClientsCreatedCallbackVector()) { + callback(worker_clients); + } + WebSecurityOrigin web_security_origin(loading_document_->GetSecurityOrigin()); ProvideContentSettingsClientToWorker( worker_clients, WTF::WrapUnique(client_->CreateWorkerContentSettingsClientProxy( web_security_origin))); - ProvideIndexedDBClientToWorker(worker_clients, - IndexedDBClientImpl::Create(*worker_clients)); if (RuntimeEnabledFeatures::OffMainThreadFetchEnabled()) { std::unique_ptr<WebWorkerFetchContext> web_worker_fetch_context = @@ -427,9 +446,10 @@ if (asked_to_terminate_) return; WebDevToolsAgent* devtools_agent = main_frame_->DevToolsAgent(); - if (devtools_agent) + if (devtools_agent) { devtools_agent->DispatchOnInspectorBackend(session_id, call_id, method, message); + } } WebSharedWorker* WebSharedWorker::Create(WebSharedWorkerClient* client) {
diff --git a/third_party/WebKit/Source/web/WebSharedWorkerImpl.h b/third_party/WebKit/Source/core/exported/WebSharedWorkerImpl.h similarity index 91% rename from third_party/WebKit/Source/web/WebSharedWorkerImpl.h rename to third_party/WebKit/Source/core/exported/WebSharedWorkerImpl.h index f6460fd..c57d38b3 100644 --- a/third_party/WebKit/Source/web/WebSharedWorkerImpl.h +++ b/third_party/WebKit/Source/core/exported/WebSharedWorkerImpl.h
@@ -34,7 +34,9 @@ #include "public/web/WebSharedWorker.h" #include <memory> +#include "core/CoreExport.h" #include "core/dom/ExecutionContext.h" +#include "core/workers/WebSharedWorkerReportingProxyImpl.h" #include "core/workers/WorkerThread.h" #include "platform/wtf/RefPtr.h" #include "public/platform/Platform.h" @@ -43,7 +45,6 @@ #include "public/web/WebDevToolsAgentClient.h" #include "public/web/WebFrameClient.h" #include "public/web/WebSharedWorkerClient.h" -#include "web/WebSharedWorkerReportingProxyImpl.h" namespace blink { @@ -55,6 +56,7 @@ class WebString; class WebURL; class WebView; +class WorkerClients; class WorkerInspectorProxy; class WorkerScriptLoader; @@ -115,6 +117,14 @@ void DidCloseWorkerGlobalScope(); void DidTerminateWorkerThread(); + using WorkerClientsCreatedCallback = void (*)(WorkerClients*); + // Allows for the registration of a callback that is invoked whenever a new + // OnScriptLoaderFinished is called. Callbacks are executed in the order that + // they were added using RegisterWorkerClientsCreatedCallback, and there are + // no checks for adding a callback multiple times. + CORE_EXPORT static void RegisterWorkerClientsCreatedCallback( + WorkerClientsCreatedCallback); + private: ~WebSharedWorkerImpl() override;
diff --git a/third_party/WebKit/Source/core/frame/LocalFrameView.cpp b/third_party/WebKit/Source/core/frame/LocalFrameView.cpp index bd3893d6..66a43d9c 100644 --- a/third_party/WebKit/Source/core/frame/LocalFrameView.cpp +++ b/third_party/WebKit/Source/core/frame/LocalFrameView.cpp
@@ -159,17 +159,6 @@ namespace blink { -namespace { - -void SetNeedsCompositingUpdate(blink::LayoutViewItem layout_view_item, - blink::CompositingUpdateType update_type) { - if (PaintLayerCompositor* compositor = - !layout_view_item.IsNull() ? layout_view_item.Compositor() : nullptr) - compositor->SetNeedsCompositingUpdate(update_type); -} - -} // namespace - using namespace HTMLNames; // The maximum number of updatePlugins iterations that should be done before @@ -2139,6 +2128,12 @@ } } +void LocalFrameView::SetNeedsCompositingUpdate( + CompositingUpdateType update_type) { + if (!GetLayoutViewItem().IsNull() && frame_->GetDocument()->IsActive()) + GetLayoutViewItem().Compositor()->SetNeedsCompositingUpdate(update_type); +} + PlatformChromeClient* LocalFrameView::GetChromeClient() const { Page* page = GetFrame().GetPage(); if (!page) @@ -2928,8 +2923,7 @@ // Being the global root scroller will affect clipping size due to browser // controls behavior so we need to update compositing based on updated clip // geometry. - LayoutViewItem view = GetLayoutViewItem(); - SetNeedsCompositingUpdate(view, kCompositingUpdateAfterGeometryChange); + SetNeedsCompositingUpdate(kCompositingUpdateAfterGeometryChange); if (RuntimeEnabledFeatures::SlimmingPaintInvalidationEnabled()) SetNeedsPaintPropertyUpdate(); @@ -4817,7 +4811,7 @@ // As parent visibility changes, we may need to recomposite this frame view // and potentially child frame views. - SetNeedsCompositingUpdate(GetLayoutViewItem(), kCompositingUpdateRebuildTree); + SetNeedsCompositingUpdate(kCompositingUpdateRebuildTree); parent_visible_ = visible; @@ -4835,8 +4829,7 @@ if (ScrollingCoordinator* scrolling_coordinator = this->GetScrollingCoordinator()) scrolling_coordinator->FrameViewVisibilityDidChange(); - SetNeedsCompositingUpdate(GetLayoutViewItem(), - kCompositingUpdateRebuildTree); + SetNeedsCompositingUpdate(kCompositingUpdateRebuildTree); UpdateParentScrollableAreaSet(); if (RuntimeEnabledFeatures::SlimmingPaintInvalidationEnabled() && !RuntimeEnabledFeatures::RootLayerScrollingEnabled()) { @@ -4863,8 +4856,7 @@ if (ScrollingCoordinator* scrolling_coordinator = this->GetScrollingCoordinator()) scrolling_coordinator->FrameViewVisibilityDidChange(); - SetNeedsCompositingUpdate(GetLayoutViewItem(), - kCompositingUpdateRebuildTree); + SetNeedsCompositingUpdate(kCompositingUpdateRebuildTree); UpdateParentScrollableAreaSet(); if (RuntimeEnabledFeatures::SlimmingPaintInvalidationEnabled() && !RuntimeEnabledFeatures::RootLayerScrollingEnabled()) {
diff --git a/third_party/WebKit/Source/core/frame/LocalFrameView.h b/third_party/WebKit/Source/core/frame/LocalFrameView.h index c42da6d..e25e0c2 100644 --- a/third_party/WebKit/Source/core/frame/LocalFrameView.h +++ b/third_party/WebKit/Source/core/frame/LocalFrameView.h
@@ -35,6 +35,7 @@ #include "core/frame/RootFrameViewport.h" #include "core/layout/MapCoordinatesFlags.h" #include "core/layout/ScrollAnchor.h" +#include "core/layout/compositing/PaintLayerCompositor.h" #include "core/paint/FirstMeaningfulPaintDetector.h" #include "core/paint/ObjectPaintProperties.h" #include "core/paint/PaintInvalidationCapableScrollableArea.h" @@ -982,6 +983,7 @@ static bool ComputeCompositedSelection(LocalFrame&, CompositedSelection&); void UpdateCompositedSelectionIfNeeded(); + void SetNeedsCompositingUpdate(CompositingUpdateType); // Returns true if the LocalFrameView's own scrollbars overlay its content // when visible.
diff --git a/third_party/WebKit/Source/core/html/HTMLFrameOwnerElement.cpp b/third_party/WebKit/Source/core/html/HTMLFrameOwnerElement.cpp index 58d0410c..d344531 100644 --- a/third_party/WebKit/Source/core/html/HTMLFrameOwnerElement.cpp +++ b/third_party/WebKit/Source/core/html/HTMLFrameOwnerElement.cpp
@@ -40,25 +40,9 @@ namespace blink { -using FrameOrPluginToParentMap = - HeapHashMap<Member<FrameOrPlugin>, Member<LocalFrameView>>; - -static FrameOrPluginToParentMap& FrameOrPluginNewParentMap() { - DEFINE_STATIC_LOCAL(FrameOrPluginToParentMap, map, - (new FrameOrPluginToParentMap)); - return map; -} - -using FrameOrPluginSet = HeapHashSet<Member<FrameOrPlugin>>; -static FrameOrPluginSet& FrameOrPluginsPendingTemporaryRemovalFromParent() { - // FrameOrPlugins in this set will not leak because it will be cleared in - // HTMLFrameOwnerElement::UpdateSuspendScope::performDeferredWidgetTreeOperations. - DEFINE_STATIC_LOCAL(FrameOrPluginSet, set, (new FrameOrPluginSet)); - return set; -} - -static FrameOrPluginSet& FrameOrPluginsPendingDispose() { - DEFINE_STATIC_LOCAL(FrameOrPluginSet, set, (new FrameOrPluginSet)); +using PluginSet = HeapHashSet<Member<PluginView>>; +static PluginSet& PluginsPendingDispose() { + DEFINE_STATIC_LOCAL(PluginSet, set, (new PluginSet)); return set; } @@ -68,76 +52,26 @@ return nodes; } -static unsigned g_update_suspend_count = 0; +static unsigned g_plugin_dispose_suspend_count = 0; -HTMLFrameOwnerElement::UpdateSuspendScope::UpdateSuspendScope() { - ++g_update_suspend_count; +HTMLFrameOwnerElement::PluginDisposeSuspendScope::PluginDisposeSuspendScope() { + ++g_plugin_dispose_suspend_count; } -void HTMLFrameOwnerElement::UpdateSuspendScope:: - PerformDeferredWidgetTreeOperations() { - FrameOrPluginToParentMap map; - FrameOrPluginNewParentMap().swap(map); - for (const auto& entry : map) { - FrameOrPlugin* child = entry.key; - bool current_attached = child->IsAttached(); - bool new_attached = entry.value; - if (new_attached != current_attached) { - if (current_attached) - child->Detach(); - - if (new_attached) - child->Attach(); - - if (current_attached && !new_attached) - child->Dispose(); - } - } - - FrameOrPluginSet remove_set; - FrameOrPluginsPendingTemporaryRemovalFromParent().swap(remove_set); - for (const auto& child : remove_set) { - if (child->IsAttached()) - child->Detach(); - } - - FrameOrPluginSet dispose_set; - FrameOrPluginsPendingDispose().swap(dispose_set); - for (const auto& frame_or_plugin : dispose_set) { - frame_or_plugin->Dispose(); +void HTMLFrameOwnerElement::PluginDisposeSuspendScope:: + PerformDeferredPluginDispose() { + PluginSet dispose_set; + PluginsPendingDispose().swap(dispose_set); + for (const auto& plugin : dispose_set) { + plugin->Dispose(); } } -HTMLFrameOwnerElement::UpdateSuspendScope::~UpdateSuspendScope() { - DCHECK_GT(g_update_suspend_count, 0u); - if (g_update_suspend_count == 1) - PerformDeferredWidgetTreeOperations(); - --g_update_suspend_count; -} - -// Unlike MoveFrameOrPluginToParentSoon, this will not call dispose. -void TemporarilyRemoveFrameOrPluginFromParentSoon(FrameOrPlugin* child) { - if (g_update_suspend_count) { - FrameOrPluginsPendingTemporaryRemovalFromParent().insert(child); - } else { - if (child->IsAttached()) - child->Detach(); - } -} - -void MoveFrameOrPluginToParentSoon(FrameOrPlugin* child, - LocalFrameView* parent) { - if (!g_update_suspend_count) { - if (parent) { - DCHECK(child != parent && !child->IsAttached()); - child->Attach(); - } else if (child->IsAttached()) { - child->Detach(); - child->Dispose(); - } - return; - } - FrameOrPluginNewParentMap().Set(child, parent); +HTMLFrameOwnerElement::PluginDisposeSuspendScope::~PluginDisposeSuspendScope() { + DCHECK_GT(g_plugin_dispose_suspend_count, 0u); + if (g_plugin_dispose_suspend_count == 1) + PerformDeferredPluginDispose(); + --g_plugin_dispose_suspend_count; } HTMLFrameOwnerElement::HTMLFrameOwnerElement(const QualifiedName& tag_name, @@ -224,13 +158,11 @@ return content_frame_ && HTMLElement::IsKeyboardFocusable(); } -void HTMLFrameOwnerElement::DisposeFrameOrPluginSoon( - FrameOrPlugin* frame_or_plugin) { - if (g_update_suspend_count) { - FrameOrPluginsPendingDispose().insert(frame_or_plugin); - } else { - frame_or_plugin->Dispose(); - } +void HTMLFrameOwnerElement::DisposePluginSoon(PluginView* plugin) { + if (g_plugin_dispose_suspend_count) + PluginsPendingDispose().insert(plugin); + else + plugin->Dispose(); } void HTMLFrameOwnerElement::UpdateContainerPolicy() { @@ -290,8 +222,13 @@ } if (widget_) { - if (widget_->IsAttached()) - MoveFrameOrPluginToParentSoon(widget_, nullptr); + if (widget_->IsAttached()) { + widget_->Detach(); + if (widget_->IsPluginView()) + DisposePluginSoon(ToPluginView(widget_)); + else + widget_->Dispose(); + } } widget_ = frame_or_plugin; @@ -307,7 +244,7 @@ DCHECK_EQ(GetDocument().View(), layout_part_item.GetFrameView()); DCHECK(layout_part_item.GetFrameView()); - MoveFrameOrPluginToParentSoon(widget_, layout_part_item.GetFrameView()); + widget_->Attach(); } if (AXObjectCache* cache = GetDocument().ExistingAXObjectCache()) @@ -318,7 +255,7 @@ if (!widget_) return nullptr; if (widget_->IsAttached()) - TemporarilyRemoveFrameOrPluginFromParentSoon(widget_); + widget_->Detach(); LayoutPart* layout_part = ToLayoutPart(GetLayoutObject()); if (layout_part) { if (AXObjectCache* cache = GetDocument().ExistingAXObjectCache())
diff --git a/third_party/WebKit/Source/core/html/HTMLFrameOwnerElement.h b/third_party/WebKit/Source/core/html/HTMLFrameOwnerElement.h index 57d3a7b..9860b3d 100644 --- a/third_party/WebKit/Source/core/html/HTMLFrameOwnerElement.h +++ b/third_party/WebKit/Source/core/html/HTMLFrameOwnerElement.h
@@ -38,6 +38,7 @@ class Frame; class FrameOrPlugin; class LayoutPart; +class PluginView; class CORE_EXPORT HTMLFrameOwnerElement : public HTMLElement, public FrameOwner { @@ -69,15 +70,15 @@ FrameOrPlugin* ReleaseWidget(); FrameOrPlugin* OwnedWidget() const { return widget_; } - class UpdateSuspendScope { + class PluginDisposeSuspendScope { STACK_ALLOCATED(); public: - UpdateSuspendScope(); - ~UpdateSuspendScope(); + PluginDisposeSuspendScope(); + ~PluginDisposeSuspendScope(); private: - void PerformDeferredWidgetTreeOperations(); + void PerformDeferredPluginDispose(); }; // FrameOwner overrides: @@ -115,7 +116,7 @@ bool replace_current_item); bool IsKeyboardFocusable() const override; - void DisposeFrameOrPluginSoon(FrameOrPlugin*); + void DisposePluginSoon(PluginView*); void FrameOwnerPropertiesChanged(); // Return the origin which is to be used for feature policy container
diff --git a/third_party/WebKit/Source/core/html/HTMLPlugInElement.cpp b/third_party/WebKit/Source/core/html/HTMLPlugInElement.cpp index ac7486f..655c7f2 100644 --- a/third_party/WebKit/Source/core/html/HTMLPlugInElement.cpp +++ b/third_party/WebKit/Source/core/html/HTMLPlugInElement.cpp
@@ -105,7 +105,7 @@ return; if (persisted_plugin_) { persisted_plugin_->Hide(); - DisposeFrameOrPluginSoon(persisted_plugin_.Release()); + DisposePluginSoon(persisted_plugin_.Release()); } persisted_plugin_ = plugin; } @@ -181,8 +181,7 @@ // If we don't have a layoutObject we have to dispose of any plugins // which we persisted over a reattach. if (persisted_plugin_) { - HTMLFrameOwnerElement::UpdateSuspendScope - suspend_widget_hierarchy_updates; + HTMLFrameOwnerElement::PluginDisposeSuspendScope suspend_plugin_dispose; SetPersistedPlugin(nullptr); } return; @@ -214,9 +213,9 @@ // If we've persisted the plugin and we're removed from the tree then // make sure we cleanup the persistance pointer. if (persisted_plugin_) { - // TODO(dcheng): This UpdateSuspendScope doesn't seem to provide much; - // investigate removing it. - HTMLFrameOwnerElement::UpdateSuspendScope suspend_widget_hierarchy_updates; + // TODO(dcheng): This PluginDisposeSuspendScope doesn't seem to provide + // much; investigate removing it. + HTMLFrameOwnerElement::PluginDisposeSuspendScope suspend_plugin_dispose; SetPersistedPlugin(nullptr); } HTMLFrameOwnerElement::RemovedFrom(insertion_point);
diff --git a/third_party/WebKit/Source/core/style/ComputedStyle.cpp b/third_party/WebKit/Source/core/style/ComputedStyle.cpp index cc91a2d..39005f6 100644 --- a/third_party/WebKit/Source/core/style/ComputedStyle.cpp +++ b/third_party/WebKit/Source/core/style/ComputedStyle.cpp
@@ -81,11 +81,6 @@ void* data_ref_svg_style; }; -// If this fails, the packing algorithm in make_computed_style_base.py has -// failed to produce the optimal packed size. To fix, update the algorithm to -// ensure that the buckets are placed so that each takes up at most 1 word. -ASSERT_SIZE(ComputedStyleBase<ComputedStyle>, SameSizeAsComputedStyleBase); - // If this assert fails, it means that size of ComputedStyle has changed. Please // check that you really *do* what to increase the size of ComputedStyle, then // update the SameSizeAsComputedStyle struct to match the updated storage of @@ -536,7 +531,7 @@ bool ComputedStyle::ScrollAnchorDisablingPropertyChanged( const ComputedStyle& other, const StyleDifference& diff) const { - if (ComputedStyleBase::ScrollAnchorDisablingPropertyChanged(other)) + if (ComputedStyleBase::ScrollAnchorDisablingPropertyChanged(*this, other)) return true; if (diff.TransformChanged()) @@ -554,7 +549,7 @@ // - or the layoutObject knows how to exactly invalidate paints caused by the // layout change instead of forced full paint invalidation. - if (ComputedStyleBase::DiffNeedsFullLayoutAndPaintInvalidation(other)) + if (ComputedStyleBase::DiffNeedsFullLayoutAndPaintInvalidation(*this, other)) return true; if (rare_non_inherited_data_.Get() != other.rare_non_inherited_data_.Get()) { @@ -634,7 +629,8 @@ if (IsDisplayTableType(Display())) { if (ComputedStyleBase:: - DiffNeedsFullLayoutAndPaintInvalidationDisplayTableType(other)) + DiffNeedsFullLayoutAndPaintInvalidationDisplayTableType(*this, + other)) return true; // In the collapsing border model, 'hidden' suppresses other borders, while @@ -659,7 +655,8 @@ return true; } else if (Display() == EDisplay::kListItem) { if (ComputedStyleBase:: - DiffNeedsFullLayoutAndPaintInvalidationDisplayListItem(other)) + DiffNeedsFullLayoutAndPaintInvalidationDisplayListItem(*this, + other)) return true; } @@ -674,7 +671,7 @@ } bool ComputedStyle::DiffNeedsFullLayout(const ComputedStyle& other) const { - if (ComputedStyleBase::DiffNeedsFullLayout(other)) + if (ComputedStyleBase::DiffNeedsFullLayout(*this, other)) return true; if (box_data_.Get() != other.box_data_.Get()) { @@ -729,7 +726,7 @@ bool ComputedStyle::DiffNeedsPaintInvalidationObject( const ComputedStyle& other) const { - if (ComputedStyleBase::DiffNeedsPaintInvalidationObject(other)) + if (ComputedStyleBase::DiffNeedsPaintInvalidationObject(*this, other)) return true; if (!BorderVisuallyEqual(other) || !RadiiEqual(other) || @@ -813,7 +810,7 @@ bool ComputedStyle::DiffNeedsVisualRectUpdate( const ComputedStyle& other) const { // Visual rect is empty if visibility is hidden. - if (ComputedStyleBase::DiffNeedsVisualRectUpdate(other)) + if (ComputedStyleBase::DiffNeedsVisualRectUpdate(*this, other)) return true; // Need to update visual rect of the resizer. @@ -889,7 +886,8 @@ other.rare_non_inherited_data_ ->visited_link_text_decoration_color_)) || ComputedStyleBase:: - UpdatePropertySpecificDifferencesTextDecorationOrColor(other)) { + UpdatePropertySpecificDifferencesTextDecorationOrColor(*this, + other)) { diff.SetTextDecorationOrColorChanged(); } }
diff --git a/third_party/WebKit/Source/core/style/ComputedStyle.h b/third_party/WebKit/Source/core/style/ComputedStyle.h index 6b139c0f..a8aacda 100644 --- a/third_party/WebKit/Source/core/style/ComputedStyle.h +++ b/third_party/WebKit/Source/core/style/ComputedStyle.h
@@ -180,10 +180,8 @@ // actually stored directly in ComputedStyle, but rather in a generated parent // class ComputedStyleBase. This separation of concerns allows us to optimise // the memory layout without affecting users of ComputedStyle. ComputedStyle -// inherits from ComputedStyleBase, which in turn takes ComputedStyle as a -// template argument so that ComputedStyleBase can access methods declared on -// ComputedStyle. For more about the memory layout, there is documentation in -// ComputedStyleBase and make_computed_style_base.py. +// inherits from ComputedStyleBase. For more about the memory layout, there is +// documentation in ComputedStyleBase and make_computed_style_base.py. // // INTERFACE: // @@ -206,11 +204,11 @@ // Currently, some properties are stored in ComputedStyle and some in // ComputedStyleBase. Eventually, the storage of all properties (except SVG // ones) will be in ComputedStyleBase. -class CORE_EXPORT ComputedStyle : public ComputedStyleBase<ComputedStyle>, +class CORE_EXPORT ComputedStyle : public ComputedStyleBase, public RefCounted<ComputedStyle> { // Needed to allow access to private/protected getters of fields to allow diff // generation - friend class ComputedStyleBase<ComputedStyle>; + friend class ComputedStyleBase; // Used by Web Animations CSS. Sets the color styles. friend class AnimatedStyleBuilder; // Used by Web Animations CSS. Gets visited and unvisited colors separately.
diff --git a/third_party/WebKit/Source/core/workers/BUILD.gn b/third_party/WebKit/Source/core/workers/BUILD.gn index ccc8e28..9d0197a 100644 --- a/third_party/WebKit/Source/core/workers/BUILD.gn +++ b/third_party/WebKit/Source/core/workers/BUILD.gn
@@ -45,6 +45,8 @@ "ThreadedWorkletMessagingProxy.h", "ThreadedWorkletObjectProxy.cpp", "ThreadedWorkletObjectProxy.h", + "WebSharedWorkerReportingProxyImpl.cpp", + "WebSharedWorkerReportingProxyImpl.h", "Worker.cpp", "Worker.h", "WorkerBackingThread.cpp",
diff --git a/third_party/WebKit/Source/core/workers/DedicatedWorkerTest.cpp b/third_party/WebKit/Source/core/workers/DedicatedWorkerTest.cpp index 2576eb79..7f2e21ed 100644 --- a/third_party/WebKit/Source/core/workers/DedicatedWorkerTest.cpp +++ b/third_party/WebKit/Source/core/workers/DedicatedWorkerTest.cpp
@@ -118,14 +118,6 @@ nullptr /* workerClients */) { worker_object_proxy_ = WTF::MakeUnique<InProcessWorkerObjectProxyForTest>( weak_ptr_factory_.CreateWeakPtr(), GetParentFrameTaskRunners()); - worker_thread_ = - WTF::MakeUnique<DedicatedWorkerThreadForTest>(WorkerObjectProxy()); - mock_worker_thread_lifecycle_observer_ = - new MockWorkerThreadLifecycleObserver( - worker_thread_->GetWorkerThreadLifecycleContext()); - EXPECT_CALL(*mock_worker_thread_lifecycle_observer_, - ContextDestroyed(::testing::_)) - .Times(1); } ~InProcessWorkerMessagingProxyForTest() override { @@ -143,7 +135,7 @@ WorkerV8Settings worker_v8_settings = WorkerV8Settings::Default(); worker_v8_settings.atomics_wait_mode_ = WorkerV8Settings::AtomicsWaitMode::kAllow; - GetWorkerThread()->Start( + InitializeWorkerThread( WorkerThreadStartupData::Create( script_url, "fake user agent", source, nullptr /* cachedMetaData */, kDontPauseWorkerGlobalScopeOnStart, headers.get(), @@ -151,11 +143,7 @@ nullptr /* workerClients */, kWebAddressSpaceLocal, nullptr /* originTrialTokens */, nullptr /* workerSettings */, worker_v8_settings), - GetParentFrameTaskRunners()); - - GetWorkerInspectorProxy()->WorkerThreadCreated( - ToDocument(GetExecutionContext()), worker_thread_.get(), script_url); - WorkerThreadCreated(); + script_url); } enum class Notification { @@ -204,8 +192,15 @@ std::unique_ptr<WorkerThread> CreateWorkerThread( double origin_time) override { - NOTREACHED(); - return nullptr; + auto worker_thread = + WTF::MakeUnique<DedicatedWorkerThreadForTest>(WorkerObjectProxy()); + mock_worker_thread_lifecycle_observer_ = + new MockWorkerThreadLifecycleObserver( + worker_thread->GetWorkerThreadLifecycleContext()); + EXPECT_CALL(*mock_worker_thread_lifecycle_observer_, + ContextDestroyed(::testing::_)) + .Times(1); + return std::move(worker_thread); } DedicatedWorkerThreadForTest* GetWorkerThread() {
diff --git a/third_party/WebKit/Source/core/workers/InProcessWorkerMessagingProxy.cpp b/third_party/WebKit/Source/core/workers/InProcessWorkerMessagingProxy.cpp index ec1b951e..217b718 100644 --- a/third_party/WebKit/Source/core/workers/InProcessWorkerMessagingProxy.cpp +++ b/third_party/WebKit/Source/core/workers/InProcessWorkerMessagingProxy.cpp
@@ -117,9 +117,7 @@ OriginTrialContext::GetTokens(document).get(), std::move(worker_settings), worker_v8_settings); - InitializeWorkerThread(std::move(startup_data)); - GetWorkerInspectorProxy()->WorkerThreadCreated(document, GetWorkerThread(), - script_url); + InitializeWorkerThread(std::move(startup_data), script_url); } void InProcessWorkerMessagingProxy::PostMessageToWorkerObject(
diff --git a/third_party/WebKit/Source/core/workers/ThreadedMessagingProxyBase.cpp b/third_party/WebKit/Source/core/workers/ThreadedMessagingProxyBase.cpp index 55ecb86..af0464f6 100644 --- a/third_party/WebKit/Source/core/workers/ThreadedMessagingProxyBase.cpp +++ b/third_party/WebKit/Source/core/workers/ThreadedMessagingProxyBase.cpp
@@ -66,13 +66,9 @@ return g_live_messaging_proxy_count; } -void ThreadedMessagingProxyBase::SetWorkerThreadForTest( - std::unique_ptr<WorkerThread> worker_thread) { - worker_thread_ = std::move(worker_thread); -} - void ThreadedMessagingProxyBase::InitializeWorkerThread( - std::unique_ptr<WorkerThreadStartupData> startup_data) { + std::unique_ptr<WorkerThreadStartupData> startup_data, + const KURL& script_url) { DCHECK(IsParentContextThread()); Document* document = ToDocument(GetExecutionContext()); @@ -84,6 +80,8 @@ worker_thread_ = CreateWorkerThread(origin_time); worker_thread_->Start(std::move(startup_data), GetParentFrameTaskRunners()); WorkerThreadCreated(); + GetWorkerInspectorProxy()->WorkerThreadCreated(document, GetWorkerThread(), + script_url); } ThreadableLoadingContext*
diff --git a/third_party/WebKit/Source/core/workers/ThreadedMessagingProxyBase.h b/third_party/WebKit/Source/core/workers/ThreadedMessagingProxyBase.h index 18f96ce9..261b219 100644 --- a/third_party/WebKit/Source/core/workers/ThreadedMessagingProxyBase.h +++ b/third_party/WebKit/Source/core/workers/ThreadedMessagingProxyBase.h
@@ -56,13 +56,12 @@ // Number of live messaging proxies, used by leak detection. static int ProxyCount(); - void SetWorkerThreadForTest(std::unique_ptr<WorkerThread>); - protected: ThreadedMessagingProxyBase(ExecutionContext*, WorkerClients*); virtual ~ThreadedMessagingProxyBase(); - void InitializeWorkerThread(std::unique_ptr<WorkerThreadStartupData>); + void InitializeWorkerThread(std::unique_ptr<WorkerThreadStartupData>, + const KURL& script_url); virtual std::unique_ptr<WorkerThread> CreateWorkerThread( double origin_time) = 0;
diff --git a/third_party/WebKit/Source/core/workers/ThreadedWorkletMessagingProxy.cpp b/third_party/WebKit/Source/core/workers/ThreadedWorkletMessagingProxy.cpp index 82381cf..ac5b7fd 100644 --- a/third_party/WebKit/Source/core/workers/ThreadedWorkletMessagingProxy.cpp +++ b/third_party/WebKit/Source/core/workers/ThreadedWorkletMessagingProxy.cpp
@@ -108,10 +108,7 @@ ReleaseWorkerClients(), document->AddressSpace(), OriginTrialContext::GetTokens(document).get(), std::move(worker_settings), WorkerV8Settings::Default()); - - InitializeWorkerThread(std::move(startup_data)); - GetWorkerInspectorProxy()->WorkerThreadCreated(document, GetWorkerThread(), - script_url); + InitializeWorkerThread(std::move(startup_data), script_url); } void ThreadedWorkletMessagingProxy::FetchAndInvokeScript(
diff --git a/third_party/WebKit/Source/core/workers/ThreadedWorkletTest.cpp b/third_party/WebKit/Source/core/workers/ThreadedWorkletTest.cpp index cfe7728..9e6360bc 100644 --- a/third_party/WebKit/Source/core/workers/ThreadedWorkletTest.cpp +++ b/third_party/WebKit/Source/core/workers/ThreadedWorkletTest.cpp
@@ -121,8 +121,6 @@ : ThreadedWorkletMessagingProxy(execution_context, worker_clients) { worklet_object_proxy_ = WTF::MakeUnique<ThreadedWorkletObjectProxyForTest>( weak_ptr_factory_.CreateWeakPtr(), GetParentFrameTaskRunners()); - worker_thread_ = - WTF::MakeUnique<ThreadedWorkletThreadForTest>(WorkletObjectProxy()); ThreadedWorkletThreadForTest::EnsureSharedBackingThread(); } @@ -140,7 +138,7 @@ WorkerClients* worker_clients = nullptr; Vector<String> origin_trial_tokens; std::unique_ptr<WorkerSettings> worker_settings = nullptr; - worker_thread_->Start( + InitializeWorkerThread( WorkerThreadStartupData::Create( script_url, "fake user agent", "// fake source code", std::move(cached_meta_data), kDontPauseWorkerGlobalScopeOnStart, @@ -148,15 +146,12 @@ security_origin_.Get(), worker_clients, kWebAddressSpaceLocal, &origin_trial_tokens, std::move(worker_settings), WorkerV8Settings::Default()), - GetParentFrameTaskRunners()); - GetWorkerInspectorProxy()->WorkerThreadCreated( - ToDocument(GetExecutionContext()), worker_thread_.get(), script_url); + script_url); } protected: std::unique_ptr<WorkerThread> CreateWorkerThread(double origin_time) final { - NOTREACHED(); - return nullptr; + return WTF::MakeUnique<ThreadedWorkletThreadForTest>(WorkletObjectProxy()); } private:
diff --git a/third_party/WebKit/Source/web/WebSharedWorkerReportingProxyImpl.cpp b/third_party/WebKit/Source/core/workers/WebSharedWorkerReportingProxyImpl.cpp similarity index 96% rename from third_party/WebKit/Source/web/WebSharedWorkerReportingProxyImpl.cpp rename to third_party/WebKit/Source/core/workers/WebSharedWorkerReportingProxyImpl.cpp index 1960336..e9564ad4 100644 --- a/third_party/WebKit/Source/web/WebSharedWorkerReportingProxyImpl.cpp +++ b/third_party/WebKit/Source/core/workers/WebSharedWorkerReportingProxyImpl.cpp
@@ -2,13 +2,13 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "web/WebSharedWorkerReportingProxyImpl.h" +#include "core/workers/WebSharedWorkerReportingProxyImpl.h" #include "bindings/core/v8/SourceLocation.h" +#include "core/exported/WebSharedWorkerImpl.h" #include "platform/CrossThreadFunctional.h" #include "platform/wtf/WTF.h" #include "public/platform/WebTraceLocation.h" -#include "web/WebSharedWorkerImpl.h" namespace blink {
diff --git a/third_party/WebKit/Source/web/WebSharedWorkerReportingProxyImpl.h b/third_party/WebKit/Source/core/workers/WebSharedWorkerReportingProxyImpl.h similarity index 100% rename from third_party/WebKit/Source/web/WebSharedWorkerReportingProxyImpl.h rename to third_party/WebKit/Source/core/workers/WebSharedWorkerReportingProxyImpl.h
diff --git a/third_party/WebKit/Source/modules/ModulesInitializer.cpp b/third_party/WebKit/Source/modules/ModulesInitializer.cpp index 2ada34d..d5b29eb 100644 --- a/third_party/WebKit/Source/modules/ModulesInitializer.cpp +++ b/third_party/WebKit/Source/modules/ModulesInitializer.cpp
@@ -8,10 +8,12 @@ #include "core/EventTypeNames.h" #include "core/css/CSSPaintImageGenerator.h" #include "core/dom/Document.h" +#include "core/exported/WebSharedWorkerImpl.h" #include "core/frame/LocalFrame.h" #include "core/html/HTMLCanvasElement.h" #include "core/html/HTMLMediaElement.h" #include "core/offscreencanvas/OffscreenCanvas.h" +#include "core/workers/WorkerContentSettingsClient.h" #include "modules/EventModulesFactory.h" #include "modules/EventModulesNames.h" #include "modules/EventTargetModulesNames.h" @@ -23,7 +25,9 @@ #include "modules/csspaint/CSSPaintImageGeneratorImpl.h" #include "modules/document_metadata/CopylessPasteServer.h" #include "modules/filesystem/DraggedIsolatedFileSystemImpl.h" +#include "modules/filesystem/LocalFileSystemClient.h" #include "modules/imagebitmap/ImageBitmapRenderingContext.h" +#include "modules/indexeddb/IndexedDBClientImpl.h" #include "modules/installation/InstallationServiceImpl.h" #include "modules/media_controls/MediaControlsImpl.h" #include "modules/offscreencanvas2d/OffscreenCanvasRenderingContext2D.h" @@ -34,6 +38,8 @@ #include "platform/mojo/MojoHelper.h" #include "platform/wtf/PtrUtil.h" #include "public/platform/InterfaceRegistry.h" +#include "public/platform/WebSecurityOrigin.h" +#include "public/web/WebWorkerContentSettingsClientProxy.h" namespace blink { @@ -97,6 +103,17 @@ &AppBannerController::BindMojoRequest, WrapWeakPersistent(frame))); }); + // WebSharedWorkerImpl callbacks for modules initialization. + // TODO(nhiroki): Implement a common mechanism to set up WorkerClients + // (https://crbug.com/729500). + WebSharedWorkerImpl::RegisterWorkerClientsCreatedCallback( + [](WorkerClients* worker_clients) { + ProvideLocalFileSystemToWorker(worker_clients, + LocalFileSystemClient::Create()); + ProvideIndexedDBClientToWorker( + worker_clients, IndexedDBClientImpl::Create(*worker_clients)); + }); + HTMLMediaElement::RegisterMediaControlsFactory( WTF::MakeUnique<MediaControlsImpl::Factory>());
diff --git a/third_party/WebKit/Source/modules/accessibility/AXObjectCacheImpl.cpp b/third_party/WebKit/Source/modules/accessibility/AXObjectCacheImpl.cpp index c977c2fa..6a356037 100644 --- a/third_party/WebKit/Source/modules/accessibility/AXObjectCacheImpl.cpp +++ b/third_party/WebKit/Source/modules/accessibility/AXObjectCacheImpl.cpp
@@ -1153,6 +1153,19 @@ HandleEditableTextContentChanged(node); } +void AXObjectCacheImpl::HandleTextMarkerDataAdded(Node* start, Node* end) { + AXObjectImpl* start_object = Get(start); + AXObjectImpl* end_object = Get(end); + if (!start_object || !end_object) + return; + + // Notify the client of new text marker data. + PostNotification(start_object, kAXChildrenChanged); + if (start_object != end_object) { + PostNotification(end_object, kAXChildrenChanged); + } +} + void AXObjectCacheImpl::HandleValueChanged(Node* node) { PostNotification(node, AXObjectCache::kAXValueChanged); }
diff --git a/third_party/WebKit/Source/modules/accessibility/AXObjectCacheImpl.h b/third_party/WebKit/Source/modules/accessibility/AXObjectCacheImpl.h index 4bdf909..d6e2aef 100644 --- a/third_party/WebKit/Source/modules/accessibility/AXObjectCacheImpl.h +++ b/third_party/WebKit/Source/modules/accessibility/AXObjectCacheImpl.h
@@ -89,6 +89,7 @@ void HandleInitialFocus() override; void HandleTextFormControlChanged(Node*) override; void HandleEditableTextContentChanged(Node*) override; + void HandleTextMarkerDataAdded(Node* start, Node* end) override; void HandleValueChanged(Node*) override; void HandleUpdateActiveMenuOption(LayoutMenuList*, int option_index) override; void DidShowMenuListPopup(LayoutMenuList*) override;
diff --git a/third_party/WebKit/Source/modules/app_banner/BeforeInstallPromptEvent.cpp b/third_party/WebKit/Source/modules/app_banner/BeforeInstallPromptEvent.cpp index 47d459e..83f42f34 100644 --- a/third_party/WebKit/Source/modules/app_banner/BeforeInstallPromptEvent.cpp +++ b/third_party/WebKit/Source/modules/app_banner/BeforeInstallPromptEvent.cpp
@@ -21,6 +21,7 @@ mojom::blink::AppBannerEventRequest event_request, const Vector<String>& platforms) : Event(name, false, true), + ContextClient(&frame), banner_service_(std::move(service_ptr)), binding_(this, std::move(event_request)), platforms_(platforms), @@ -34,14 +35,18 @@ } BeforeInstallPromptEvent::BeforeInstallPromptEvent( + ExecutionContext* execution_context, const AtomicString& name, const BeforeInstallPromptEventInit& init) - : Event(name, init), binding_(this), prompt_called_(false) { + : Event(name, init), + ContextClient(execution_context), + binding_(this), + prompt_called_(false) { if (init.hasPlatforms()) platforms_ = init.platforms(); } -BeforeInstallPromptEvent::~BeforeInstallPromptEvent() {} +BeforeInstallPromptEvent::~BeforeInstallPromptEvent() = default; void BeforeInstallPromptEvent::Dispose() { banner_service_.reset(); @@ -97,6 +102,11 @@ } } +bool BeforeInstallPromptEvent::HasPendingActivity() const { + return user_choice_ && + user_choice_->GetState() == ScriptPromisePropertyBase::kPending; +} + void BeforeInstallPromptEvent::BannerAccepted(const String& platform) { user_choice_->Resolve(AppBannerPromptResult::Create( platform, AppBannerPromptResult::Outcome::kAccepted)); @@ -110,6 +120,7 @@ DEFINE_TRACE(BeforeInstallPromptEvent) { visitor->Trace(user_choice_); Event::Trace(visitor); + ContextClient::Trace(visitor); } } // namespace blink
diff --git a/third_party/WebKit/Source/modules/app_banner/BeforeInstallPromptEvent.h b/third_party/WebKit/Source/modules/app_banner/BeforeInstallPromptEvent.h index e463f92..37469f0 100644 --- a/third_party/WebKit/Source/modules/app_banner/BeforeInstallPromptEvent.h +++ b/third_party/WebKit/Source/modules/app_banner/BeforeInstallPromptEvent.h
@@ -5,14 +5,16 @@ #ifndef BeforeInstallPromptEvent_h #define BeforeInstallPromptEvent_h +#include <utility> #include "bindings/core/v8/ScriptPromise.h" #include "bindings/core/v8/ScriptPromiseProperty.h" +#include "core/dom/ContextLifecycleObserver.h" #include "core/frame/LocalFrame.h" #include "modules/EventModules.h" #include "modules/app_banner/AppBannerPromptResult.h" #include "mojo/public/cpp/bindings/binding.h" +#include "platform/bindings/ActiveScriptWrappable.h" #include "public/platform/modules/app_banner/app_banner.mojom-blink.h" -#include <utility> namespace blink { @@ -24,10 +26,14 @@ Member<AppBannerPromptResult>, ToV8UndefinedGenerator>; -class BeforeInstallPromptEvent final : public Event, - public mojom::blink::AppBannerEvent { +class BeforeInstallPromptEvent final + : public Event, + public mojom::blink::AppBannerEvent, + public ActiveScriptWrappable<BeforeInstallPromptEvent>, + public ContextClient { DEFINE_WRAPPERTYPEINFO(); USING_PRE_FINALIZER(BeforeInstallPromptEvent, Dispose); + USING_GARBAGE_COLLECTED_MIXIN(BeforeInstallPromptEvent); public: ~BeforeInstallPromptEvent() override; @@ -43,9 +49,10 @@ } static BeforeInstallPromptEvent* Create( + ExecutionContext* execution_context, const AtomicString& name, const BeforeInstallPromptEventInit& init) { - return new BeforeInstallPromptEvent(name, init); + return new BeforeInstallPromptEvent(execution_context, name, init); } void Dispose(); @@ -57,6 +64,9 @@ const AtomicString& InterfaceName() const override; void preventDefault() override; + // ScriptWrappable + bool HasPendingActivity() const override; + DECLARE_VIRTUAL_TRACE(); private: @@ -65,7 +75,8 @@ mojom::blink::AppBannerServicePtr, mojom::blink::AppBannerEventRequest, const Vector<String>& platforms); - BeforeInstallPromptEvent(const AtomicString& name, + BeforeInstallPromptEvent(ExecutionContext*, + const AtomicString& name, const BeforeInstallPromptEventInit&); // mojom::blink::AppBannerEvent methods:
diff --git a/third_party/WebKit/Source/modules/app_banner/BeforeInstallPromptEvent.idl b/third_party/WebKit/Source/modules/app_banner/BeforeInstallPromptEvent.idl index d48bcde..987a4ced 100644 --- a/third_party/WebKit/Source/modules/app_banner/BeforeInstallPromptEvent.idl +++ b/third_party/WebKit/Source/modules/app_banner/BeforeInstallPromptEvent.idl
@@ -3,7 +3,10 @@ // found in the LICENSE file. [ - Constructor(DOMString type, optional BeforeInstallPromptEventInit eventInitDict) + ActiveScriptWrappable, + DependentLifetime, + Constructor(DOMString type, optional BeforeInstallPromptEventInit eventInitDict), + ConstructorCallWith=ExecutionContext, ] interface BeforeInstallPromptEvent : Event { readonly attribute FrozenArray<DOMString> platforms; [CallWith=ScriptState] readonly attribute Promise<AppBannerPromptResult> userChoice;
diff --git a/third_party/WebKit/Source/modules/filesystem/BUILD.gn b/third_party/WebKit/Source/modules/filesystem/BUILD.gn index 86c7cbb..cfa9326 100644 --- a/third_party/WebKit/Source/modules/filesystem/BUILD.gn +++ b/third_party/WebKit/Source/modules/filesystem/BUILD.gn
@@ -60,6 +60,8 @@ "HTMLInputElementFileSystem.h", "LocalFileSystem.cpp", "LocalFileSystem.h", + "LocalFileSystemClient.cpp", + "LocalFileSystemClient.h", "Metadata.h", "MetadataCallback.h", "SyncCallbackHelper.h",
diff --git a/third_party/WebKit/Source/web/LocalFileSystemClient.cpp b/third_party/WebKit/Source/modules/filesystem/LocalFileSystemClient.cpp similarity index 97% rename from third_party/WebKit/Source/web/LocalFileSystemClient.cpp rename to third_party/WebKit/Source/modules/filesystem/LocalFileSystemClient.cpp index cb92feaa..6b34d16 100644 --- a/third_party/WebKit/Source/web/LocalFileSystemClient.cpp +++ b/third_party/WebKit/Source/modules/filesystem/LocalFileSystemClient.cpp
@@ -28,7 +28,7 @@ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -#include "web/LocalFileSystemClient.h" +#include "modules/filesystem/LocalFileSystemClient.h" #include <memory> #include "core/dom/Document.h"
diff --git a/third_party/WebKit/Source/web/LocalFileSystemClient.h b/third_party/WebKit/Source/modules/filesystem/LocalFileSystemClient.h similarity index 95% rename from third_party/WebKit/Source/web/LocalFileSystemClient.h rename to third_party/WebKit/Source/modules/filesystem/LocalFileSystemClient.h index b728f80..e789630 100644 --- a/third_party/WebKit/Source/web/LocalFileSystemClient.h +++ b/third_party/WebKit/Source/modules/filesystem/LocalFileSystemClient.h
@@ -32,6 +32,7 @@ #define LocalFileSystemClient_h #include <memory> +#include "modules/ModulesExport.h" #include "modules/filesystem/FileSystemClient.h" #include "platform/wtf/Forward.h" @@ -39,7 +40,7 @@ class LocalFileSystemClient final : public FileSystemClient { public: - static std::unique_ptr<FileSystemClient> Create(); + MODULES_EXPORT static std::unique_ptr<FileSystemClient> Create(); ~LocalFileSystemClient() override;
diff --git a/third_party/WebKit/Source/modules/indexeddb/BUILD.gn b/third_party/WebKit/Source/modules/indexeddb/BUILD.gn index 29d5112..4d00467e 100644 --- a/third_party/WebKit/Source/modules/indexeddb/BUILD.gn +++ b/third_party/WebKit/Source/modules/indexeddb/BUILD.gn
@@ -61,6 +61,8 @@ "IndexedDB.h", "IndexedDBClient.cpp", "IndexedDBClient.h", + "IndexedDBClientImpl.cpp", + "IndexedDBClientImpl.h", "InspectorIndexedDBAgent.cpp", "InspectorIndexedDBAgent.h", "WebIDBCallbacksImpl.cpp",
diff --git a/third_party/WebKit/Source/web/IndexedDBClientImpl.cpp b/third_party/WebKit/Source/modules/indexeddb/IndexedDBClientImpl.cpp similarity index 98% rename from third_party/WebKit/Source/web/IndexedDBClientImpl.cpp rename to third_party/WebKit/Source/modules/indexeddb/IndexedDBClientImpl.cpp index 1931e4b..53c9328 100644 --- a/third_party/WebKit/Source/web/IndexedDBClientImpl.cpp +++ b/third_party/WebKit/Source/modules/indexeddb/IndexedDBClientImpl.cpp
@@ -26,7 +26,7 @@ * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -#include "web/IndexedDBClientImpl.h" +#include "modules/indexeddb/IndexedDBClientImpl.h" #include "bindings/core/v8/WorkerOrWorkletScriptController.h" #include "core/dom/Document.h"
diff --git a/third_party/WebKit/Source/web/IndexedDBClientImpl.h b/third_party/WebKit/Source/modules/indexeddb/IndexedDBClientImpl.h similarity index 93% rename from third_party/WebKit/Source/web/IndexedDBClientImpl.h rename to third_party/WebKit/Source/modules/indexeddb/IndexedDBClientImpl.h index 90b51a2..4a4d54fc 100644 --- a/third_party/WebKit/Source/web/IndexedDBClientImpl.h +++ b/third_party/WebKit/Source/modules/indexeddb/IndexedDBClientImpl.h
@@ -29,6 +29,7 @@ #ifndef IndexedDBClientImpl_h #define IndexedDBClientImpl_h +#include "modules/ModulesExport.h" #include "modules/indexeddb/IndexedDBClient.h" namespace blink { @@ -42,8 +43,8 @@ // for the main thread. class IndexedDBClientImpl final : public IndexedDBClient { public: - static IndexedDBClient* Create(LocalFrame&); - static IndexedDBClient* Create(WorkerClients&); + MODULES_EXPORT static IndexedDBClient* Create(LocalFrame&); + MODULES_EXPORT static IndexedDBClient* Create(WorkerClients&); bool AllowIndexedDB(ExecutionContext*, const String& name) override;
diff --git a/third_party/WebKit/Source/modules/presentation/PresentationRequest.cpp b/third_party/WebKit/Source/modules/presentation/PresentationRequest.cpp index 6b7ee90..8c02fd10 100644 --- a/third_party/WebKit/Source/modules/presentation/PresentationRequest.cpp +++ b/third_party/WebKit/Source/modules/presentation/PresentationRequest.cpp
@@ -109,7 +109,14 @@ bool PresentationRequest::HasPendingActivity() const { // Prevents garbage collecting of this object when not hold by another // object but still has listeners registered. - return GetExecutionContext() && HasEventListeners(); + if (!GetExecutionContext()) + return false; + + if (HasEventListeners()) + return true; + + return availability_property_ && availability_property_->GetState() == + ScriptPromisePropertyBase::kPending; } ScriptPromise PresentationRequest::start(ScriptState* script_state) {
diff --git a/third_party/WebKit/Source/web/BUILD.gn b/third_party/WebKit/Source/web/BUILD.gn index 473df22..758d62fe 100644 --- a/third_party/WebKit/Source/web/BUILD.gn +++ b/third_party/WebKit/Source/web/BUILD.gn
@@ -55,14 +55,10 @@ "ExternalPopupMenu.h", "FullscreenController.cpp", "FullscreenController.h", - "IndexedDBClientImpl.cpp", - "IndexedDBClientImpl.h", "InspectorOverlayAgent.cpp", "InspectorOverlayAgent.h", "LinkHighlightImpl.cpp", "LinkHighlightImpl.h", - "LocalFileSystemClient.cpp", - "LocalFileSystemClient.h", "LocalFrameClientImpl.cpp", "LocalFrameClientImpl.h", "MediaKeysClientImpl.cpp", @@ -134,10 +130,6 @@ "WebRemoteFrameImpl.h", "WebScopedWindowFocusAllowedIndicator.cpp", "WebSearchableFormData.cpp", - "WebSharedWorkerImpl.cpp", - "WebSharedWorkerImpl.h", - "WebSharedWorkerReportingProxyImpl.cpp", - "WebSharedWorkerReportingProxyImpl.h", "WebSurroundingText.cpp", "WebViewImpl.cpp", "WebViewImpl.h",
diff --git a/third_party/WebKit/Source/web/ChromeClientImpl.cpp b/third_party/WebKit/Source/web/ChromeClientImpl.cpp index 074e1b76..1c908e10 100644 --- a/third_party/WebKit/Source/web/ChromeClientImpl.cpp +++ b/third_party/WebKit/Source/web/ChromeClientImpl.cpp
@@ -65,6 +65,8 @@ #include "modules/accessibility/AXObjectImpl.h" #include "modules/audio_output_devices/AudioOutputDeviceClient.h" #include "modules/audio_output_devices/AudioOutputDeviceClientImpl.h" +#include "modules/filesystem/LocalFileSystemClient.h" +#include "modules/indexeddb/IndexedDBClientImpl.h" #include "modules/installedapp/InstalledAppController.h" #include "modules/mediastream/UserMediaController.h" #include "modules/navigatorcontentutils/NavigatorContentUtils.h" @@ -117,8 +119,6 @@ #include "web/ColorChooserUIController.h" #include "web/ExternalDateTimeChooser.h" #include "web/ExternalPopupMenu.h" -#include "web/IndexedDBClientImpl.h" -#include "web/LocalFileSystemClient.h" #include "web/NavigatorContentUtilsClientImpl.h" #include "web/PopupMenuImpl.h" #include "web/WebFrameWidgetImpl.h"
diff --git a/third_party/WebKit/Source/web/DedicatedWorkerMessagingProxyProviderImpl.cpp b/third_party/WebKit/Source/web/DedicatedWorkerMessagingProxyProviderImpl.cpp index 6f8c9c5..e59ed63 100644 --- a/third_party/WebKit/Source/web/DedicatedWorkerMessagingProxyProviderImpl.cpp +++ b/third_party/WebKit/Source/web/DedicatedWorkerMessagingProxyProviderImpl.cpp
@@ -38,14 +38,14 @@ #include "core/workers/Worker.h" #include "core/workers/WorkerClients.h" #include "core/workers/WorkerContentSettingsClient.h" +#include "modules/filesystem/LocalFileSystemClient.h" +#include "modules/indexeddb/IndexedDBClientImpl.h" #include "platform/wtf/PtrUtil.h" #include "public/platform/Platform.h" #include "public/platform/WebContentSettingsClient.h" #include "public/platform/WebString.h" #include "public/web/WebFrameClient.h" #include "public/web/WebWorkerContentSettingsClientProxy.h" -#include "web/IndexedDBClientImpl.h" -#include "web/LocalFileSystemClient.h" namespace blink {
diff --git a/third_party/WebKit/Source/web/TextFinder.cpp b/third_party/WebKit/Source/web/TextFinder.cpp index 7032e85e..d192da5 100644 --- a/third_party/WebKit/Source/web/TextFinder.cpp +++ b/third_party/WebKit/Source/web/TextFinder.cpp
@@ -30,6 +30,7 @@ #include "web/TextFinder.h" +#include "core/dom/AXObjectCacheBase.h" #include "core/dom/Range.h" #include "core/dom/TaskRunnerHelper.h" #include "core/dom/shadow/ShadowRoot.h" @@ -45,8 +46,6 @@ #include "core/layout/LayoutObject.h" #include "core/layout/TextAutosizer.h" #include "core/page/Page.h" -#include "modules/accessibility/AXObjectCacheImpl.h" -#include "modules/accessibility/AXObjectImpl.h" #include "platform/RuntimeEnabledFeatures.h" #include "platform/Timer.h" #include "platform/wtf/CurrentTime.h" @@ -58,6 +57,8 @@ namespace blink { +class AXObjectImpl; + TextFinder::FindMatch::FindMatch(Range* range, int ordinal) : range_(range), ordinal_(ordinal) {} @@ -247,26 +248,18 @@ if (!active_match_) return; - AXObjectCacheImpl* ax_object_cache = ToAXObjectCacheImpl( + AXObjectCacheBase* ax_object_cache = ToAXObjectCacheBase( OwnerFrame().GetFrame()->GetDocument()->ExistingAXObjectCache()); if (!ax_object_cache) return; - AXObjectImpl* start_object = - ax_object_cache->Get(active_match_->startContainer()); - AXObjectImpl* end_object = - ax_object_cache->Get(active_match_->endContainer()); - if (!start_object || !end_object) - return; - - // Notify the client of new text marker data. - ax_object_cache->PostNotification( - start_object, AXObjectCache::AXNotification::kAXChildrenChanged); - if (start_object != end_object) - ax_object_cache->PostNotification( - end_object, AXObjectCache::AXNotification::kAXChildrenChanged); + Node* start_node = active_match_->startContainer(); + Node* end_node = active_match_->endContainer(); + ax_object_cache->HandleTextMarkerDataAdded(start_node, end_node); if (OwnerFrame().Client()) { + AXObjectImpl* start_object = ax_object_cache->Get(start_node); + AXObjectImpl* end_object = ax_object_cache->Get(end_node); OwnerFrame().Client()->HandleAccessibilityFindInPageResult( identifier, active_match_index_ + 1, WebAXObject(start_object), active_match_->startOffset(), WebAXObject(end_object),
diff --git a/third_party/WebKit/Source/web/WebEmbeddedWorkerImpl.cpp b/third_party/WebKit/Source/web/WebEmbeddedWorkerImpl.cpp index 6a73fe3f..93faa6e4 100644 --- a/third_party/WebKit/Source/web/WebEmbeddedWorkerImpl.cpp +++ b/third_party/WebKit/Source/web/WebEmbeddedWorkerImpl.cpp
@@ -50,6 +50,7 @@ #include "core/workers/WorkerInspectorProxy.h" #include "core/workers/WorkerScriptLoader.h" #include "core/workers/WorkerThreadStartupData.h" +#include "modules/indexeddb/IndexedDBClientImpl.h" #include "modules/serviceworkers/ServiceWorkerContainerClient.h" #include "modules/serviceworkers/ServiceWorkerThread.h" #include "platform/Histogram.h" @@ -74,7 +75,6 @@ #include "public/web/WebView.h" #include "public/web/WebWorkerContentSettingsClientProxy.h" #include "public/web/modules/serviceworker/WebServiceWorkerContextClient.h" -#include "web/IndexedDBClientImpl.h" #include "web/ServiceWorkerGlobalScopeClientImpl.h" #include "web/ServiceWorkerGlobalScopeProxy.h"
diff --git a/third_party/WebKit/Source/web/WebFactoryImpl.cpp b/third_party/WebKit/Source/web/WebFactoryImpl.cpp index 779e1727..66230e3 100644 --- a/third_party/WebKit/Source/web/WebFactoryImpl.cpp +++ b/third_party/WebKit/Source/web/WebFactoryImpl.cpp
@@ -4,6 +4,7 @@ #include "web/WebFactoryImpl.h" #include "web/ChromeClientImpl.h" +#include "web/WebLocalFrameImpl.h" #include "web/WebViewImpl.h" namespace blink { @@ -21,4 +22,13 @@ WebPageVisibilityState state) const { return WebViewImpl::Create(client, state); } + +WebLocalFrameBase* WebFactoryImpl::CreateWebLocalFrameBase( + WebTreeScopeType type, + WebFrameClient* client, + blink::InterfaceProvider* provider, + blink::InterfaceRegistry* registry, + WebFrame* opener) const { + return WebLocalFrameImpl::Create(type, client, provider, registry, opener); +} }
diff --git a/third_party/WebKit/Source/web/WebFactoryImpl.h b/third_party/WebKit/Source/web/WebFactoryImpl.h index 4d13eae2..732a9500 100644 --- a/third_party/WebKit/Source/web/WebFactoryImpl.h +++ b/third_party/WebKit/Source/web/WebFactoryImpl.h
@@ -20,6 +20,12 @@ ChromeClient* CreateChromeClient(WebViewBase*) const override; WebViewBase* CreateWebViewBase(WebViewClient*, WebPageVisibilityState) const override; + WebLocalFrameBase* CreateWebLocalFrameBase( + WebTreeScopeType, + WebFrameClient*, + blink::InterfaceProvider*, + blink::InterfaceRegistry*, + WebFrame* opener = nullptr) const override; }; } // namespace blink
diff --git a/third_party/WebKit/Tools/Scripts/webkitpy/layout_tests/controllers/manager.py b/third_party/WebKit/Tools/Scripts/webkitpy/layout_tests/controllers/manager.py index 95c34cc..b2b67e3 100644 --- a/third_party/WebKit/Tools/Scripts/webkitpy/layout_tests/controllers/manager.py +++ b/third_party/WebKit/Tools/Scripts/webkitpy/layout_tests/controllers/manager.py
@@ -128,7 +128,7 @@ tests_to_run, tests_to_skip = self._prepare_lists(paths, test_names) - self._expectations.remove_tests(tests_in_other_chunks) + self._expectations.remove_tests_from_expectations(tests_in_other_chunks) self._printer.print_found( len(all_test_names), len(test_names), len(tests_to_run),
diff --git a/third_party/WebKit/Tools/Scripts/webkitpy/layout_tests/models/test_expectations.py b/third_party/WebKit/Tools/Scripts/webkitpy/layout_tests/models/test_expectations.py index 567c80e..e43b247 100644 --- a/third_party/WebKit/Tools/Scripts/webkitpy/layout_tests/models/test_expectations.py +++ b/third_party/WebKit/Tools/Scripts/webkitpy/layout_tests/models/test_expectations.py
@@ -250,7 +250,8 @@ self.name, self.matching_configurations, self.original_string) def __eq__(self, other): - return (self.original_string == other.original_string + return (isinstance(other, self.__class__) + and self.original_string == other.original_string and self.filename == other.filename and self.line_numbers == other.line_numbers and self.name == other.name @@ -695,7 +696,7 @@ raise ValueError(expectation) def remove_expectation_line(self, test): - if not self.has_test(test): + if not self.has_test(test.name): return self._clear_expectations_for_test(test) del self._test_to_expectation_line[test] @@ -1180,10 +1181,17 @@ model.add_expectation_line(expectation_line) self._model.merge_model(model) - def remove_tests(self, tests_to_remove): + def remove_tests_from_expectations(self, tests_to_remove): for test in self._expectations: - if test.name and test.name in tests_to_remove: - self.remove_expectation_line(test) + if not test.name: + continue + if test.name not in tests_to_remove: + continue + self._expectations.remove(test) + if not self._model.has_test(test.name): + continue + line = self._model.get_expectation_line(test.name) + self._model.remove_expectation_line(line) def add_expectations_from_bot(self): # FIXME: With mode 'very-flaky' and 'maybe-flaky', this will show the expectations entry in the flakiness @@ -1201,12 +1209,6 @@ self._model.add_expectation_line(expectation_line) self._expectations += [expectation_line] - def remove_expectation_line(self, test): - if not self._model.has_test(test): - return - self._expectations.remove(self._model.get_expectation_line(test)) - self._model.remove_expectation_line(test) - @staticmethod def list_to_string(expectation_lines, test_configuration_converter=None, reconstitute_only_these=None): def serialize(expectation_line):
diff --git a/third_party/WebKit/public/BUILD.gn b/third_party/WebKit/public/BUILD.gn index f2aacc44..b3691d47 100644 --- a/third_party/WebKit/public/BUILD.gn +++ b/third_party/WebKit/public/BUILD.gn
@@ -683,7 +683,7 @@ html_min_css = "$blink_core_output_dir/html.css" grit_flags = [ "-E", - "html_min_css=" + rebase_path(html_min_css), + "html_min_css=" + rebase_path(html_min_css, "."), ] deps = [ "//third_party/WebKit/Source/core:make_minimized_css",
diff --git a/third_party/WebKit/public/web/WebFrame.h b/third_party/WebKit/public/web/WebFrame.h index e141023..dcf4dd1 100644 --- a/third_party/WebKit/public/web/WebFrame.h +++ b/third_party/WebKit/public/web/WebFrame.h
@@ -195,7 +195,10 @@ void ClearOpener() { SetOpener(0); } // Returns the parent frame or 0 if this is a top-most frame. - BLINK_EXPORT WebFrame* Parent() const; + // TODO(sashab): "Virtual" is needed here temporarily to resolve linker errors + // in core/. Remove the "virtual" keyword once WebFrame and WebLocalFrameImpl + // have been moved to core/. + BLINK_EXPORT virtual WebFrame* Parent() const; // Returns the top-most frame in the hierarchy containing this frame. BLINK_EXPORT WebFrame* Top() const;
diff --git a/third_party/brotli/BUILD.gn b/third_party/brotli/BUILD.gn index 7e7db4a6..d094ad5 100644 --- a/third_party/brotli/BUILD.gn +++ b/third_party/brotli/BUILD.gn
@@ -21,47 +21,64 @@ ] } +common_sources = [ + "common/constants.h", + "common/dictionary.c", + "common/dictionary.h", + "common/version.h", +] + static_library("common") { - sources = [ - "common/constants.h", - "common/dictionary.c", - "common/dictionary.h", - "common/version.h", - ] + sources = common_sources public_configs = [ ":includes" ] - deps = [ - ":headers", - ] + deps = [ ":headers" ] } -static_library("dec") { - sources = [ - "dec/bit_reader.c", - "dec/bit_reader.h", - "dec/context.h", - "dec/decode.c", - "dec/huffman.c", - "dec/huffman.h", - "dec/port.h", - "dec/prefix.h", - "dec/state.c", - "dec/state.h", - "dec/transform.h", - ] +static_library("common_no_dictionary_data") { + sources = common_sources public_configs = [ ":includes" ] + deps = [ ":headers" ] + defines = ["BROTLI_EXTERNAL_DICTIONARY_DATA"] +} - public_deps = [ - ":headers", - ] +dec_sources = [ + "dec/bit_reader.c", + "dec/bit_reader.h", + "dec/context.h", + "dec/decode.c", + "dec/huffman.c", + "dec/huffman.h", + "dec/port.h", + "dec/prefix.h", + "dec/state.c", + "dec/state.h", + "dec/transform.h", +] - deps = [ - ":common", - ] +static_library("dec") { + sources = dec_sources + public_configs = [ ":includes" ] + public_deps = [ ":headers" ] + deps = [ ":common" ] configs -= [ "//build/config/compiler:chromium_code" ] configs += [ "//build/config/compiler:no_chromium_code" ] - # Since we are never debug brotli, freeze the optimizations to -O2. + # Since we never debug brotli, freeze the optimizations to -O2. + configs -= [ "//build/config/compiler:default_optimization" ] + configs += [ "//build/config/compiler:optimize_max" ] +} + +static_library("dec_no_dictionary_data") { + sources = dec_sources + public_configs = [ ":includes" ] + public_deps = [ ":headers" ] + deps = [ ":common_no_dictionary_data" ] + + configs -= [ "//build/config/compiler:chromium_code" ] + configs += [ "//build/config/compiler:no_chromium_code" ] + + # Since we never debug brotli, freeze the optimizations to -O2. configs -= [ "//build/config/compiler:default_optimization" ] configs += [ "//build/config/compiler:optimize_max" ] }
diff --git a/third_party/google_input_tools/closure.gni b/third_party/google_input_tools/closure.gni index ea8fe83..74128440 100644 --- a/third_party/google_input_tools/closure.gni +++ b/third_party/google_input_tools/closure.gni
@@ -34,7 +34,7 @@ if (defined(invoker.path)) { args += [ "--path", - invoker.path, + rebase_path(invoker.path, root_build_dir), ] } }
diff --git a/ui/arc/notification/arc_notification_content_view.cc b/ui/arc/notification/arc_notification_content_view.cc index 824f337..4469fc34 100644 --- a/ui/arc/notification/arc_notification_content_view.cc +++ b/ui/arc/notification/arc_notification_content_view.cc
@@ -361,8 +361,6 @@ surface_->window()->AddObserver(this); surface_->window()->AddPreTargetHandler(event_forwarder_.get()); - MaybeCreateFloatingControlButtons(); - if (GetWidget()) AttachSurface(); } @@ -389,22 +387,9 @@ } void ArcNotificationContentView::UpdateControlButtonsVisibility() { - if (!surface_) + if (!floating_control_buttons_widget_) return; - // TODO(edcourtney, yhanada): Creating the floating control widget here is not - // correct. This function may be called during the destruction of - // |floating_control_buttons_widget_|. This can lead to memory corruption. - // Rather than creating it here, we should fix the behaviour of OnMouseExited - // and OnMouseEntered for ARC notifications in MessageCenterView. See - // crbug.com/714587 and crbug.com/709862. - if (!floating_control_buttons_widget_) { - // This may update |floating_control_buttons_widget_|. - MaybeCreateFloatingControlButtons(); - if (!floating_control_buttons_widget_) - return; - } - const bool target_visiblity = IsMouseHovered() || (close_button_ && close_button_->HasFocus()) || (settings_button_ && settings_button_->HasFocus()); @@ -421,6 +406,10 @@ if (!item_) return; + // Surface is not attached yet. + if (!control_buttons_view_) + return; + if (item_->GetPinned() && close_button_) { control_buttons_view_->RemoveChildView(close_button_.get()); close_button_.reset(); @@ -458,10 +447,8 @@ // Invokes Update() in case surface is attached during a slide. slide_helper_->Update(); - // Updates pinned state to create or destroy the floating close button - // after |surface_| is attached to a widget. - if (item_) - UpdatePinnedState(); + // (Re-)create the floating buttons after |surface_| is attached to a widget. + MaybeCreateFloatingControlButtons(); } void ArcNotificationContentView::StartControlButtonsColorAnimation() {